Merge main into fix/svg-export-confined-image-links

# Conflicts:
#	crates/engine/src/cmd/fileio/commands.rs
This commit is contained in:
dotCooCoo
2026-11-14 15:17:48 -08:00
267 changed files with 19313 additions and 3476 deletions
+5
View File
@@ -31,3 +31,8 @@ jobs:
require-craft-fonts: true
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
run-package-check: true
# The test builds of this workspace's largest crates (engine, ui-egui) need more than the
# VM's 12 GB when two compile at once: the build was killed (exit 137) every night with
# four jobs and again with two. One rustc at a time; it still uses every core.
cargo-build-extra-args: "-j 1"
cargo-test-extra-args: "-j 1"
Generated
+12
View File
@@ -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",
+2
View File
@@ -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" }
+1
View File
@@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
+75 -8
View File
@@ -17,7 +17,8 @@
//! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at
//! once; a paste then waits for that read's answer off the UI thread.
//! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS,
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text).
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). A
//! file of more than 64 MiB is skipped before it is read.
use std::io::{Cursor, Read};
use std::path::PathBuf;
@@ -144,9 +145,18 @@ fn dib_image(dib: &[u8]) -> Option<image::RgbaImage> {
Some(img)
}
/// The most bytes a paste takes from another app (untrusted data), VectorCraft's own limit: a copied
/// file of more is skipped, and on Wayland a read of more fails.
const MAX_BYTES: usize = 64 << 20;
/// The first of `paths` (files copied in a file manager) that pastes as one of `mimes`, read
/// whole. Only its first bytes are read to tell, so other files cost little.
/// whole, at most [`MAX_BYTES`]. Only its first bytes are read to tell, so other files cost little.
fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
copied_file_within(paths, mimes, MAX_BYTES)
}
/// [`copied_file`] with a file of more than `limit` bytes skipped.
fn copied_file_within(paths: Vec<PathBuf>, mimes: &[&'static str], limit: usize) -> Option<Flavour> {
paths.into_iter().find_map(|path| {
// text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only.
let path = match path.to_str() {
@@ -164,14 +174,29 @@ fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
if !std::fs::metadata(&path).ok()?.is_file() {
return None;
}
let mut file = std::fs::File::open(&path).ok()?;
// The file opened may not be the one looked at: its size is checked before any read.
let meta = file.metadata().ok()?;
if !meta.is_file() || meta.len() > limit as u64 {
return None;
}
let mut head = Vec::with_capacity(FILE_HEAD);
std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?;
(&mut file).take(FILE_HEAD as u64).read_to_end(&mut head).ok()?;
let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?;
let data = std::fs::read(&path).ok()?;
let data = read_rest(file, head, limit)?;
(!data.is_empty()).then_some(Flavour { mime, data })
})
}
/// `data` (the first bytes read of `file`) followed by the rest of `file`, or `None` when they come
/// to more than `limit` bytes, as when the file grew after its size was checked. At most one byte
/// past `limit` is read.
fn read_rest(file: impl Read, mut data: Vec<u8>, limit: usize) -> Option<Vec<u8>> {
let more = (limit + 1).saturating_sub(data.len());
file.take(more as u64).read_to_end(&mut data).ok()?;
(data.len() <= limit).then_some(data)
}
/// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted
/// data) names no files.
const MAX_URIS: usize = 1024;
@@ -1900,7 +1925,7 @@ mod wayland {
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
use super::{BITMAP, Flavour, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths};
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths};
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
/// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`.
@@ -1911,9 +1936,6 @@ mod wayland {
/// best first: `text/uri-list` (RFC 2483), and GNOME Files' own list, read only when the first
/// names no file.
const FILE_LISTS: [(&str, PathsOf); 2] = [("text/uri-list", uri_list_paths), ("x-special/gnome-copied-files", gnome_copied_paths)];
/// The most bytes a read takes from the app that copied (untrusted data), VectorCraft's own
/// limit: a read of more fails.
const MAX_BYTES: usize = 64 << 20;
/// The most pastes of a Copy's data that are sent at once; a paste beyond them gets nothing.
const MAX_SENDS: usize = 8;
/// The most types of an offer that are kept (untrusted data).
@@ -3176,6 +3198,51 @@ mod tests {
assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG));
}
/// A copied file of more than 64 MiB is skipped before it is read, and the next one pastes.
#[test]
fn an_oversized_copied_file_is_skipped_before_it_is_read() {
let d = dir("oversized");
let (big, small) = (d.path().join("big.png"), d.path().join("small.png"));
std::fs::write(&big, png(2, 2)).unwrap();
// Sparse where the file system allows: no 64 MiB is written.
std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(MAX_BYTES as u64 + 1).unwrap();
std::fs::write(&small, png(3, 2)).unwrap();
assert!(copied_file(vec![big.clone()], &PASTE_ORDER).is_none());
let f = copied_file(vec![big, small], &PASTE_ORDER).unwrap();
assert_eq!((f.mime, f.data), (PNG, png(3, 2)));
}
/// A copied file of exactly the limit pastes; one byte more and it is skipped.
#[test]
fn a_copied_file_pastes_up_to_the_limit() {
let d = dir("limit");
let art = d.path().join("art.svg");
let svg = "<svg xmlns=\"http://www.w3.org/2000/svg\"/>";
std::fs::write(&art, svg).unwrap();
let read = |limit| copied_file_within(vec![art.clone()], &PASTE_ORDER, limit).map(|f| f.data);
assert_eq!(read(svg.len()), Some(svg.as_bytes().to_vec()));
assert_eq!(read(svg.len() - 1), None);
}
/// A file that grows past the limit after its size was checked is read to one byte past the
/// limit and refused.
#[test]
fn the_rest_of_a_file_is_read_to_the_limit_at_most() {
let read = |len: usize, head: usize| {
let bytes = vec![7u8; len];
let mut file = Cursor::new(bytes);
let mut first = vec![0; head];
file.read_exact(&mut first).unwrap();
(read_rest(&mut file, first, 16).map(|d| d.len()), file.position())
};
assert_eq!(read(16, 4), (Some(16), 16));
assert_eq!(read(0, 0), (Some(0), 0));
assert_eq!(read(17, 4), (None, 17));
assert_eq!(read(1000, 4), (None, 17));
// First bytes already past the limit: nothing more is read.
assert_eq!(read(1000, 20), (None, 20));
}
fn uri_paths(list: &[u8]) -> Vec<String> {
uri_list_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect()
}
+20
View File
@@ -1024,6 +1024,26 @@ fn overlaps(a: Rect, b: Rect) -> bool {
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
}
/// Whether a plot draws nothing of `n` wherever it is, apart from what every export leaves out
/// (hidden objects, guides and template layers): an object at 0% opacity, a non-printing layer, a
/// placed image, a gradient mesh whose every point is at 0% opacity, or a path or compound path
/// without effects whose fills and strokes paint nothing. An image or a mesh in `doc` with a
/// visible Crop Marks effect, or with a Vector Halftone effect that makes dots, is not one of them.
/// A clipping path still clips when the plot draws nothing of it.
pub fn plots_nothing(doc: &Document, n: &Node) -> bool {
let unpainted = || n.appearance.effects.is_empty() && top_stroke(n).is_none() && top_fill(n).is_none();
let dots = || vectorcraft_effects::addons::halftone::halftone_art(doc, n).is_some_and(|g| g.children().is_some_and(|c| !c.is_empty()));
let adds_art = || vectorcraft_effects::has_crop_marks(n) || dots();
n.opacity <= 0.0
|| match &n.kind {
NodeKind::Layer { printable, .. } => !printable,
NodeKind::Image(_) => !adds_art(),
NodeKind::Mesh(m) => !adds_art() && m.points.iter().all(|p| p.opacity <= 0.0),
NodeKind::Path { .. } | NodeKind::Compound { .. } => unpainted(),
_ => false,
}
}
/// `nodes` (the children of a clipping container when `clipping`) without the layers and
/// sublayers a plot leaves out (hidden, non-printing, template or at 0% opacity) and without
/// guides, in layers and groups at any depth, so that baking can't wrap one in art that is drawn
+84
View File
@@ -177,6 +177,90 @@ fn meshes_in_blends_are_outlines_and_clear_meshes_draw_nothing() {
assert_eq!(t.matches("PD").count(), 3, "{t}");
}
/// `plots_nothing` picks the objects and layers that a plot draws nothing of: a path that paints
/// nothing, objects at 0% opacity, placed images, meshes with every point at 0% opacity and
/// non-printing layers, and not a painted path or a mesh.
#[test]
fn plots_nothing_picks_what_a_plot_draws_nothing_of() {
type Make = fn(&mut Document) -> Node;
let cases: [(&str, Make, bool); 7] = [
("stroked", |d| stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK), false),
("unpainted", |d| Node::path(d.alloc_id(), rect(10.0, 10.0, 40.0, 40.0), Appearance::basic(Paint::None, Paint::None, 1.0)), true),
(
"clear",
|d| {
let mut n = filled(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK);
n.opacity = 0.0;
n
},
true,
),
(
"image",
|d| {
let image = vectorcraft_doc::ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)))
},
true,
),
(
"image with Crop Marks",
|d| {
let image = vectorcraft_doc::ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
n.appearance.effects.push(vectorcraft_doc::Effect { id: "cropMarks".into(), params: serde_json::json!({}), visible: true });
n
},
false,
),
("mesh", |d| Node::new(d.alloc_id(), NodeKind::Mesh(mesh_at(10.0))), false),
(
"clear mesh",
|d| {
let mut clear = mesh_at(10.0);
clear.points.iter_mut().for_each(|p| p.opacity = 0.0);
Node::new(d.alloc_id(), NodeKind::Mesh(clear))
},
true,
),
];
for (name, make, nothing) in cases {
let mut held = None;
let d = doc_with(|d| {
let n = make(d);
held = Some(n.clone());
vec![n]
});
let Some(n) = held else { panic!("{name}") };
assert_eq!(plots_nothing(&d, &n), nothing, "{name}");
assert_eq!(text(&plot(&d, &opts(&d))) == "IN;PU;SP0;", nothing, "{name}");
}
let mut d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK)]);
let layer = d.layers[0].id;
assert!(!plots_nothing(&d, &d.layers[0]));
if let Some(NodeKind::Layer { printable, .. }) = d.node_mut(layer).map(|n| &mut n.kind) {
*printable = false;
}
assert!(plots_nothing(&d, &d.layers[0]));
assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;");
}
/// Live art that makes more objects than the plot's limit (1,000 in tests) is left out with a
/// warning.
#[test]
+4
View File
@@ -8,6 +8,10 @@ description = "VectorCraft document model: artboards, layers, objects, appearanc
[lints]
workspace = true
[features]
# `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only).
spine-count = []
[dependencies]
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
+450 -18
View File
@@ -19,11 +19,11 @@
use std::f64::consts::PI;
use std::sync::Arc;
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint};
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeLayer, WidthProfile};
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile};
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
use crate::node::{Node, NodeId, NodeKind};
use crate::text::TextObject;
@@ -79,7 +79,11 @@ fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) ->
/// of the two stops around `t` at the tint and plates between theirs (unlinked when they differ),
/// as [`Gradient::sample_with`] walks.
fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
let stops = &g.stops;
link_in(&g.stops, t)
}
/// [`link_at`] of a gradient's `stops`.
fn link_in(stops: &[GradientStop], t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
let link = |s: &GradientStop| (s.swatch.clone(), s.tint, s.plates);
let Some(first) = stops.first() else { return (None, 1.0, None) };
if t <= first.offset {
@@ -103,15 +107,32 @@ fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
stops.last().map_or((None, 1.0, None), link)
}
/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred).
/// How close two places a gradient changes are for [`common_stops`] to give them one stop (two
/// where either gradient steps there: two of its stops at the same offset).
const STEP: f32 = 1e-4;
/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred). An
/// offset given twice is a step: the second stop paints what `g` steps to there (the last of its
/// stops at one offset within [`STEP`] of it), or what it paints there when it does not step.
fn resample_stops(g: &Gradient, offsets: &[f32]) -> Gradient {
let mut out = g.clone();
out.stops = offsets
.iter()
.map(|&o| {
let (color, opacity) = g.sample_keep_model(o);
let (swatch, tint, plates) = link_at(g, o);
GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) }
.enumerate()
.map(|(i, &o)| {
let after = i.checked_sub(1).and_then(|j| offsets.get(j)) == Some(&o);
let stepped =
if after { g.stops.windows(2).rfind(|w| w[0].offset == w[1].offset && (w[0].offset - o).abs() < STEP).map(|w| &w[1]) } else { None };
match stepped {
Some(s) => {
GradientStop { opacity: s.opacity, swatch: s.swatch.clone(), tint: s.tint, plates: s.plates, ..GradientStop::new(o, s.color) }
}
None => {
let (color, opacity) = g.sample_keep_model(o);
let (swatch, tint, plates) = link_at(g, o);
GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) }
}
}
})
.collect();
out
@@ -130,7 +151,7 @@ fn gradient_breaks(g: &Gradient, out: &mut Vec<f32>) {
}
/// Two gradients of one kind with the same number of stops: as they are when the counts match,
/// else both resampled at every place either changes.
/// else both resampled at every place either changes, with two stops where either steps.
fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> {
if a.kind != b.kind {
return None;
@@ -146,8 +167,22 @@ fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> {
gradient_breaks(b, &mut offs);
offs.retain(|o| o.is_finite());
offs.sort_by(f32::total_cmp);
offs.dedup_by(|x, y| (*x - *y).abs() < 1e-4);
Some((resample_stops(a, &offs), resample_stops(b, &offs)))
offs.dedup_by(|x, y| (*x - *y).abs() < STEP);
let mut steps: Vec<f32> =
[a, b].into_iter().flat_map(|g| g.stops.windows(2).filter(|w| w[1].offset == w[0].offset).map(|w| w[0].offset)).collect();
steps.sort_by(f32::total_cmp);
let mut at = Vec::with_capacity(offs.len() + steps.len());
let mut k = 0;
for o in offs {
at.push(o);
while steps.get(k).is_some_and(|&s| s <= o - STEP) {
k += 1;
}
if steps.get(k).is_some_and(|&s| (s - o).abs() < STEP) {
at.push(o);
}
}
Some((resample_stops(a, &at), resample_stops(b, &at)))
}
fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<GradientPaint> {
@@ -627,12 +662,128 @@ fn reoriented<V: Copy>(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wr
out
}
/// A stroke read along its subpath turned as `o` says: its width profile (whose sides swap when
/// reversed), pen pressure, tilt, bearing and rotation. Its arrowheads stay as they are.
fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
/// Gradient `g` laid along a closed subpath that now starts at fraction `s` of its length: the
/// part from `s` on runs first, then the part before it, stepping where the old start now falls.
/// The stops follow its colors as [`Gradient::span`] reads them, mixed linearly, and run once.
/// One of `g`'s own stops keeps its swatch link (each stop of a step its own), and a stop between
/// two of them the link [`link_at`] reads there.
fn gradient_from(g: &Gradient, s: f32) -> Gradient {
// A hue gradient that reflects unrolls through its curve, whose stops have no links: the links
// come from its own stops unrolled as a Classic gradient's, which keep them.
let hue_reflect = g.is_spread() && g.spread == GradientSpread::Reflect && g.method.is_hue();
let classic = hue_reflect.then(|| Gradient { method: GradientMethod::Classic, ..g.clone() });
let g = g.unrolled();
let mut own = classic.as_ref().map_or_else(|| g.stops.clone(), |c| c.unrolled().stops.clone());
own.sort_by(|a, b| a.offset.total_cmp(&b.offset));
let mut stops = Vec::new();
// The part from `s` to the end runs first, then the part up to `s`.
for (from, to, at) in [(s, 1.0, 0.0), (0.0, s, 1.0 - s)] {
// The first of `own` not yet matched: the parts' stops run in order, so the links are
// found in one pass.
let mut j = 0;
for (k, st) in g.span(from, to).stops.into_iter().enumerate() {
let p = from + (to - from) * st.offset;
while own.get(j).is_some_and(|o| o.offset <= p - STEP) {
j += 1;
}
let same = |i: usize| own.get(i).is_some_and(|o| o.color == st.color && o.opacity == st.opacity);
let near = (j..own.len()).take_while(|&i| own.get(i).is_some_and(|o| o.offset < p + STEP));
let mut hit = near.clone().find(|&i| same(i));
// A part starting on a step starts with the color after it, so its first stop takes
// the link of the step's last stop of that color.
if k == 0
&& let Some(at) = hit.and_then(|i| own.get(i)).map(|o| o.offset)
{
hit = near.filter(|&i| own.get(i).is_some_and(|o| o.offset == at) && same(i)).last().or(hit);
}
let (swatch, tint, plates) = match hit.and_then(|i| own.get(i).map(|o| (i, o))) {
Some((i, o)) => {
j = i + 1;
(o.swatch.clone(), o.tint, o.plates)
}
None => link_in(own.get(j.saturating_sub(1)..(j + 1).min(own.len())).unwrap_or_default(), p),
};
stops.push(GradientStop { offset: at + (to - from) * st.offset, swatch, tint, plates, ..st });
}
}
Gradient { stops, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1, ..g.into_owned() }
}
/// Dash pattern `d` read along subpaths of lengths `lens` turned as `o` says. Reversed, the
/// pattern runs backwards: from the start of a dash, that is the dash and then the other entries
/// in reverse order. Exact dashes also start where the turned subpaths now start. The pattern
/// restarts on every subpath at the one offset, so the offset moves only when every subpath needs
/// the same one (as subpaths whose lengths differ by whole periods do); dashes fitted to corners
/// ignore the offset, which stays as it is. A dash pattern starts once per subpath, so on a closed
/// subpath started elsewhere the dashes match the key's as far as its own start, and past it run
/// on without restarting there.
fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) {
if !d.is_dashed() || !d.offset.is_finite() {
return;
}
let mut pat = d.pattern.clone();
// An odd pattern repeats twice per period (dash, gap, dash / gap, dash, gap).
if pat.len() % 2 == 1 {
pat.extend_from_within(..);
}
let period: f64 = pat.iter().sum();
// Where along the key's own subpath the turned one starts (a closed one wraps round). A
// closed one reversed from its own start runs back from its end.
let at = match (o.closed, o.seam()) {
(true, s) if s == 0.0 && o.reversed => 1.0,
(true, s) => s,
(false, _) => o.start,
};
let first = pat.first().copied().unwrap_or(0.0);
let offset = |len: f64| if o.reversed { first - at * len - d.offset } else { d.offset + at * len };
let offsets: Vec<f64> = lens.iter().map(|&len| offset(len)).collect();
let agree = offsets.first().is_some_and(|&a| {
offsets.iter().all(|&b| {
let r = (b - a).rem_euclid(period);
r.is_finite() && r.min(period - r) <= 1e-6
})
});
if o.reversed {
if let Some(rest) = pat.get_mut(1..) {
rest.reverse();
}
d.pattern = pat;
}
if let Some(&off) = offsets.first().filter(|_| agree && !d.align_corners) {
d.offset = off;
}
}
/// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width
/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes,
/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as
/// they are.
fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) {
if o.is_identity() {
return;
}
if let Some(d) = &mut s.dash {
reorient_dash(d, o, lens);
}
let along = s.gradient_mode == StrokeGradientMode::Along;
if s.path_gradient().is_some()
&& let Paint::Gradient(g) = &mut s.paint
{
let start = along && o.seam() > 0.0;
if start {
g.gradient = gradient_from(&g.gradient, o.seam() as f32);
}
// Stops that reflect an even number of times read the same either way.
let (spread, runs) = g.gradient.painted_spread();
let reverse = o.reversed && !(spread == GradientSpread::Reflect && runs % 2 == 0);
if reverse {
g.gradient.reverse();
}
if start || reverse {
// The turned gradient is no longer the swatch's.
g.swatch = None;
}
}
let same = |v: f64| v;
if let Some(p) = &mut s.profile {
let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect();
@@ -676,9 +827,11 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
if o.is_identity() {
return;
}
let lens: Vec<f64> =
node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default();
for it in n.appearance.items.iter_mut() {
if let AppearanceItem::Stroke(s) = it {
reorient_stroke(s, o);
reorient_stroke(s, o, &lens);
if o.reversed && !o.closed {
std::mem::swap(&mut s.start_arrow, &mut s.end_arrow);
s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0);
@@ -709,9 +862,11 @@ pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
if o.is_identity() || !turns.all(|t| t.same_turn(&o)) {
return;
}
let lens: Vec<f64> =
node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default();
for it in n.appearance.items.iter_mut() {
if let AppearanceItem::Stroke(s) = it {
reorient_stroke(s, o);
reorient_stroke(s, o, &lens);
}
}
}
@@ -1255,13 +1410,21 @@ pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) ->
// Spine
// =====================================================================================
#[cfg(test)]
#[cfg(any(test, feature = "spine-count"))]
thread_local! {
/// How many times [`Spine::new`] has run on this thread, for tests that count how often a path
/// is flattened.
pub(crate) static SPINES_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// How many times [`Spine::new`] has run on this thread, for other crates' tests that count how
/// often a path is flattened (the `spine-count` feature, dev-dependencies only).
#[cfg(any(test, feature = "spine-count"))]
#[doc(hidden)]
pub fn spines_built() -> usize {
SPINES_BUILT.with(|n| n.get())
}
/// A spine (the first subpath of a path) flattened to a polyline, with cumulative lengths and the
/// arc length at each of its anchors.
pub struct Spine {
@@ -1280,7 +1443,7 @@ impl Spine {
/// arc lengths, and the arc length at each anchor. `None` when `path` has no subpath, or when
/// the first one flattens to fewer than two points (so it has no length to walk).
pub fn new(path: &PathData) -> Option<Self> {
#[cfg(test)]
#[cfg(any(test, feature = "spine-count"))]
SPINES_BUILT.with(|n| n.set(n.get() + 1));
let sp = path.subpaths.first()?;
let mut pts: Vec<Point> = Vec::new();
@@ -2783,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();
+71
View File
@@ -150,6 +150,10 @@ pub struct LabelStyles {
pub categories: Option<crate::CharStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub legend: Option<crate::CharStyle>,
/// The fill of [`Self::legend`] was set on the legend labels, so it is drawn on every pie wedge with Legends in
/// Wedges. `false`: a black fill there is the default, and the labels on dark wedges are drawn white.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub legend_fill_set: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub values_para: Option<crate::ParaStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -182,6 +186,18 @@ impl LabelStyles {
fn is_default(&self) -> bool {
*self == Self::default()
}
/// Is the kept legend fill the legend labels' own: set on them ([`Self::legend_fill_set`]), or not black (a file
/// saved without the mark)? Otherwise it is the default black, which edits that map the kept paints leave as it is.
pub fn legend_fill_is_own(&self) -> bool {
self.legend.as_ref().is_some_and(|st| self.legend_fill_set || st.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK))
}
/// Mark a kept legend fill that is the labels' own ([`Self::legend_fill_is_own`]) as set on them, before an edit
/// that maps the kept paints can turn it black.
pub fn mark_own_legend_fill(&mut self) {
self.legend_fill_set = self.legend_fill_is_own();
}
}
/// Graph Type › Position for pie graphs with several pies: the same size (Even), sized by their totals (Ratio), or
@@ -363,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")]
@@ -511,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 {
@@ -532,6 +568,14 @@ impl GraphSpec {
self.series_kinds.get(s).copied().flatten().filter(|k| k.combines_with(self.kind)).unwrap_or(self.kind)
}
/// Does the graph pick the fill of its legend labels itself, white on a dark wedge and black on the others: a pie
/// with Legends in Wedges whose legend labels keep no fill of their own ([`LabelStyles::legend_fill_is_own`])? Only
/// then is a black legend fill it keeps the default, which edits that map the kept paints leave as it is; other
/// graphs draw the kept fill as it is.
pub fn picks_legend_fill(&self) -> bool {
self.kind == GraphKind::Pie && self.legend && self.pie_legend_in_wedges && !self.label_styles.legend_fill_is_own()
}
/// The data with blank cells as `None`, every row as long as the longest (at most [`MAX_GRAPH_CATEGORIES`] rows
/// of [`MAX_GRAPH_SERIES`] cells).
pub fn cells(&self) -> Vec<Vec<Option<f64>>> {
@@ -586,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 {
@@ -635,6 +705,7 @@ impl Default for GraphSpec {
connect_points: true,
edge_to_edge: false,
placed: None,
placed_art: None,
}
}
}
+27 -23
View File
@@ -974,43 +974,45 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
/// The art of a symbol instance with its own appearance changes, in the symbol's coordinates, and
/// how the canvas places each object of it: through the symbol's 9-slice guides when the instance
/// is scaled by them ([`Document::place_symbol_art`]), otherwise by the instance's transform.
struct InstanceArt {
struct InstanceArt<'a> {
art: Node,
map: Option<crate::NineSliceMap>,
xf: vectorcraft_geom::Affine,
/// Quick boxes, which measure the instances in the art as it is placed through the guides.
boxes: SymbolBoxes<'a>,
}
impl InstanceArt {
impl<'a> InstanceArt<'a> {
/// The art of symbol instance `inst`. `None` for anything else, a missing symbol, or art that
/// placing through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of,
/// which [`Document::place_symbol_art`] does not place and the canvas does not draw.
fn of(doc: &Document, inst: &Node) -> Option<Self> {
fn of(doc: &'a Document, inst: &Node) -> Option<Self> {
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
let art = crate::symbol_overrides::dynamic_art(&sym.art, inst);
let map = doc.symbol_slice_map(symbol, *xf);
if map.as_ref().is_some_and(|m| m.most_placed(&art, doc) > crate::MAX_SYMBOL_NODES) {
let boxes = doc.symbol_boxes().quick();
let art = crate::symbol_overrides::dynamic_art(boxes.symbol_art(symbol)?, inst);
let map = boxes.slice_map(symbol, *xf);
if map.as_ref().is_some_and(|m| m.most_placed_with(&art, &boxes) > crate::MAX_SYMBOL_NODES) {
return None;
}
Some(Self { art, map, xf: *xf })
Some(Self { art, map, xf: *xf, boxes })
}
/// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the
/// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell
/// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides
/// object by object.
fn whole(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<vectorcraft_geom::Affine> {
whole.or_else(|| self.map.as_ref()?.one_cell(n, doc))
fn whole(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> Option<vectorcraft_geom::Affine> {
whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes))
}
/// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by
/// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when
/// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as
/// [`Document::place_symbol_art`] refuses it.
fn place(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
fn place(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
match (&self.map, whole) {
(_, Some(a)) => Some(moved(n, a)),
(Some(m), None) => (m.most_placed(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place(n, doc)),
(Some(m), None) => (m.most_placed_with(n, &self.boxes) <= crate::MAX_SYMBOL_NODES).then(|| m.place_with(n, &self.boxes)),
(None, None) => Some(moved(n, self.xf)),
}
}
@@ -1018,10 +1020,13 @@ impl InstanceArt {
/// Object `n` of the art placed on the canvas without clip groups
/// ([`crate::NineSliceMap::place_unclipped`]), as [`Self::place`] places it and within the
/// same limit ([`Document::place_symbol_art_unclipped`]).
fn place_unclipped(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
fn place_unclipped(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
match (&self.map, whole) {
(_, Some(a)) => Some(moved(n, a)),
(Some(m), None) => (m.most_placed_unclipped(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place_unclipped(n, doc)),
(Some(m), None) => {
let m = m.unclipped();
(m.most_placed_with(n, &self.boxes) <= crate::MAX_SYMBOL_NODES).then(|| m.place_with(n, &self.boxes))
}
(None, None) => Some(moved(n, self.xf)),
}
}
@@ -1046,15 +1051,14 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
/// draw. `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> {
doc: &'a Document,
art: &'a InstanceArt,
art: &'a InstanceArt<'a>,
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, self.doc, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
}
fn skips_guide(&self, n: &Node) -> bool {
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
@@ -1067,11 +1071,11 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
return self.hit(n, whole);
}
let whole = self.art.whole(n, self.doc, whole);
let whole = self.art.whole(n, whole);
if n.clips()
&& let Some(first) = children.first()
{
let Some(clip) = self.art.place_unclipped(first, self.doc, whole) else { return false };
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
if self.opt.clip_outlines
&& first.visible
&& !first.locked
@@ -1103,7 +1107,7 @@ 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 { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
}
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
@@ -1123,11 +1127,11 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
let mut n = &art.art;
for &i in path {
let children = n.children()?;
whole = art.whole(n, doc, whole);
whole = art.whole(n, whole);
if i != 0
&& n.clips()
&& let Some(first) = children.first()
&& let Some(clip) = art.place_unclipped(first, doc, whole)?.geometric_bounds()
&& let Some(clip) = art.place_unclipped(first, whole)?.geometric_bounds()
{
match meet(Some(clip), limit) {
Some(r) => limit = Some(r),
@@ -1136,7 +1140,7 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
}
n = children.get(usize::try_from(i).ok()?)?;
}
outline_within(&art.place(part, doc, whole)?, limit, &mut out);
outline_within(&art.place(part, whole)?, limit, &mut out);
Some(out)
}
+47
View File
@@ -1586,6 +1586,53 @@ fn symbol_art_past_the_object_limit_picks_nothing() {
assert!(symbol_part_outline(&d, n, &[0]).is_some());
}
/// Picking and outlining an object of a 9-slice instance's art, and placing that art, read the
/// symbol list once for each call, however many instances the art holds.
#[test]
fn picking_in_9_slice_art_reads_the_symbol_list_once() {
let mut d = Document::new(400.0, 400.0);
for i in 0..2_000 {
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: format!("Dot {i}"), art: Arc::new(dot) });
}
// A frame, a group of 20 squares in its top left cell, and 20 instances of the dots across
// the guides.
let square = |d: &mut Document, x: f64, y: f64| {
Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Appearance::default_art()))
};
let corner: Vec<_> = (0..20).map(|i| square(&mut d, f64::from(i % 5) * 4.0, f64::from(i / 5) * 4.0)).collect();
let dot = |d: &mut Document, i: u32| {
let xf = vectorcraft_geom::Affine::translate((f64::from(i) * 4.5 + 5.0, 48.0)) * vectorcraft_geom::Affine::scale(4.0);
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Dot {i}"), xf }))
};
let across: Vec<_> = (0..20).map(|i| dot(&mut d, i)).collect();
let frame = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()));
let mut kids = vec![frame, Arc::new(Node::group(d.alloc_id(), corner))];
kids.extend(across);
let root = Node::group(d.alloc_id(), kids);
d.symbols.push(crate::Symbol { dynamic: true, name: "Panel".into(), art: Arc::new(root) });
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5);
let inst = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Panel".into(), xf });
let art = d.symbols[2_000].art.clone();
let symbols = d.symbols.len();
let read = || crate::symbols::SYMBOLS_READ.with(std::cell::Cell::get);
let reads = |f: &dyn Fn()| {
let before = read();
f();
read() - before
};
// Picking also tests the placed art with boxes of its own, as a click outside symbols does.
let n = reads(&|| assert_eq!(symbol_part_at(&d, &inst, Point::new(2.0, 2.0), HitOptions::default()).map(|p| p[0]), Some(1)));
assert!(n <= 2 * symbols, "picking read {n} symbols");
let n = reads(&|| assert!(symbol_part_outline(&d, &inst, &[2]).is_some()));
assert!(n <= symbols, "outlining read {n} symbols");
let n = reads(&|| assert!(d.place_symbol_art("Panel", &art, xf).is_some()));
assert!(n <= symbols, "placing read {n} symbols");
let n = reads(&|| assert!(d.place_symbol_art_unclipped("Panel", &art, xf).is_some()));
assert!(n <= symbols, "placing without clips read {n} symbols");
}
/// A clip group that lies in one 9-slice cell is moved by that cell as one piece, everything in it
/// included, so an object in it is picked and outlined there even when placing that object through
/// the guides on its own would pass [`crate::MAX_SYMBOL_NODES`] objects.
+1
View File
@@ -55,6 +55,7 @@ mod pixels;
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
pub mod placed_document;
pub mod plugin_data;
pub mod ppi;
pub mod profiles;
pub mod puppet;
pub mod range;
+42 -9
View File
@@ -234,8 +234,14 @@ pub fn is_objects_on_path(n: &Node) -> bool {
/// The path of `n` if it is a path object an Objects on Path group can attach objects to: a path
/// (not a guide) whose first subpath has a length ([`path_length`]).
pub fn attachable_path(n: &Node) -> Option<&PathData> {
attachable(n).map(|(path, _)| path)
}
/// [`attachable_path`] with the path measured ([`Measured`]), from the one flattening that checks
/// its length.
pub fn attachable(n: &Node) -> Option<(&PathData, Measured)> {
match &n.kind {
NodeKind::Path { path, guide: false, .. } if path_length(path).is_some() => Some(path),
NodeKind::Path { path, guide: false, .. } => Some((path, Measured::new(path)?)),
_ => None,
}
}
@@ -301,20 +307,51 @@ pub fn path_length(path: &PathData) -> Option<(f64, bool)> {
/// A path's first subpath flattened ([`Spine`]), with its length and whether it is closed, so that
/// one flattening serves both measuring the path and finding points along it.
struct Measured {
pub struct Measured {
spine: Spine,
len: f64,
closed: bool,
}
impl std::fmt::Debug for Measured {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Measured").field("len", &self.len).field("closed", &self.closed).finish_non_exhaustive()
}
}
impl Measured {
/// `None` for a path without length, or with a length too large to be finite.
fn new(path: &PathData) -> Option<Self> {
pub fn new(path: &PathData) -> Option<Self> {
let spine = Spine::new(path)?;
let len = spine.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
(len.is_finite() && len > 1e-9).then_some(Self { spine, len, closed })
}
/// The flattened first subpath, to measure along.
pub fn spine(&self) -> &Spine {
&self.spine
}
/// The length of the first subpath (points), as [`path_length`] gives it.
pub fn length(&self) -> f64 {
self.len
}
/// Is the first subpath closed?
pub fn closed(&self) -> bool {
self.closed
}
/// [`stops`] on this path.
pub fn stops(&self, n: usize, spacing: Option<f64>, start: f64) -> Vec<(Point, f64)> {
let (start, gap) = layout(self.len, self.closed, n, spacing, start);
(0..n).map(|i| self.spine.at_length(nth_length(self.len, self.closed, start, gap, i))).collect()
}
/// [`stop`] on this path: `None` for an `i` of `n` or more.
pub fn stop(&self, n: usize, spacing: Option<f64>, start: f64, i: usize) -> Option<(Point, f64)> {
if i >= n {
return None;
}
let (start, gap) = layout(self.len, self.closed, n, spacing, start);
Some(self.spine.at_length(nth_length(self.len, self.closed, start, gap, i)))
}
}
/// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the
@@ -359,9 +396,7 @@ fn wrap(s: f64, len: f64) -> f64 {
/// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them
/// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length.
pub fn stops(path: &PathData, n: usize, spacing: Option<f64>, start: f64) -> Option<Vec<(Point, f64)>> {
let Measured { spine, len, closed } = Measured::new(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect())
Some(Measured::new(path)?.stops(n, spacing, start))
}
/// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others.
@@ -370,9 +405,7 @@ pub fn stop(path: &PathData, n: usize, spacing: Option<f64>, start: f64, i: usiz
if i >= n {
return None;
}
let Measured { spine, len, closed } = Measured::new(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
Some(spine.at_length(nth_length(len, closed, start, gap, i)))
Measured::new(path)?.stop(n, spacing, start, i)
}
/// The distance along a path of length `len` (closed or not) to object `i`, from `start` and
+287
View File
@@ -0,0 +1,287 @@
//! Image resolution metadata (pixels per inch) in the formats the image decoder reads: PNG `pHYs`,
//! JPEG JFIF density or EXIF, TIFF and WebP EXIF resolution tags, and BMP pixels per metre. An image
//! converted to PNG keeps it as a `pHYs` chunk ([`with_png_resolution`]).
const INCH_M: f64 = 0.0254;
const INCH_CM: f64 = 2.54;
/// Is `bytes` a PNG, JPEG, TIFF, WebP or BMP file, the formats [`resolution`] reads?
pub fn reads(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|| bytes.starts_with(&[0xff, 0xd8])
|| bytes.starts_with(b"II*\0")
|| bytes.starts_with(b"MM\0*")
|| (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP")
|| bytes.starts_with(b"BM")
}
/// The resolution a PNG, JPEG, TIFF, WebP or BMP file declares as (horizontal, vertical) ppi, each
/// from 1 to 100,000; `None` when it declares none (or only an aspect ratio), and for other files.
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
png(bytes)
} else if bytes.starts_with(&[0xff, 0xd8]) {
jpeg(bytes)
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
tiff(bytes)
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
webp(bytes)
} else if bytes.starts_with(b"BM") {
bmp(bytes)
} else {
None
};
r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v)))
}
/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either).
fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> {
b.get(at..at.checked_add(n)?)
}
fn bytes<const N: usize>(b: &[u8], at: usize) -> Option<[u8; N]> {
slice(b, at, N)?.try_into().ok()
}
fn be16(b: &[u8], at: usize) -> Option<u16> {
bytes(b, at).map(u16::from_be_bytes)
}
fn be32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_be_bytes)
}
fn le32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_le_bytes)
}
/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when
/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi).
fn per_metre(ppm: u32) -> f64 {
let v = ppm as f64 * INCH_M;
let whole = v.round();
if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v }
}
/// PNG chunks after the signature: (type, data).
pub fn png_chunks(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
let mut at = 8;
std::iter::from_fn(move || {
let len = be32(b, at)? as usize;
let ty = slice(b, at + 4, 4)?;
let data = slice(b, at + 8, len)?;
at = at.checked_add(12 + len)?;
Some((ty, data))
})
}
fn png(b: &[u8]) -> Option<(f64, f64)> {
let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?;
// Unit 1 = metre; 0 only gives the pixel aspect ratio.
(d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0))))
}
fn jpeg(b: &[u8]) -> Option<(f64, f64)> {
let (mut jfif, mut exif) = (None, None);
let mut at = 2;
while at + 4 <= b.len() && b[at] == 0xff {
let marker = b[at + 1];
// 0xff fill bytes pad between segments.
if marker == 0xff {
at += 1;
continue;
}
if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
at += 2;
continue;
}
// Start of scan or end of image: no more metadata.
if marker == 0xda || marker == 0xd9 {
break;
}
let len = be16(b, at + 2)? as usize;
let seg = slice(b, at + 4, len.checked_sub(2)?)?;
match marker {
0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => {
let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64);
jfif = match seg[7] {
1 => Some((x, y)),
2 => Some((x * INCH_CM, y * INCH_CM)),
_ => None,
};
}
0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]),
_ => {}
}
at += 2 + len;
}
jfif.or(exif)
}
/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit, as (horizontal, vertical) ppi
/// in the stored pixels' axes, unchecked; `None` without an absolute unit.
pub fn tiff(b: &[u8]) -> Option<(f64, f64)> {
let le = b.starts_with(b"II");
let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes });
let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes });
let ifd = u32_at(4)? as usize;
let (mut x, mut y, mut unit) = (None, None, 2);
for i in 0..u16_at(ifd)? as usize {
let e = ifd.checked_add(2 + i * 12)?;
let rational = || -> Option<f64> {
let at = u32_at(e + 8)? as usize;
let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
(d != 0).then(|| n as f64 / d as f64)
};
match u16_at(e)? {
282 => x = rational(),
283 => y = rational(),
296 => unit = u16_at(e + 8)?,
_ => {}
}
}
let k = match unit {
2 => 1.0,
3 => INCH_CM,
_ => return None,
};
let x = x?;
Some((x * k, y.unwrap_or(x) * k))
}
fn webp(b: &[u8]) -> Option<(f64, f64)> {
let mut at = 12;
while at + 8 <= b.len() {
let len = le32(b, at + 4)? as usize;
let data = slice(b, at + 8, len)?;
if &b[at..at + 4] == b"EXIF" {
return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data));
}
at += 8 + len + (len & 1);
}
None
}
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
if le32(b, 14)? < 40 {
return None;
}
let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre);
Some((ppm(38)?, ppm(42)?))
}
/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores).
pub fn pixels_per_metre(ppi: f64) -> u32 {
(ppi / INCH_M).round().clamp(1.0, u32::MAX as f64) as u32
}
/// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another.
fn crc32(parts: &[&[u8]]) -> u32 {
let mut crc = !0u32;
for &b in parts.iter().flat_map(|p| p.iter()) {
crc ^= u32::from(b);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg());
}
}
!crc
}
/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch.
pub fn phys_chunk(x: f64, y: f64) -> Vec<u8> {
let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes());
// x, y, unit 1 = metre.
let data = [x.as_slice(), y.as_slice(), &[1]].concat();
let mut out = Vec::with_capacity(21);
out.extend_from_slice(&9u32.to_be_bytes());
out.extend_from_slice(b"pHYs");
out.extend_from_slice(&data);
out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes());
out
}
/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced).
pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> {
let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() };
let chunk = phys_chunk(x, y);
let mut out = Vec::with_capacity(png.len() + chunk.len());
out.extend_from_slice(head);
out.extend_from_slice(&chunk);
let mut at = head.len();
while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) {
if chunk.get(4..8) != Some(b"pHYs") {
out.extend_from_slice(chunk);
}
at += chunk.len();
}
out.extend_from_slice(png.get(at..).unwrap_or_default());
out
}
#[cfg(test)]
mod tests {
use super::*;
fn png_of(w: u32, h: u32) -> Vec<u8> {
let mut out = Vec::new();
image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
/// The `pHYs` chunk carries the CRC a PNG reader checks, and replaces the one already there.
#[test]
fn a_png_takes_its_resolution_and_still_decodes() {
let png = png_of(4, 3);
assert_eq!(resolution(&png), None);
let tagged = with_png_resolution(&png, (300.0, 150.0));
assert_eq!(resolution(&tagged), Some((300.0, 150.0)));
let again = with_png_resolution(&tagged, (72.0, 72.0));
assert_eq!(resolution(&again), Some((72.0, 72.0)), "replaced, not duplicated");
assert_eq!(again.len(), tagged.len());
let img = image::load_from_memory(&again).unwrap();
assert_eq!((img.width(), img.height()), (4, 3));
// Every PNG ends with this IEND chunk CRC.
assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082);
}
/// RIFF chunk `ty` holding `data`, padded to an even length.
fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec<u8> {
let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat();
if data.len() % 2 == 1 {
out.push(0);
}
out
}
fn webp_of(chunks: &[Vec<u8>]) -> Vec<u8> {
let body = chunks.concat();
let size = u32::try_from(body.len() + 4).unwrap();
[b"RIFF".as_slice(), &size.to_le_bytes(), b"WEBP", &body].concat()
}
/// A WebP's EXIF chunk is found past an odd-length chunk and its padding byte, and a chunk whose
/// length runs past the end of the file (up to `u32::MAX`, more than a 32-bit `usize` can add to
/// an offset) gives no resolution.
#[test]
fn a_webp_reads_its_exif_and_rejects_a_chunk_past_the_end() {
// Little-endian TIFF: two IFD0 entries, XResolution 300/1 at offset 38 and ResolutionUnit inch.
let mut tiff = b"II*\0".to_vec();
tiff.extend_from_slice(&8u32.to_le_bytes());
tiff.extend_from_slice(&2u16.to_le_bytes());
for (tag, ty, value) in [(282u16, 5u16, 38u32), (296, 3, 2)] {
tiff.extend_from_slice(&tag.to_le_bytes());
tiff.extend_from_slice(&ty.to_le_bytes());
tiff.extend_from_slice(&1u32.to_le_bytes());
tiff.extend_from_slice(&value.to_le_bytes());
}
tiff.extend_from_slice(&0u32.to_le_bytes());
tiff.extend_from_slice(&300u32.to_le_bytes());
tiff.extend_from_slice(&1u32.to_le_bytes());
let exif = [b"Exif\0\0".as_slice(), &tiff].concat();
let exif_len = u32::try_from(exif.len()).unwrap();
let ok = webp_of(&[riff_chunk(b"VP8X", 3, &[0, 0, 0]), riff_chunk(b"EXIF", exif_len, &exif)]);
assert_eq!(resolution(&ok), Some((300.0, 300.0)));
for len in [u32::MAX, u32::MAX - 7, 1_000] {
let bad = webp_of(&[riff_chunk(b"VP8X", len, &[0; 10])]);
assert_eq!(resolution(&bad), None, "chunk length {len}");
}
}
}
+79 -3
View File
@@ -206,11 +206,13 @@ impl Document {
impl Document {
/// Visit every paint held by the art (opacity masks included), symbol definitions, pattern
/// tiles and graphic styles (fills, strokes and text runs), and the colour of every
/// gradient-mesh point as a solid paint.
/// gradient-mesh point as a solid paint. A graph's default black legend fill is left out.
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
let mut tree = |n: &Node| {
walk_with_masks(n, &mut |m| {
node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f);
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
let default_legend = default_legend_fill(m);
graph_paints(m).enumerate().filter(|(i, _)| Some(*i) != default_legend).for_each(|(_, p)| f(p));
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
}
@@ -404,6 +406,19 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mu
.chain(rows.flat_map(|r| [r.paint.fill.as_mut(), r.paint.stroke.as_mut()]).flatten())
}
/// The place in [`graph_paints`] of the legend fill graph `n` keeps when it is the default black of a graph that picks
/// its legend labels' fill ([`crate::graph::GraphSpec::picks_legend_fill`]). Other graphs draw the kept fill as it is,
/// so it is visited and mapped.
fn default_legend_fill(n: &Node) -> Option<usize> {
let g = n.extras().graph.as_deref()?;
let l = &g.label_styles;
if l.legend.is_none() || !g.picks_legend_fill() {
return None;
}
let series: usize = g.series_paints.iter().map(|s| usize::from(s.fill.is_some()) + usize::from(s.stroke.is_some())).sum();
Some(series + 2 * (usize::from(l.values.is_some()) + usize::from(l.categories.is_some())))
}
/// Mutable [`node_paints`], in the same order.
pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
let runs = match &mut n.kind {
@@ -446,11 +461,16 @@ fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> {
}
}
// A graph's series and label paints, which its marks and labels take when it is drawn again.
let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
// The default black legend fill, which is not the legend labels' own, stays black.
let default_legend = default_legend_fill(n);
let graph: Vec<(usize, Paint)> =
graph_paints(n).enumerate().filter(|(i, _)| Some(*i) != default_legend).filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
if !graph.is_empty() {
count += graph.len();
let m = out.get_or_insert_with(|| n.clone());
if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
// A legend fill of the labels' own stays theirs when the change makes it black.
spec.label_styles.mark_own_legend_fill();
let mut graph = graph.into_iter().peekable();
for (i, p) in graph_paints_mut(spec).enumerate() {
if graph.peek().is_some_and(|c| c.0 == i)
@@ -720,6 +740,62 @@ mod tests {
assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none));
}
#[test]
fn a_legend_fill_mapped_to_black_stays_the_labels_own() {
let (mut d, a, _) = doc();
let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand");
let spec = crate::graph::GraphSpec {
label_styles: crate::graph::LabelStyles { legend: Some(crate::CharStyle { fill: red, ..Default::default() }), ..Default::default() },
..Default::default()
};
assert!(spec.label_styles.legend_fill_is_own() && !spec.label_styles.legend_fill_set, "not black, saved without the mark");
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let mut to_black = |c: &mut Color, s: &mut Option<String>, _: &mut f32| {
s.as_deref() == Some("Brand") && {
*c = Color::BLACK;
*s = None;
true
}
};
assert_eq!(d.map_solid_paints(&mut to_black), 2, "the rectangle's fill and the legend fill");
let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles;
assert_eq!(styles.legend.unwrap().fill, Paint::solid(Color::BLACK));
assert!(styles.legend_fill_set, "the black fill is still the labels' own");
}
#[test]
fn the_default_black_legend_fill_is_left_as_it_is() {
use crate::graph::GraphKind;
// Only a pie with Legends in Wedges picks its legend labels' fill; the other graphs draw the kept black.
for (kind, in_wedges, picks) in [(GraphKind::Pie, true, true), (GraphKind::Pie, false, false), (GraphKind::Column, true, false)] {
let (mut d, a, _) = doc();
let black = || crate::CharStyle { fill: Paint::solid(Color::BLACK), size: 11.0, ..Default::default() };
let spec = crate::graph::GraphSpec {
kind,
legend: true,
pie_legend_in_wedges: in_wedges,
series_paints: vec![crate::SeriesPaint { fill: Some(Paint::solid(Color::BLACK)), ..Default::default() }],
label_styles: crate::graph::LabelStyles { values: Some(black()), legend: Some(black()), ..Default::default() },
..Default::default()
};
let blacks = |d: &Document| {
let mut seen = 0;
d.visit_paints(&mut |p| seen += usize::from(*p == Paint::solid(Color::BLACK)));
seen
};
let before = blacks(&d);
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let want = if picks { 2 } else { 3 };
assert_eq!(blacks(&d) - before, want, "{kind:?}, in wedges {in_wedges}: the series, value labels' and legend fills visited");
let mut link_black = |c: &mut Color, s: &mut Option<String>, _: &mut f32| *c == Color::BLACK && s.replace("Black".into()).is_none();
assert_eq!(d.map_solid_paints_in(&[a], &mut link_black), want, "{kind:?}, in wedges {in_wedges}");
let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles;
let legend = if picks { Paint::solid(Color::BLACK) } else { linked(Color::BLACK, "Black") };
assert_eq!(styles.legend.unwrap().fill, legend, "{kind:?}, in wedges {in_wedges}: linked unless the pie picks the fill");
assert_eq!(styles.values.unwrap().fill, linked(Color::BLACK, "Black"));
}
}
#[test]
fn mapping_within_ids_visits_each_paint_once() {
let (mut d, a, b) = doc();
+36 -18
View File
@@ -463,8 +463,13 @@ impl NineSliceMap {
///
/// Strokes keep their weight, as they do for any instance.
pub fn place(&self, art: &Node, doc: &Document) -> Node {
let boxes = doc.symbol_boxes().quick();
self.place_at(art, &boxes, 0)
self.place_with(art, &doc.symbol_boxes().quick())
}
/// [`Self::place`] with the instances in `art` measured by `boxes`, quick boxes or boxes
/// measuring symbol art.
pub(crate) fn place_with(&self, art: &Node, boxes: &SymbolBoxes) -> Node {
self.place_at(art, boxes, 0)
}
/// [`Self::place`] without clip groups, for writers that do not apply clipping (DXF, WMF):
@@ -480,16 +485,25 @@ impl NineSliceMap {
/// object drawn in clip groups counts one group plus a clip path and a copy for each cell its
/// box reaches. That is never more than [`MAX_SLICE_GROWTH`] for each object of `art`.
pub fn most_placed(&self, art: &Node, doc: &Document) -> u64 {
let boxes = doc.symbol_boxes().quick();
self.most_at(art, &boxes, 0)
self.most_placed_with(art, &doc.symbol_boxes().quick())
}
/// [`Self::most_placed`] with the instances in `art` measured by `boxes`, quick boxes or boxes
/// measuring symbol art.
pub(crate) fn most_placed_with(&self, art: &Node, boxes: &SymbolBoxes) -> u64 {
self.most_at(art, boxes, 0)
}
/// The affine map that [`Self::place`] and [`Self::place_unclipped`] move object `n` by as one
/// piece, with everything in it: the map of the cell its box lies in, or of the cell at the
/// origin when it has no box. `None` when its box crosses a guide.
pub fn one_cell(&self, n: &Node, doc: &Document) -> Option<Affine> {
let boxes = doc.symbol_boxes().quick();
let Some(b) = n.geometric(Some(&boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
self.one_cell_with(n, &doc.symbol_boxes().quick())
}
/// [`Self::one_cell`] with the instances in `n` measured by `boxes`.
pub(crate) fn one_cell_with(&self, n: &Node, boxes: &SymbolBoxes) -> Option<Affine> {
let Some(b) = n.geometric(Some(boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
return Some(self.cell_at(Point::ZERO));
};
let (cols, rows) = (self.x.cells(b.x0, b.x1), self.y.cells(b.y0, b.y1));
@@ -501,6 +515,11 @@ impl NineSliceMap {
Self { clips: false, ..*self }.most_placed(art, doc)
}
/// This map placing without clip groups, as [`Self::place_unclipped`] does.
pub(crate) fn unclipped(&self) -> Self {
Self { clips: false, ..*self }
}
/// [`Self::most_placed`] for `n` at nesting depth `depth`, following [`Self::place_at`].
fn most_at(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 {
let whole = n.count_with_masks() as u64;
@@ -671,7 +690,7 @@ impl NineSliceMap {
}
/// `n` moved by `a`, its strokes at their own weight.
fn transformed(n: &Node, a: Affine) -> Node {
pub(crate) fn transformed(n: &Node, a: Affine) -> Node {
let mut out = n.clone();
out.transform(a, false);
out
@@ -765,10 +784,7 @@ impl Document {
/// `None` when the symbol has no guides or the instance is at its natural size. The guides cut
/// the art's box with the instances in it measured by their own art.
pub fn symbol_slice_map(&self, name: &str, xf: Affine) -> Option<NineSliceMap> {
let guides = self.symbol_nine_slice(name)?;
let sym = self.symbols.iter().find(|s| s.name == name)?;
let art = self.symbol_boxes().quick().art_bounds(name).or_else(|| sym.art.geometric_bounds())?;
NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf)
self.symbol_boxes().quick().slice_map(name, xf)
}
/// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already
@@ -782,9 +798,10 @@ impl Document {
/// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through
/// the guides could make more than [`MAX_SYMBOL_NODES`] objects ([`NineSliceMap::most_placed`]).
pub fn place_symbol_art(&self, name: &str, art: &Node, xf: Affine) -> Option<Node> {
match self.symbol_slice_map(name, xf) {
Some(m) if m.most_placed(art, self) > MAX_SYMBOL_NODES => None,
Some(m) => Some(m.place(art, self)),
let boxes = self.symbol_boxes().quick();
match boxes.slice_map(name, xf) {
Some(m) if m.most_placed_with(art, &boxes) > MAX_SYMBOL_NODES => None,
Some(m) => Some(m.place_with(art, &boxes)),
None => Some(transformed(art, xf)),
}
}
@@ -795,8 +812,8 @@ impl Document {
pub fn edited_nine_slice(&self) -> Option<EditedNineSlice> {
let se = self.symbol_edit.as_ref()?;
let guides = self.symbol_nine_slice(&se.symbol)?;
let sym = self.symbols.iter().find(|s| s.name == se.symbol)?;
let art = self.symbol_boxes().quick().art_bounds(&se.symbol).or_else(|| sym.art.geometric_bounds())?;
let boxes = self.symbol_boxes().quick();
let art = boxes.art_bounds(&se.symbol).or_else(|| boxes.symbol_art(&se.symbol)?.geometric_bounds())?;
let natural = self.symbol_natural_xf(&se.symbol);
let b = natural.transform_rect_bbox(art);
if !finite(b) || b.width() <= 1e-9 || b.height() <= 1e-9 || natural.determinant().abs() < 1e-18 {
@@ -811,8 +828,9 @@ impl Document {
/// [`Self::place_symbol_art`] for writers that do not apply clipping
/// ([`NineSliceMap::place_unclipped`]).
pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option<Node> {
match self.symbol_slice_map(name, xf) {
Some(m) => (m.most_placed_unclipped(art, self) <= MAX_SYMBOL_NODES).then(|| m.place_unclipped(art, self)),
let boxes = self.symbol_boxes().quick();
match boxes.slice_map(name, xf).map(|m| m.unclipped()) {
Some(m) => (m.most_placed_with(art, &boxes) <= MAX_SYMBOL_NODES).then(|| m.place_with(art, &boxes)),
None => Some(transformed(art, xf)),
}
}
+57 -7
View File
@@ -8,7 +8,8 @@ use std::sync::Arc;
use vectorcraft_geom::{Affine, Rect};
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, Node, NodeKind, SYMBOL_HALF};
use crate::symbol_nine_slice::transformed;
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF};
/// The box a symbol instance is measured by when its symbol's art has no box
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
@@ -128,6 +129,8 @@ impl Document {
/// Each symbol name of this document → the index of the first symbol of that name (the one a
/// name finds).
pub(crate) fn symbol_names(&self) -> SymbolNames {
#[cfg(test)]
SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len()));
let mut names = HashMap::with_capacity(self.symbols.len());
for (i, s) in self.symbols.iter().enumerate() {
names.entry(s.name.clone()).or_insert(i);
@@ -136,6 +139,12 @@ impl Document {
}
}
#[cfg(test)]
thread_local! {
/// How many symbols [`Document::symbol_names`] has read on this thread.
pub(crate) static SYMBOLS_READ: Cell<usize> = const { Cell::new(0) };
}
impl<'a> SymbolBoxes<'a> {
/// The document whose symbols these are.
pub fn document(&self) -> &'a Document {
@@ -437,8 +446,8 @@ impl<'a> SymbolBoxes<'a> {
// The most objects placing makes, the art of opacity masks included, is set aside
// while the art is placed and measured, and what placing did not make is given back.
let art = self.symbol_art(name)?;
let most = match self.doc.symbol_slice_map(name, linear) {
Some(m) => m.most_placed(art, self.doc),
let most = match self.slice_map(name, linear) {
Some(m) => self.in_art(|| m.most_placed_with(art, self)),
None => art.count_with_masks() as u64,
};
let used = self.sliced_placed.get();
@@ -455,6 +464,14 @@ impl<'a> SymbolBoxes<'a> {
v.map(|v| moved.transform_rect_bbox(v))
}
/// [`Document::symbol_slice_map`] with the guides cutting the art box these boxes measure for
/// the symbol (its geometric part, which does not depend on the mode of the boxes).
pub(crate) fn slice_map(&self, name: &str, xf: Affine) -> Option<NineSliceMap> {
let guides = self.doc.symbol_nine_slice(name)?;
let art = self.art_bounds(name).or_else(|| self.symbol_art(name)?.geometric_bounds())?;
NineSliceMap::new(guides, art, self.doc.symbol_natural_xf(name), xf)
}
/// The box [`Self::placed_visual_within`] returns outside quick boxes.
fn place_and_measure(&self, name: &str, xf: Affine, most: u64) -> Option<Rect> {
self.place_and_count(name, xf, most).and_then(|(v, _)| v)
@@ -464,10 +481,10 @@ impl<'a> SymbolBoxes<'a> {
/// opacity masks included. `None` when the art is not placed.
fn place_and_count(&self, name: &str, xf: Affine, most: u64) -> Option<(Option<Rect>, u64)> {
self.measure_art(name, |art| {
let art = match self.doc.symbol_slice_map(name, xf) {
Some(m) if m.most_placed(art, self.doc) > most => return None,
Some(m) => m.place(art, self.doc),
None => self.doc.place_symbol_art(name, art, xf)?,
let art = match self.slice_map(name, xf) {
Some(m) if self.in_art(|| m.most_placed_with(art, self)) > most => return None,
Some(m) => self.in_art(|| m.place_with(art, self)),
None => transformed(art, xf),
};
Some((self.in_art(|| art.visual(Some(self))), art.count_with_masks() as u64))
})
@@ -689,6 +706,39 @@ mod tests {
assert_eq!(s.sliced_placed.get(), 13);
}
#[test]
fn measuring_9_slice_instances_reads_the_symbol_list_once() {
// 2,000 symbols, then a frame with guides and a symbol with guides holding the frame
// scaled 2 times across, each shown by 200 instances scaled by different amounts.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let dot = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Dot {i}"), vec![dot]);
}
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0);
symbol(&mut d, "Panel", vec![frame]);
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
symbol(&mut d, "Holder", vec![wide]);
d.set_symbol_nine_slice("Holder", Some(crate::SymbolNineSlice::default()));
let scaled = |d: &mut Document, name: &str| -> Vec<Node> {
(1..=200).map(|i| instance(d, name, Affine::scale_non_uniform(1.0 + f64::from(i) / 100.0, 1.5))).collect()
};
let (panels, holders) = (scaled(&mut d, "Panel"), scaled(&mut d, "Holder"));
// What each instance measures in boxes of its own.
let exact: Vec<_> = panels.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes())).collect();
let quick: Vec<_> = holders.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes().quick())).collect();
let read = || SYMBOLS_READ.with(Cell::get);
let before = read();
let s = d.symbol_boxes();
assert_eq!(panels.iter().map(|n| n.visual_bounds_with(&s)).collect::<Vec<_>>(), exact);
let s = d.symbol_boxes().quick();
assert_eq!(holders.iter().map(|n| n.visual_bounds_with(&s)).collect::<Vec<_>>(), quick);
// Each set of boxes reads the list once to find symbols by name.
let symbols = d.symbols.len();
assert!(read() - before <= 2 * symbols, "{} symbols read", read() - before);
}
#[test]
fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() {
let mut d = Document::new(200.0, 200.0);
+7 -3
View File
@@ -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)
+23 -8
View File
@@ -12,7 +12,7 @@ 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) {
match clip_effects_applied(clip, true, || true) {
Some(m) => m.clip_outline(Some(&outline_text), &unite),
None => clip.clip_outline(Some(&outline_text), &unite),
}
@@ -31,14 +31,26 @@ pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> {
/// geometry effects of its own fills and strokes live instead. `None` when nothing in it has a
/// geometry effect. Effects on the clip group or around it then reshape the result, after its own.
pub(crate) fn with_clip_effects_applied(n: &Node) -> Option<Node> {
let paint = n.clip_paint();
clip_effects_applied(n, paint.fill.is_none() && paint.stroke.is_none())
with_clip_effects_applied_while(n, || true)
}
/// [`with_clip_effects_applied`]; with `items` unset (a clipping path that paints, and the paths of
/// a compound path, which draw with the compound path's fills and strokes), the geometry effects of
/// `n`'s own fills and strokes are left out.
fn clip_effects_applied(n: &Node, items: bool) -> Option<Node> {
/// [`with_clip_effects_applied`] that calls `take` before it visits each member of a group, layer
/// or compound path in `n`, at every depth: once `take` returns `false`, that member and the
/// members after it are not visited. The members of a group or layer that are not visited stay as
/// they are, with their effects. A compound path with geometry effects of its own still becomes a
/// path of its reshaped geometry. In a clipping path that does not paint, one whose fills or
/// strokes have geometry effects still becomes a group of one path per fill and stroke. In both
/// cases the paths in it that are not visited go
/// into that geometry as they are, and their own effects are not applied.
pub(crate) fn with_clip_effects_applied_while(n: &Node, take: fn() -> bool) -> Option<Node> {
let paint = n.clip_paint();
clip_effects_applied(n, paint.fill.is_none() && paint.stroke.is_none(), take)
}
/// [`with_clip_effects_applied_while`]; with `items` unset (a clipping path that paints, and the
/// paths of a compound path, which draw with the compound path's fills and strokes), the geometry
/// effects of `n`'s own fills and strokes are left out.
fn clip_effects_applied(n: &Node, items: bool, take: fn() -> bool) -> Option<Node> {
let mut m: Option<Node> = None;
let members: &[std::sync::Arc<Node>] = match &n.kind {
NodeKind::Group { children, clip: true } => children.get(..1).unwrap_or_default(),
@@ -53,7 +65,10 @@ fn clip_effects_applied(n: &Node, items: bool) -> Option<Node> {
// The paths of a compound path draw with the compound path's fills and strokes, and stay paths.
let compound = matches!(n.kind, NodeKind::Compound { .. });
for (i, c) in members.iter().enumerate().skip(skip).filter(|(_, c)| all || c.visible) {
if let Some(r) = clip_effects_applied(c, items && !compound)
if !take() {
break;
}
if let Some(r) = clip_effects_applied(c, items && !compound, take)
&& let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i))
{
*slot = std::sync::Arc::new(r);
+5 -2
View File
@@ -904,7 +904,10 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
/// draw. A clip group's clipping path only takes the geometry effects in it into its geometry
/// ([`crate::clip::with_clip_effects_applied`]). Images, symbol instances and the other objects
/// ([`crate::clip::with_clip_effects_applied_while`]), and the members of a clipping group or
/// compound path count toward the limit below. A group or layer in a clipping path that has
/// geometry effects of its own is walked twice, once for its members' effects and once for its
/// own, and its members count each time. Images, symbol instances and the other objects
/// that `own_effects_art` leaves alone stay as they are, and so does a group or layer with a 3D
/// effect with everything in it. Calls nested in one another, through the
/// groups and layers it walks and the art it evaluates (symbol art and Pathfinder members
@@ -917,7 +920,7 @@ pub(crate) fn members_as_drawn(doc: Option<&Document>, n: &mut Node) {
// The clipping path's own geometry effects shape it before the effects around it do.
if clip == 1
&& let Some(first) = ch.first_mut()
&& let Some(applied) = crate::clip::with_clip_effects_applied(first)
&& let Some(applied) = crate::clip::with_clip_effects_applied_while(first, DrawnFrame::take_member)
{
*first = Arc::new(applied);
}
+47
View File
@@ -849,6 +849,53 @@ fn nested_groups_with_effects_count_toward_the_depth_limit() {
assert!(deepest.is_some_and(|d| crate::reshape::geometry_effects(&d).len() == 1), "the deepest member keeps its effect");
}
/// The members of a clipping path count toward the member limit: with room for two more members,
/// the third member of a clipping group keeps its own effect as it is.
#[test]
fn clipping_path_members_past_the_member_limit_stay_as_they_are() {
let member = |id: u64| {
let mut m = with_effect(square_at_100(), offset_10());
m.id = NodeId(id);
Arc::new(m)
};
let clipping = Node::group(NodeId(20), vec![member(2), member(3), member(4)]);
let mut clipped = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clipping), Arc::new(square_at_100())], clip: true });
// An enclosing call that has visited all the members it may but two.
let _outer = DrawnFrame::enter().unwrap();
DRAWN.with(|d| d.set((1, crate::SYMBOL_ART_MAX_NODES - 2)));
members_as_drawn(None, &mut clipped);
let clipping = clipped.children().unwrap()[0].clone();
let effects: Vec<usize> = clipping.children().unwrap().iter().map(|m| crate::reshape::geometry_effects(m).len()).collect();
assert_eq!(effects, [0, 0, 1], "the first two members take their Offset Path, the third keeps it");
let widths: Vec<f64> = clipping.children().unwrap().iter().map(|m| m.geometric_bounds().unwrap().width()).collect();
assert!((widths[0] - 120.0).abs() < 0.5 && (widths[1] - 120.0).abs() < 0.5 && (widths[2] - 100.0).abs() < 0.5, "{widths:?}");
}
/// A compound clipping path with an effect of its own takes that effect when the member limit is
/// reached among its paths: with room for one more member, the first path (at 100 to 200) takes
/// its Offset Path, the second (at 300 to 400) goes in as it is, and the compound path's Offset
/// Path reshapes both, to 80 to 220 and 290 to 410.
#[test]
fn a_compound_clipping_path_takes_its_own_effect_at_the_member_limit() {
let member = |id: u64, x: f64| {
let path = Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 100.0, x + 100.0, 200.0)), black());
Arc::new(with_effect(path, offset_10()))
};
let kind = NodeKind::Compound { children: vec![member(2, 100.0), member(3, 300.0)], rule: FillRule::NonZero };
let clipping = with_effect(Node::new(NodeId(20), kind), offset_10());
let mut clipped = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clipping), Arc::new(square_at_100())], clip: true });
// An enclosing call that has visited all the members it may but one.
let _outer = DrawnFrame::enter().unwrap();
DRAWN.with(|d| d.set((1, crate::SYMBOL_ART_MAX_NODES - 1)));
members_as_drawn(None, &mut clipped);
let clipping = clipped.children().unwrap()[0].clone();
assert!(crate::reshape::geometry_effects(&clipping).is_empty(), "the compound path's Offset Path is in its geometry");
let subpaths = clipping.path_data().unwrap().subpaths.clone();
let bounds: Vec<(f64, f64)> = subpaths.into_iter().map(|sp| PathData::single(sp).bounds().unwrap()).map(|b| (b.x0, b.x1)).collect();
let near = |(a, b): (f64, f64), (x0, x1): (f64, f64)| (a - x0).abs() < 0.5 && (b - x1).abs() < 0.5;
assert!(bounds.len() == 2 && near(bounds[0], (80.0, 220.0)) && near(bounds[1], (290.0, 410.0)), "{bounds:?}");
}
/// An image or a symbol instance that a group's Transform effect moves takes the placed gradients
/// of its own fills along, as a path does, and each copy takes them as many times as it takes the
/// transform.
+2 -2
View File
@@ -84,8 +84,8 @@ pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
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, outline_art, outline_text,
reshape,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
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,
+142 -9
View File
@@ -107,11 +107,44 @@ fn reaches_appearance(e: &Effect) -> bool {
}
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`]), or whose
/// live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn, baked and
/// expanded through that art ([`reshape`]).
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`]),
/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn,
/// baked and expanded through that art ([`reshape`]).
pub fn has_transform_art(n: &Node) -> bool {
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n)
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n) || copied_raster_at(n).is_some()
}
/// Where the own effects of `n`, a path or compound path, split so that each copy of a Transform
/// effect carries the raster effects listed before that effect ([`copied_raster_art`]): the index
/// of the last visible Transform effect that makes copies, when a visible raster effect that
/// follows a Transform effect ([`crate::raster::follows`]) is listed before it and every other
/// visible effect before it is a geometry effect or such a raster effect. `None` otherwise, and for
/// a path with a linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect
/// plug-in that paints what it returns, or a fill or stroke that paints with geometry effects of
/// its own.
pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) {
return None;
}
let effects = &n.appearance.effects;
// Checked first: this runs for every object drawn.
if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") {
return None;
}
let t = effects.iter().rposition(|e| {
e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0
})?;
let before = effects.get(..t)?;
let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id))
&& before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id));
let excluded = n.extras().mask.as_ref().is_some_and(|m| m.linked)
|| crate::has_solid(n)
|| crate::has_revolve(n)
|| crate::has_crop_marks(n)
|| crate::addons::halftone::has_halftone(n)
|| has_painted_effects(n)
|| n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()));
(carried && !excluded).then_some(t)
}
/// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id,
@@ -475,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
@@ -487,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.
@@ -495,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() {
@@ -797,6 +841,9 @@ fn as_art_opts(
nodes: &SymbolNodes,
apart: bool,
) -> Option<Node> {
if let Some(t) = copied_raster_at(n) {
return Some(dressed_keeping_effects(copied_raster_art(paint_doc, n, t, apart), n));
}
let fx = geometry_effects(n);
let mut art = match &n.kind {
NodeKind::Image(im) => {
@@ -882,6 +929,89 @@ pub(crate) fn dressed(mut art: Node, n: &Node) -> Node {
art
}
/// [`dressed`] that keeps the effects of `art`.
fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node {
let effects = std::mem::take(&mut art.appearance.effects);
let mut art = dressed(art, n);
art.appearance.effects = effects;
art
}
/// The art of path or compound path `n` whose own effects split at `t` ([`copied_raster_at`]): the
/// art the effects before the Transform effect at `t` make of `n`, with their raster effects, then
/// copied by that Transform effect, each copy an object of its own carrying those raster effects
/// moved, turned, reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry
/// effects after it. The art keeps `n`'s id and carries the raster effects from `t` on, without
/// `n`'s name, visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do,
/// each with its raster effects. With `apart`, the Transform effects before `t` make each copy an
/// object of its own ([`copy_leaf`]).
fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> Node {
let (before, rest) = n.appearance.effects.split_at(t);
let mut source = n.clone();
source.appearance.effects = before.to_vec();
let piece = match copied_raster_at(&source) {
Some(at) => copied_raster_art(doc, &source, at, apart),
None => {
let mut art = one_piece(&source);
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc);
if apart {
hoist_copies(&mut art);
}
transform_items(&mut art, doc);
let mut ran = source.appearance.effects.clone();
if carry.skipped() {
carry.hide_skipped(&mut ran);
}
art.appearance.effects = crate::raster::without_geometry(&ran);
art
}
};
let mut art = Node::group(n.id, vec![Arc::new(piece)]);
if let (Some(e), Some(bounds)) = (rest.first(), art.geometric_bounds()) {
let params = merged_params(&e.id, &e.params);
let (m, copies) = crate::distort::transform_map(bounds, &params, n.id.0);
let options = crate::distort::TransformOptions::of(&params);
// The raster effects follow the copies below; Scale Strokes & Effects scales the others.
let mut scaling = copy_scaling(options);
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
let max = Budget::EFFECTS.at_least(art_cost(&art));
copy_art(&mut art, m, copies, scaling, max);
if let Some(children) = art.children_mut() {
// The original is last, and each copy above it is mapped once more by `m`.
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
let mut a = Affine::IDENTITY;
let none = HashSet::new();
for (k, c) in children.iter_mut().rev().enumerate() {
if k > 0 {
a *= step;
follow_art(Arc::make_mut(c), a, &none, Some(&none), None, 0);
}
// Each copy is the piece in a group of its own: the piece takes its place.
if let Some([one]) = c.children().map(Vec::as_slice) {
*c = one.clone();
}
}
}
}
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, apart, doc);
let mut ran = n.appearance.effects.clone();
if carry.skipped() {
carry.hide_skipped(&mut ran);
}
art.appearance.effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default());
art
}
/// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect
/// on for a path whose copies each carry the raster effects listed before it ([`copied_raster_at`]).
pub fn outer_effects(n: &Node) -> &[Effect] {
match copied_raster_at(n) {
Some(t) => n.appearance.effects.get(t..).unwrap_or_default(),
None => &n.appearance.effects,
}
}
/// A group with `n`'s id holding `n` without its transparency, opacity mask and effects: the one
/// piece that `n`'s own geometry effects reshape.
fn one_piece(n: &Node) -> Node {
@@ -909,6 +1039,9 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
{
return None;
}
if let Some(t) = copied_raster_at(n) {
return Some(dressed_keeping_effects(copied_raster_art(doc, n, t, false), n));
}
if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) {
// One element: its pieces never knock each other out.
return crate::bake_type_appearance(doc, n).map(|art| Node { knockout: vectorcraft_doc::Knockout::Off, ..art });
+165 -35
View File
@@ -6,7 +6,7 @@ use serde_json::Value;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve};
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
use crate::solids::wireframe::WireFace;
use crate::solids::{
@@ -338,34 +338,80 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with
/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when
/// the surface it is cast from is past the limits.
fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result<Option<Node>, String> {
///
/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the
/// surface is swept again for its shadow alone.
fn shadow_of(
id: NodeId,
fx: &Effect,
path: &PathData,
item: &AppearanceItem,
b: Rect,
options: Revolve,
kept: Option<SolidFaces>,
) -> Result<Option<Node>, String> {
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) };
let (_, opacity, blend) = paint_of(item);
if opacity <= 0.0 {
return Ok(None);
}
let mut caster = vectorcraft_three_d::ShadowCaster::new();
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)?;
cast_surface(&mut caster, path, b, options, kept)?;
Ok(crate::solids::shadow::art(id, &caster, settings, crate::solids::shadow::Ink { opacity, blend }))
}
/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces
/// its shadow is cast from ([`surface`])?
fn casts(fx: &Effect, opacity: f32) -> bool {
opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
}
/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was
/// drawn, or without them, the surface swept for its shadow alone.
fn cast_surface(
caster: &mut vectorcraft_three_d::ShadowCaster,
path: &PathData,
b: Rect,
options: Revolve,
kept: Option<SolidFaces>,
) -> Result<std::ops::Range<usize>, String> {
match kept {
Some(kept) => caster.add_solid(kept),
None => {
#[cfg(test)]
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)
}
}
}
/// The shadow of group Revolve `fx` cast by the surfaces of the members `shapes` that have one,
/// about the axis of `b`, on one plane; each member's part is as dark as its surface is opaque,
/// in its paint's blending mode, and its opacity mask and blending mode apply to that part
/// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the
/// limits.
fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result<Vec<Arc<Node>>, String> {
/// limits. `kept` holds, member by member, the faces each surface drawn kept for its shadow
/// ([`surface`]); a member without them is swept again for its shadow alone.
fn group_shadow(
id: NodeId,
fx: &Effect,
shapes: &[Profile],
b: Rect,
options: Revolve,
kept: Vec<Option<SolidFaces>>,
) -> Result<Vec<Arc<Node>>, String> {
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) };
let mut caster = vectorcraft_three_d::ShadowCaster::new();
let mut cast = vec![];
let mut kept = kept.into_iter();
for s in shapes {
let kept = kept.next().flatten();
let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue };
// A member whose surface is fully transparent casts nothing.
let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend };
if ink.opacity <= 0.0 {
continue;
}
let faces = caster.revolve(&s.path, vectorcraft_geom::FillRule::NonZero, b, options)?;
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
cast.push((s.scopes.as_slice(), ink, faces));
}
Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes)))
@@ -377,7 +423,8 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R
/// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
/// a face with a part of a graphic is a group of the face and that part.
/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]).
#[allow(clippy::too_many_arguments)]
fn surface(
doc: Option<&Document>,
@@ -391,11 +438,18 @@ fn surface(
blend: vectorcraft_doc::color::BlendMode,
expand: bool,
copies: &mut Copies,
) -> Option<(Vec<Drawn>, Node)> {
cast: bool,
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>)> {
#[cfg(test)]
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
// A loaded file or a profile edited past the limits keeps drawing its source path instead
// of crashing the frame. Commands validate the same evaluator and report its errors.
if fx.id == CLASSIC_REVOLVE {
let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?;
let (facets, kept) = if cast {
vectorcraft_three_d::revolve_facets_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
} else {
(vectorcraft_three_d::revolve_facets(path, b, options).ok()?, None)
};
copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint));
if copies.surfaces > MAX_PAINT_COPIES {
return None;
@@ -405,10 +459,14 @@ fn surface(
let drawn =
facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect();
let p = merged_params(&fx.id, &fx.params);
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p)));
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept));
}
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
let faces = vectorcraft_three_d::revolve(path, b, options).ok()?;
let (faces, kept) = if cast {
vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
} else {
(vectorcraft_three_d::revolve(path, b, options).ok()?, None)
};
copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint));
if copies.surfaces > MAX_PAINT_COPIES {
return None;
@@ -532,7 +590,7 @@ fn surface(
let mut group = Node::group(n.id, children);
group.opacity = opacity;
group.blend = blend;
Some((keys, group))
Some((keys, group, kept))
}
/// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the
@@ -549,8 +607,9 @@ fn in_order<T>(items: Vec<T>, order: &[usize]) -> Vec<T> {
order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect()
}
/// A surface of one object about the bounds of `path`, built with options derived from `fx`.
/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`.
/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and
/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count
/// [`surface`] adds to; its graphics take the symbols of `doc`.
fn object_surface(
doc: Option<&Document>,
n: &Node,
@@ -559,10 +618,11 @@ fn object_surface(
item: &AppearanceItem,
expand: bool,
copies: &mut Copies,
) -> Option<Node> {
) -> Option<(Node, Option<SolidFaces>)> {
let b = path.bounds()?;
let (paint, opacity, blend) = paint_of(item);
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
let cast = casts(fx, opacity);
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept))
}
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
@@ -663,10 +723,11 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
/// instances, blends and clipping groups already resolved), in document coordinates: with the
/// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of
/// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for
/// each member, about one shared axis. The swatches and patterns named by a live-effect plug-in
/// after a fill's or stroke's Revolve are looked up in `doc`. Each face carries the width of the
/// stroke the canvas draws around it ([`surface`]).
pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<WireFace>, String> {
/// each member, about one shared axis. With the effect on the object, group or layer, also the
/// shadow drawn behind them. The swatches and patterns named by a live-effect plug-in after a fill's
/// or stroke's Revolve are looked up in `doc`. Each face carries the width of the stroke the canvas
/// draws around it ([`surface`]).
pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<crate::solids::wireframe::FacesAndShadow, String> {
let faces = |path: &PathData, b: Rect, fx: &Effect, options: Revolve| -> Result<Vec<WireFace>, String> {
if fx.id == CLASSIC_REVOLVE {
let p = merged_params(&fx.id, &fx.params);
@@ -682,7 +743,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec
.iter()
.position(|e| e.visible && is_revolve(&e.id))
.ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let Some(fx) = n.appearance.effects.get(index) else { return Ok((vec![], vec![])) };
let mut shapes = members(n, "Revolve")?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
@@ -691,18 +752,19 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
out.extend(faces(&s.path, b, fx, options)?);
}
return Ok(out);
return Ok((out, group_shadow(n.id, fx, &shapes, b, options, vec![])?));
}
let (path, _) = object_profile(n, "Revolve")?;
let ctx = GeomContext::of(n);
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let Some(fx) = n.appearance.effects.get(index) else { return Ok((vec![], vec![])) };
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
if surface_item(&solid_paints(n)).is_none() {
return Err("the revolved object has no fill or stroke".into());
}
let paints = solid_paints(n);
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")?;
return faces(&path, b, fx, fx_options(fx));
let surface = faces(&path, b, fx, 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);
let mut out = vec![];
@@ -716,7 +778,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
Ok((out, vec![]))
}
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
@@ -762,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));
}
@@ -788,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));
@@ -940,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;
@@ -1055,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 };
@@ -1680,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)]
+203 -67
View File
@@ -7,7 +7,9 @@ use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask};
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
use vectorcraft_pathops::BoolOp;
use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, View};
use vectorcraft_three_d::{
Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View,
};
#[cfg(test)]
use vectorcraft_doc::color::Color;
@@ -236,6 +238,30 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
}
}
/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast
/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the
/// classic effects cast no shadow: they keep no faces.
fn facets_and_faces(
id: &str,
path: &PathData,
rule: FillRule,
bounds: Rect,
p: &Value,
cast: bool,
) -> Result<(Vec<Facet>, Option<SolidFaces>), String> {
let view = view_options(p);
#[cfg(test)]
if cast && id == EXTRUDE {
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
}
let built = match id {
EXTRUDE if cast => vectorcraft_three_d::extrude_shadowed(path, rule, bounds, extrude_options(p), view),
ROTATE if cast => vectorcraft_three_d::plane_shadowed(path, rule, bounds, view),
_ => return facets(id, path, rule, bounds, p).map(|f| (f, None)),
};
built.map(|(f, faces)| (f, Some(faces)))
}
/// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not
/// need the object.
fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
@@ -693,7 +719,9 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
#[cfg(test)]
thread_local! {
/// How many solids [`built_solids`] and [`meshes_for`] have built on this thread, for the tests.
static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Rotate's planes drawn, the solids built to cast a shadow ([`cast_shadow`]) and Revolve's
/// surfaces count too.
pub(crate) static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and
/// [`built_solids`] have built on this thread, for the tests.
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
@@ -712,10 +740,35 @@ fn built_solids<'a>(
bounds: Rect,
limit: usize,
) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a {
built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f)))
}
/// One solid's facets and, when its shadow is cast, the faces it is cast from.
type CastingSolid = (Vec<Facet>, Option<SolidFaces>);
/// The surfaces of an object's solids, and the faces each solid kept for its shadow
/// ([`surfaces_for`]).
type SurfacesAndFaces = (Vec<Arc<Node>>, Vec<Option<SolidFaces>>);
/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow
/// is cast from, from the same build ([`SolidFaces`]).
fn built_solids_cast<'a>(
id: &'a str,
p: &'a Value,
parts: &'a [Part<'a>],
bounds: Rect,
limit: usize,
cast: bool,
) -> impl Iterator<Item = Result<Option<CastingSolid>, String>> + 'a {
// Inflate's eye is placed for every puff together, as far away as the highest needs.
let mut inflated = (id == INFLATE).then(|| {
let mut inflated = (id == INFLATE).then(|| -> Box<dyn Iterator<Item = Result<CastingSolid, String>>> {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
vectorcraft_three_d::inflate_each(&shapes, bounds, inflate_options(p), view_options(p))
let (o, view) = (inflate_options(p), view_options(p));
if cast {
Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces)))))
} else {
Box::new(vectorcraft_three_d::inflate_each(&shapes, bounds, o, view).map(|r| r.map(|f| (f, None))))
}
});
let mut kept = 0usize;
let mut ended = false;
@@ -729,13 +782,13 @@ fn built_solids<'a>(
Some(each) => {
#[cfg(test)]
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
each.next().unwrap_or_else(|| Ok(vec![]))
each.next().unwrap_or_else(|| Ok((vec![], None)))
}
None => facets(id, area, *rule, bounds, p),
None => facets_and_faces(id, area, *rule, bounds, p, cast),
};
let result = match built {
Ok(f) => {
kept = kept.saturating_add(f.len());
kept = kept.saturating_add(f.0.len());
if kept > limit { Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()) } else { Ok(Some(f)) }
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => Ok(None),
@@ -1364,18 +1417,31 @@ 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 = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), 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))
}
/// The shadow [`art_for`] draws for effect `fx` on `shapes` behind the surfaces of object `id`:
/// none with the shadow off, and an error when it is past the limits.
pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result<Vec<Arc<Node>>, String> {
Ok(match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes)? {
Some((caster, settings, cast)) => shadow::scoped_art(id, &caster, settings, cast, has_masks(shapes)),
None => vec![],
})
}
/// What the shadow of the solids [`surfaces_for`] builds for effect `id` with parameters `p` on
/// `shapes` is cast from, on one plane: the faces of every solid, the shadow's settings and the
/// faces of each solid of visible art with its member's scopes and ink. `None` with the shadow
@@ -1402,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));
}
@@ -1413,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
@@ -1438,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>>);
@@ -1496,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]),
}
@@ -1529,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));
}
}
}
@@ -1546,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());
@@ -1579,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;
@@ -1595,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;
}
@@ -1616,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.
@@ -1757,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
@@ -1787,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 {
@@ -1807,24 +1949,18 @@ fn in_one_order(
}
let order = draw_order(&placed, sealed);
// Each graphic goes right after the last of the faces it is drawn on, among the surfaces that
// share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a
// mask that ends at its surface.
// share it ([`placed_graphics`]): those from the first of them to its own.
let last: Vec<Option<usize>> = arts
.iter()
.map(|(at, face, _)| {
let at = at - first;
let from = if masks.get(at).is_some_and(Option::is_some) {
at
} else {
masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1)
};
.map(|(from, at, face, _)| {
let (from, at) = (from.saturating_sub(first), at - first);
order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface)))
})
.collect();
let mut drawn: Vec<(usize, Arc<Node>)> = Vec::with_capacity(order.len() + arts.len());
for (at, k) in order.into_iter().enumerate() {
drawn.extend(faces.get_mut(k).and_then(Option::take));
drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| {
drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (_, surface, _, art))| {
let mut art = art.clone();
if let Some(mask) = masks.get(surface - first).cloned().flatten() {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask);
+111 -55
View File
@@ -617,10 +617,11 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
};
// The graphic carries the cap's mask, so it is hidden where the gradient is transparent.
assert_eq!(masks(&art), vec![true]);
// With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own
// and the stroke's outline gets an unmasked one.
// With an opaque stroke drawn after the fill, the fill and the stroke share one graphic, drawn
// after the stroke's cap as for a fill without a mask, and it takes the stroke's surface,
// which carries no mask.
n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0)));
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![false]);
}
/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its
@@ -649,23 +650,56 @@ fn face_paths(art: &Node) -> Vec<PathData> {
out
}
/// The graphics in `art` (clip groups of solid-color paths), in drawing order: for each, how many
/// faces ([`face_paths`]) are drawn before it, whether it carries an opacity mask, its opacity and
/// its blending mode.
fn graphic_places(art: &Node) -> Vec<(usize, bool, f32, BlendMode)> {
fn walk(n: &Node, faces: &mut usize, out: &mut Vec<(usize, bool, f32, BlendMode)>) {
match &n.kind {
NodeKind::Group { children, clip: true } => {
let graphic = children.get(1).is_some_and(|inner| match &inner.kind {
NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| {
p.path_data().is_some()
&& p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some()))
}),
_ => false,
});
if graphic {
out.push((*faces, n.extras().mask.is_some(), n.opacity, n.blend));
} else if children.first().and_then(|c| c.path_data()).is_some() {
*faces += 1;
}
}
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, faces, out)),
_ => *faces += usize::from(n.path_data().is_some()),
}
}
let mut out = vec![];
walk(art, &mut 0, &mut out);
out
}
/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke
/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without
/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's.
/// the graphic, and draws the graphic once, where it goes in a gradient without transparent stops:
/// after the stroke's cap, without a mask.
#[test]
fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
let solid = |graphics: Value| {
// A red gradient whose last stop has opacity `last`.
let gradient = |last: f32| {
let mut stop = GradientStop::new(1.0, red());
stop.opacity = last;
GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]))
};
let solid = |fill: &GradientPaint, graphics: Value| {
let mut n = object(
EXTRUDE,
json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}),
);
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient.clone()));
f.paint = Paint::Gradient(Box::new(fill.clone()));
}
// A gradient stroke: a solid color under the colored light would be one composite.
let blues = Gradient::new(
@@ -677,54 +711,76 @@ fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
n.appearance.items.push(AppearanceItem::Stroke(stroke));
solid_art_in(Some(&d), &n).unwrap()
};
let with = solid(json!([{"symbol": "Mark"}]));
let without = solid(json!([]));
let masked = gradient(0.25);
let with = solid(&masked, json!([{"symbol": "Mark"}]));
let without = solid(&masked, json!([]));
assert!(face_paths(&without).len() > 20, "the faces are found");
assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order");
// The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the
// symbol's red square); the fill's, whose surface carries the mask, carries it too.
let mut masked = vec![];
with.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& let [_, inner] = children.as_slice()
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
&& paths.iter().any(|p| {
p.appearance.items.iter().any(|i| match i {
AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3),
AppearanceItem::Stroke(_) => false,
})
})
{
masked.push(c.extras().mask.is_some());
}
});
masked.sort_unstable();
assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask");
// The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn
// after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face,
// the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds.
let mut drawn: Vec<(&str, Rect)> = vec![];
with.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& c.extras().mask.is_some()
&& let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds)
{
drawn.push(("graphic", bounds));
}
let first_stop = c.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) => match &f.paint {
Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()),
_ => None,
},
AppearanceItem::Stroke(_) => None,
});
if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) {
drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds));
}
});
let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap();
let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0;
assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic");
let mut mask = false;
with.walk(&mut |c| mask |= c.extras().mask.is_some());
assert!(mask, "the fill's faces carry the gradient's mask");
let opaque = solid(&gradient(1.0), json!([{"symbol": "Mark"}]));
assert_eq!(face_paths(&opaque), face_paths(&with));
let places = graphic_places(&with);
assert_eq!(places.iter().map(|(_, mask, opacity, blend)| (*mask, *opacity, *blend)).collect::<Vec<_>>(), [(false, 1.0, BlendMode::Normal)]);
assert_eq!(places, graphic_places(&opaque), "drawn where a fill without a mask draws it");
}
/// A plane in a gradient with transparent stops under a colored light draws its graphic with the
/// fill's mask, and with a dashed stroke draws it once, after the stroke, without a mask.
#[test]
fn a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
let mut n = object(ROTATE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient));
}
let places = graphic_places(&solid_art_in(Some(&d), &n).unwrap());
assert_eq!(places.iter().map(|(_, mask, ..)| *mask).collect::<Vec<_>>(), [true]);
let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0);
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
n.appearance.items.push(AppearanceItem::Stroke(stroke));
let art = solid_art_in(Some(&d), &n).unwrap();
let places = graphic_places(&art);
assert_eq!(places, [(face_paths(&art).len(), false, 1.0, BlendMode::Normal)], "one graphic, drawn after every face");
}
/// Members of a group share a graphic only when neither surface carries an opacity mask, while
/// one member's fill and stroke share theirs.
#[test]
fn members_in_transparent_gradients_keep_graphics_of_their_own() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]))));
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
let (left, right) = (Rect::new(0.0, 0.0, 50.0, 100.0), Rect::new(50.0, 0.0, 100.0, 100.0));
// Whether each graphic drawn on the group of `members` carries an opacity mask, in order.
let masks = |members: Vec<Node>| {
let mut group = Node::group(NodeId(3), members.into_iter().map(Arc::new).collect());
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 1000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let mut masks: Vec<bool> = graphic_places(&solid_art_in(Some(&d), &group).unwrap()).iter().map(|(_, mask, ..)| *mask).collect();
masks.sort_unstable();
masks
};
assert_eq!(masks(vec![square(1, left, gradient.clone()), square(2, right, gradient.clone())]), [true, true]);
// With a dashed stroke, the first member's fill and stroke share one graphic, without a mask.
let mut stroked = square(1, left, gradient.clone());
let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0);
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
stroked.appearance.items.push(AppearanceItem::Stroke(stroke));
assert_eq!(masks(vec![stroked, square(2, right, gradient.clone())]), [false, true]);
// A member with a gray stroke listed before its fill in the gradient does not share its
// graphic with the gray member after it.
let mut layered = square(1, left, gradient);
layered.appearance.items.insert(0, AppearanceItem::Stroke(StrokeLayer::new(gray.clone(), 6.0)));
assert_eq!(masks(vec![layered, square(2, right, gray)]), [false, true]);
}
#[test]
+89
View File
@@ -223,3 +223,92 @@ fn expand_appearance_keeps_the_shadow_as_a_path() {
assert!((after.x0 - before.x0 - 40.0).abs() < 1e-6, "{id}: {before:?} {after:?}");
}
}
/// A square filled red and stroked blue, its stroke as opaque as `stroke`.
fn stroked_square(id: u64, dx: f64, stroke: f32) -> Node {
let mut n = square_node(id, dx);
n.appearance = Appearance::basic(Paint::solid(RED), Paint::solid(Color::rgb(0.1, 0.2, 0.9)), 6.0).into();
for item in &mut n.appearance.items {
if let AppearanceItem::Stroke(s) = item {
s.opacity = stroke;
}
}
n
}
/// Objects with 3D effect `id` and its shadow on (`params`): a filled and stroked square, one whose
/// stroke is half transparent, one whose stroke is fully transparent, and a group of two members,
/// one of them at half opacity.
fn shadowed(id: &str, params: &Value) -> Vec<Node> {
let with = |mut n: Node| {
n.appearance.effects.push(crate::new_effect(id, params).unwrap());
n
};
let mut half = stroked_square(2, 200.0, 1.0);
half.opacity = 0.5;
let group = Node::group(NodeId(9), vec![Arc::new(stroked_square(1, 0.0, 1.0)), Arc::new(half)]);
vec![with(stroked_square(1, 0.0, 1.0)), with(stroked_square(1, 0.0, 0.5)), with(stroked_square(1, 0.0, 0.0)), with(group)]
}
/// The settings the shadows of effect `id` are compared with: the defaults, turned with
/// perspective, and under a colored light, below the object for Extrude & Bevel, Inflate and
/// Rotate and behind it for Revolve.
fn shadow_settings(id: &str) -> [Value; 3] {
let position = if id == crate::REVOLVE { "behind" } else { "below" };
[
json!({"shadow": true}),
json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "shadowDistance": 40}),
json!({"shadow": true, "shadowPosition": position, "shadowDistance": 30, "lightColor": "#ff8040", "twist": 30}),
]
}
/// How many solids drawing the art of `n` with effect `id` builds.
fn solids_built(n: &Node, id: &str) -> usize {
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
assert!(art(n, id).is_some(), "{id}");
SOLIDS_BUILT.with(std::cell::Cell::get) - start
}
/// Drawing a 3D object with its shadow on builds each of its solids once: the shadow is cast from
/// the faces the solids drawn kept, so it builds no more solids than the art without a shadow.
#[test]
fn a_shadowed_3d_object_builds_each_solid_once() {
for id in CASTING {
for params in shadow_settings(id) {
for (lit, mut plain) in shadowed(id, &params).into_iter().zip(shadowed(id, &params)) {
plain.appearance.effects.iter_mut().for_each(|e| e.params["shadow"] = json!(false));
let mut cast = 0;
art(&lit, id).unwrap().walk(&mut |c| cast += usize::from(shadow_opacity(c).is_some()));
assert!(cast > 0, "{id} {params}");
let built = solids_built(&plain, id);
assert!(built > 0, "{id}");
assert_eq!(solids_built(&lit, id), built, "{id} {params}: the shadow builds no solid of its own");
}
}
}
}
/// The shadow of the faces Extrude & Bevel, Inflate and Rotate kept when they drew their solids,
/// to the bit: the shadow [`cast_shadow`] casts from solids built for the shadow alone.
#[test]
fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() {
for id in [EXTRUDE, INFLATE, ROTATE] {
for params in shadow_settings(id) {
for n in shadowed(id, &params) {
let (_, fx) = solid(&n.appearance.effects).unwrap();
let shapes = if is_container(&n) {
members(&n, "").unwrap()
} else {
let (path, rule) = profile(&n).unwrap();
vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }]
};
let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap();
let p = crate::merged_params(&fx.id, &fx.params);
let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap();
let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes));
assert!(!alone.is_empty(), "{id} {params}");
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
}
}
}
}
+45 -19
View File
@@ -53,8 +53,8 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<Path
// Revolve's art is cut for Revolve whatever other 3D effect the object carries, as the canvas
// cuts it ([`crate::revolve_art_in`]).
let n = &*if revolve { resolve_for(doc, n, label, false)? } else { resolve(doc, n, label)? };
let faces = if revolve { crate::revolve::revolve_face_paths(doc, n)? } else { solid_face_paths(doc, n)? };
let faces: Vec<PathData> = after_geometry(doc, n, faces, revolve).into_iter().map(|f| f.path).collect();
let (faces, shadow) = if revolve { crate::revolve::revolve_face_paths(doc, n)? } else { solid_face_paths(doc, n)? };
let faces: Vec<PathData> = after_geometry(doc, n, faces, shadow, revolve).into_iter().map(|f| f.path).collect();
let wire = edges(&faces)?;
if wire.is_empty() {
return Err(format!("{label} draws no faces for this object"));
@@ -63,13 +63,14 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<Path
}
/// `faces` reshaped by the visible geometry effects after the 3D effect of `n`'s own that drew them
/// ([`reshaped`]): its first visible Revolve when `revolve` is set, else its first visible Extrude &
/// Bevel, Inflate or Rotate.
fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec<WireFace>, revolve: bool) -> Vec<WireFace> {
/// ([`reshaped_beside`]): its first visible Revolve when `revolve` is set, else its first visible
/// Extrude & Bevel, Inflate or Rotate. The effects measure the faces together with `shadow`, the
/// shadow the canvas draws behind them, as they measure the drawn art.
fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec<WireFace>, shadow: Vec<Arc<Node>>, revolve: bool) -> Vec<WireFace> {
let fx = &n.appearance.effects;
let drawn = if revolve { fx.iter().position(|e| e.visible && crate::revolve::is_revolve(&e.id)) } else { solid(fx).map(|(i, _)| i) };
let Some(index) = drawn else { return faces };
reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) })
reshaped_beside(faces, shadow, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) })
}
/// One face of a drawn 3D surface: its outline and the width of the stroke the canvas draws around
@@ -86,6 +87,15 @@ pub(crate) struct WireFace {
/// the canvas, so an Outline Stroke outlines that stroke. `ctx` gives the object's id, the seed of a
/// random Transform, and the document.
pub(crate) fn reshaped(faces: Vec<WireFace>, later: &[Effect], ctx: &GeomContext) -> Vec<WireFace> {
reshaped_beside(faces, vec![], later, ctx)
}
/// The name the faces carry through [`reshaped_beside`], which tells them from the shadow.
const FACE: &str = "face";
/// [`reshaped`] with `shadow`, the shadow drawn behind the faces, in the art the effects reshape:
/// each effect measures the faces and the shadow together, and only the faces are returned.
fn reshaped_beside(faces: Vec<WireFace>, shadow: Vec<Arc<Node>>, later: &[Effect], ctx: &GeomContext) -> Vec<WireFace> {
let after: Vec<&Effect> = later.iter().filter(|e| e.visible && is_geometry(&e.id)).collect();
if after.is_empty() {
return faces;
@@ -95,29 +105,44 @@ pub(crate) fn reshaped(faces: Vec<WireFace>, later: &[Effect], ctx: &GeomContext
let face = |f: WireFace| {
let items =
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), f.stroke))];
Arc::new(Node::path(id, f.path, Appearance { items, ..Default::default() }))
let mut face = Node::path(id, f.path, Appearance { items, ..Default::default() });
face.name = Some(FACE.into());
Arc::new(face)
};
let mut art = Node::group(id, faces.into_iter().map(face).collect());
let mut art = Node::group(id, shadow.into_iter().chain(faces.into_iter().map(face)).collect());
crate::reshape::reshape_leaves(&mut art, &after, later, ctx.doc);
let mut out = vec![];
art.walk(&mut |c| {
if let Some(path) = c.path_data() {
out.push(WireFace { path: path.clone(), stroke: c.appearance.stroke().map_or(0.0, |s| s.width) });
}
});
face_paths(&art, false, &mut out);
out
}
/// The faces in `n` ([`FACE`]), `inside` one or not, each with the width of its stroke: a face that
/// a Transform effect copies or a live-effect plug-in cuts into pieces becomes a group with its name.
fn face_paths(n: &Node, inside: bool, out: &mut Vec<WireFace>) {
let inside = inside || n.name.as_deref() == Some(FACE);
if inside && let Some(path) = n.path_data() {
out.push(WireFace { path: path.clone(), stroke: n.appearance.stroke().map_or(0.0, |s| s.width) });
}
for c in n.children().into_iter().flatten() {
face_paths(c, inside, out);
}
}
/// The faces of a 3D effect on an object, group or layer itself, and the shadow the canvas draws
/// behind them (none with the shadow off, or with the effect on fills and strokes).
pub(crate) type FacesAndShadow = (Vec<WireFace>, Vec<Arc<Node>>);
/// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect
/// on the object, its solids; with it on fills and strokes, the solid of each; on a group or layer,
/// the solids of its members, about one shared axis. The swatches and patterns named by a live-effect
/// plug-in after a fill's or stroke's 3D effect are looked up in `doc`.
fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<WireFace>, String> {
/// the solids of its members, about one shared axis. With the effect on the object, group or layer,
/// also the shadow drawn behind them. The swatches and patterns named by a live-effect plug-in after
/// a fill's or stroke's 3D effect are looked up in `doc`.
fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<FacesAndShadow, String> {
if is_container(n) {
let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
let mut shapes = members(n, label_of(&fx.id))?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
return facet_paths(fx, &shapes);
return Ok((facet_paths(fx, &shapes)?, super::shadow_for(n.id, fx, &shapes)?));
}
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
let (path, rule) = object_profile(n, label)?;
@@ -125,7 +150,8 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<WireFace>, S
let (sources, paints) = solid_paint_sources(n);
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]);
let shapes = [Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }];
return Ok((facet_paths(fx, &shapes)?, super::shadow_for(n.id, fx, &shapes)?));
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
@@ -136,7 +162,7 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<WireFace>, S
out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
Ok((out, vec![]))
}
/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and
@@ -222,6 +222,32 @@ fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() {
}
}
/// A Transform effect after the 3D effect scales the faces about the center of the drawn art with
/// its shadow, as it scales the surfaces on the canvas.
#[test]
fn a_later_transform_measures_the_faces_with_their_shadow() {
for id in [super::super::EXTRUDE, crate::REVOLVE] {
let scale = crate::new_effect("distort.transform", &json!({"scaleH": 50.0, "scaleV": 50.0})).unwrap();
let mut n = solid_square(id, json!({"shadow": true, "shadowDistance": 100}));
n.appearance.effects.push(scale.clone());
let wire = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}")));
let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { super::super::solid_art(&n) }.unwrap();
let mut drawn = art.clone();
let fx: Vec<&Effect> = art.appearance.effects.iter().collect();
crate::reshape::reshape_leaves(&mut drawn, &fx, &art.appearance.effects, None);
// The shadow is the art's first member; the surfaces follow it.
let surfaces: Vec<PathData> = drawn.children().unwrap().iter().skip(1).flat_map(|c| face_paths(c)).collect();
let a = bounds(&surfaces);
for (x, y) in [(wire.x0, a.x0), (wire.y0, a.y0), (wire.x1, a.x1), (wire.y1, a.y1)] {
assert!((x - y).abs() < 1e-6, "{id}: {wire:?} {a:?}");
}
// Without the shadow, the faces are scaled about their own center.
let mut alone = solid_square(id, json!({}));
alone.appearance.effects.push(scale);
assert!((bounds(&three_d_wireframe_in(None, &alone).unwrap()).x0 - wire.x0).abs() > 1.0, "{id}");
}
}
/// With two 3D effects, a geometry effect between them reshapes the faces of the one drawn only
/// once: Revolve is drawn, so a Transform before it moves its profile and not its faces again.
#[test]
+42
View File
@@ -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
+95 -3
View File
@@ -584,8 +584,9 @@ fn image(id: u64, effects: Vec<Effect>) -> Node {
/// A group's Transform effect transforms, with Scale Strokes & Effects off or on, the raster
/// effects that a member's own Transform effect with copies holds back: they keep their value
/// through the member's effect and transform with the group's. That holds for a shadow listed
/// before the member's copying effect, one listed after it, a fill's shadow under it, the shadow
/// of a member of a nested group with such an effect, and an image's shadow.
/// before the member's copying effect (which each copy carries), one listed after it, a fill's
/// shadow under it, the shadow of a member of a nested group with such an effect, and an image's
/// shadow.
#[test]
fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() {
let copies = || transform(json!({"moveH": 60, "copies": 1}));
@@ -605,7 +606,8 @@ fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() {
let art = crate::evaluate_container(None, &g).unwrap();
for id in [71, 72, 73, 75, 76] {
let drawn = shadows_in(&node_in(&art, id));
assert!(near(&drawn, &[want]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
let wanted = if id == 71 { vec![want, want] } else { vec![want] };
assert!(near(&drawn, &wanted), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
}
}
}
@@ -841,3 +843,93 @@ fn copying_and_object_disabled_transforms_keep_their_existing_shadow_rules() {
assert!(close(drawn_shadow(&effects), (10.0, 5.0, 4.0)), "{t:?}: {:?}", drawn_shadow(&effects));
}
}
/// The blur of every Drop Shadow drawn on `n` and the nodes under it, in the order of
/// [`shadows_in`].
fn shadow_blurs_in(n: &Node) -> Vec<f64> {
let mut out = vec![];
n.walk(&mut |m| {
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
for list in lists {
for r in raster_effects(list) {
if let RasterFx::DropShadow { blur, .. } = r {
out.push(blur);
}
}
}
});
out
}
/// How many paths `n` holds.
fn paths_in(n: &Node) -> usize {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, vectorcraft_doc::NodeKind::Path { .. })));
count
}
/// A Transform effect that makes copies gives each copy the shadow listed before it, moved, turned,
/// reflected and scaled with that copy, the last copy lowest: drawn, expanded and baked. The object
/// itself keeps the shadow as it is, and paints none around all of them. With Scale Strokes &
/// Effects on, the shadow is not scaled a second time.
#[test]
fn each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it() {
let cases = [
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0), (10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
(json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "random": true}), vec![(10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]),
];
for (params, want, blurs) in cases {
let n = square(91, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]);
assert!(crate::has_transform_art(&n), "{params}");
assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}");
let random = params["random"].as_bool().unwrap_or(false);
for (how, art) in
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
{
let drawn = shadows_in(&art);
assert_eq!(paths_in(&art), want.len(), "{params}: {how} {art:?}");
if random {
// Random scales the copy by a share of the 200 %, and its shadow with it; the object
// keeps its own.
assert_eq!(drawn.len(), want.len(), "{params}: {how} {drawn:?}");
assert!(near(&drawn[1..], &want[1..]), "{params}: {how} {drawn:?}");
continue;
}
assert!(near(&drawn, &want), "{params}: {how} {drawn:?}");
let b = shadow_blurs_in(&art);
assert!(b.len() == blurs.len() && b.iter().zip(&blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{params}: {how} blurs {b:?}");
}
}
}
/// A shadow listed after a Transform effect that makes copies paints once around all of them, and
/// one listed before it on each copy. A Transform effect that makes no copies, or has Transform
/// Objects off, leaves the object's shadows on the object.
#[test]
fn a_shadow_after_a_copying_transform_paints_once_around_the_copies() {
let n = square(92, vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)]);
let art = crate::reshape(None, &n, None).unwrap();
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{:?}", shadows_in(&art));
assert_eq!(crate::outer_effects(&n).len(), 2);
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
let n = square(93, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
assert!(!crate::has_transform_art(&n), "{params}");
assert_eq!(crate::outer_effects(&n).len(), 2, "{params}");
}
}
/// Copies that stop at the effect budget each keep their shadow: no copy goes without one, and no
/// shadow is left without its copy.
#[test]
fn copies_past_the_budget_each_keep_their_shadow() {
let n = path_node(94, wavy(30_000), vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]);
let art = crate::reshape(None, &n, None).unwrap();
let paths = paths_in(&art);
assert!(paths > 1 && paths < 1001, "{paths}");
assert_eq!(shadows_in(&art).len(), paths);
}
+1 -1
View File
@@ -827,7 +827,7 @@ pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
pub use plugin_call::{Location, key_location, location_in, location_keys};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
pub(crate) use vectorcraft_doc::range::parse_range;
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
+7 -5
View File
@@ -23,7 +23,7 @@ use vectorcraft_render::effects;
use super::super::appearance::series_children_in_paint_order;
use super::super::colorcmds::edit_if_changed;
use super::super::edit::selected_roots;
use super::super::graph::capture_series_object_opacity;
use super::super::graph::{capture_series_object_opacity, series_groups_among};
use super::super::menucmds::whole_or;
use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns};
use super::super::typecmd::refresh_bounds_of;
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Opacity",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md) → {count}",
has_selection,
randomize_opacity
),
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sort Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md). A run that changes nothing makes no step → {count}",
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}",
has_multi,
sort
),
@@ -418,9 +418,11 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
/// Store on their graphs the opacity just given to the paths among `changed` (objects whose opacity changed) that are
/// directly in a graph series, with their blend mode, so that every path of the series has them when the graph is drawn
/// again; the frontmost of them in a series sets them.
/// again; the frontmost of them in a series sets them. A series group among `changed` has its own opacity stored for the
/// group.
fn keep_series_opacity(d: &mut vectorcraft_doc::Document, changed: &[NodeId]) {
let marks = series_children_in_paint_order(d, changed);
let mut marks = series_children_in_paint_order(d, changed);
marks.extend(series_groups_among(d, changed));
capture_series_object_opacity(d, &marks);
}
+15 -12
View File
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Breaks",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
"{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story, locked and hidden frames included), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
has_selection,
remove_breaks
),
@@ -821,9 +821,9 @@ fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize {
}
/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or
/// start of a frame between words of the frames on either side becomes a space. Each editable frame
/// (each frame when `all`) comes with its own breaks, at its own bytes.
fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(NodeId, Vec<(usize, bool)>)> {
/// start of a frame between words of the frames on either side becomes a space. Each frame comes
/// with its own breaks, at its own bytes, its locked and hidden frames included.
fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> {
let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect();
let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect();
// The breaks in story order, handed to the frames in one pass.
@@ -836,9 +836,7 @@ fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(Node
while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) {
own.push((at - start, space));
}
if all || d.is_editable(id) {
out.push((id, own));
}
out.push((id, own));
start = end;
}
out
@@ -859,7 +857,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
// Each type object with the breaks that go from it.
let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing {
Some(_) if !story.is_empty() => story_cuts(d, &story, brk, false),
Some(_) if !story.is_empty() => story_cuts(d, &story, brk),
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))]
.into_iter()
.filter(|(id, ..)| d.is_editable(*id))
@@ -871,20 +869,25 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
let named: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let threads = thread_index(d);
let mut done = std::collections::HashSet::new();
// The threads already found not to be a story whose frames are all among them: their
// other frames are read one at a time without going through the thread again.
let mut partial = std::collections::HashSet::new();
let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![];
for &id in &ids {
if !done.insert(id) {
continue;
}
let story = match threads.get(&id).and_then(|&i| d.text_threads.get(i)) {
Some(thread) => crate::cmd::threads::story_in(d, thread, id),
let thread = threads.get(&id).copied();
let story = match thread.filter(|i| !partial.contains(i)).and_then(|i| d.text_threads.get(i)) {
Some(frames) => crate::cmd::threads::story_in(d, frames, id),
None => vec![],
};
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);
out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk)));
}
}
@@ -379,6 +379,38 @@ fn remove_breaks_reads_the_threads_once() {
}
}
/// Remove Breaks reads each named frame of a story that is not all named on its own, in the order
/// named and each once, as one undo step, and goes through that story's frames once for all of them.
#[test]
fn remove_breaks_goes_through_a_partly_named_story_once() {
for (kind, brk) in [("line", '\u{2028}'), ("paragraph", '\n')] {
let mut s = session();
let a = text(&mut s, json!({"x": 10, "y": 20, "text": "a\u{2028}b\n".repeat(40), "size": 12, "area": {"width": 150, "height": 60}}));
let mut roots = vec![a];
for i in 0..4 {
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 100 + 70 * i, "width": 150, "height": 60})).unwrap();
roots.push(NodeId(r["id"].as_u64().unwrap()));
}
select(&mut s, &roots);
s.execute("text.thread.create", &json!({})).unwrap();
let f = s.doc().unwrap().doc.text_threads[0].clone();
assert_eq!(f.len(), 5);
let named = [f[4], f[1], f[3]];
let breaks: Vec<usize> = named.iter().map(|id| obj(&s, *id).plain_text().matches(brk).count()).collect();
assert!(breaks.iter().all(|n| *n > 0), "{kind}: each named frame holds breaks: {breaks:?}");
let before = doc_json(&s);
let steps = undo_steps(&s);
let builds = crate::cmd::threads::story_builds();
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": kind, "ids": [f[4].0, f[1].0, f[4].0, f[3].0]})).unwrap();
assert_eq!(crate::cmd::threads::story_builds() - builds, 1, "{kind}: the story's frames are gone through once");
assert_eq!(r["removed"].as_u64(), Some(breaks.iter().sum::<usize>() as u64), "{kind}");
assert_eq!(ids(&r), named, "{kind}");
assert_eq!(undo_steps(&s), steps + 1, "{kind}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(doc_json(&s), before, "{kind}");
}
}
/// Lock `id` (`locked`), else hide it, as an undo step of its own.
fn lock_or_hide(s: &mut Session, id: NodeId, locked: bool) {
s.edit("Lock or Hide", |d, _| {
+4 -1
View File
@@ -2,9 +2,11 @@
//! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together
//! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art
//! for vinyl cutting ([`weed`]). Banner Hems and Grommets marks the hems and grommets of a banner
//! ([`banner`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's.
//! ([`banner`]). Nest Shapes packs the selected art onto a sheet or a roll of material ([`nest`]).
//! Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's.
mod banner;
mod nest;
mod stencil;
mod weed;
@@ -14,5 +16,6 @@ pub fn specs() -> Vec<CommandSpec> {
let mut v = stencil::specs();
v.extend(weed::specs());
v.extend(banner::specs());
v.extend(nest::specs());
v
}
@@ -0,0 +1,403 @@
//! Nest Shapes (`addon.cutting.nest`), a command of the built-in Cutting Tools add-on that packs
//! the selected objects onto a sheet or a roll of material by their bounding boxes
//! (<https://en.wikipedia.org/wiki/Packing_problems>). The sheet is an
//! artboard, or a set size from the artboard's top-left corner; a roll is as wide as the sheet
//! and has no end. The objects are moved, and with `rotate` turned a quarter turn when that places
//! them better; they are never scaled or changed otherwise.
#[cfg(test)]
mod tests;
use std::collections::VecDeque;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use vectorcraft_render::effects;
use super::super::super::edit::selected_roots_to_transform;
use super::super::super::object::{keep_compound_aligned, transform_node, transform_patterns};
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, check_switches, cmd, has_selection, switch_or};
use crate::{Result, Session};
/// Nest Shapes' command.
pub const NEST: &str = "addon.cutting.nest";
/// The largest sheet width or height, in points.
const MAX_SIZE: f64 = 1_000_000.0;
/// The largest margin or spacing, in points.
const MAX_GAP: f64 = 100_000.0;
/// The most objects one run nests.
const MAX_SHAPES: usize = 10_000;
/// How far a box may reach past the sheet's edge and still fit (rounding).
const EPS: f64 = 1e-9;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.cutting.nest",
"Nest Shapes…",
["Object", "Plug-ins", "Cutting Tools"],
None,
"{roll?: bool (false: a sheet `width` × `height`; true: a roll `width` wide with no end), width?: pt 0..1000000 (0: the artboard's width), height?: pt 0..1000000 (0: the artboard's height; not used with roll), margin?: pt 0..100000 (18: kept clear inside each edge of the sheet; on a roll, the sides and the start), spacing?: pt 0..100000 (9: kept between two objects), rotate?: bool (false: objects keep their orientation; true: an object may turn 90° clockwise where that puts its bottom edge higher, or where only the turned object fits), usePreviewBounds?: bool (true: objects are measured with their strokes and effects, the reach of shadows, glows and blurs included; false: by their geometry), artboard?: index (0-based; the sheet's artboard; default: the artboard under the center of the selection, else the first), patterns?: bool (Transform Patterns: pattern fills and strokes move with the art; default: prefs transformPatternTiles)} move the selected objects onto the sheet or roll, which starts at the artboard's top-left corner, packed by their bounding boxes: the tallest first (with rotate, the longest side first), each where its bottom edge is highest and then furthest left, without resizing them. An object on the pixel grid moves by whole points and takes 1 pt more room across and down; a path of a pixel-aligned compound path is not turned. Objects that do not fit on the sheet go in a column to the right of it, `spacing` from its edge and from each other, from its top, in stacking order (back to front). Objects without bounds (an empty group) are not moved. One undo step; nothing changes when no object moves → {placed: count, unplaced: [ids of the objects put beside the sheet], rotated: [ids], skipped: [ids of the objects without bounds], length: pt (from the sheet's top edge to the bottom margin below the lowest object placed)}",
has_selection,
nest
)]
}
/// The length `p` gives for `key`, from 0 to `max`, or `default`.
fn length(p: &Value, key: &str, default: f64, max: f64) -> Result<f64> {
match length_given(p, key, NEST)? {
None => Ok(default),
Some(v) if (0.0..=max).contains(&v) => Ok(v),
Some(_) => Err(bad(NEST, format!("`{key}` must be from 0 to {max} pt"))),
}
}
/// One stretch of a skyline: from `x`, `w` wide, filled down to `y`.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Span {
x: f64,
w: f64,
y: f64,
}
/// Bottom-left packing of boxes on a skyline: a strip `width` wide and `height` deep
/// (`f64::INFINITY` for a roll), whose filled part is the spans' outline along its top.
struct Skyline {
spans: Vec<Span>,
width: f64,
height: f64,
}
impl Skyline {
fn new(width: f64, height: f64) -> Self {
Skyline { spans: vec![Span { x: 0.0, w: width, y: 0.0 }], width, height }
}
/// Where a box `w` × `h` goes: at the left edge of a span, as high as the spans under it
/// allow, choosing the place where its bottom edge is highest and then furthest left. `None`
/// when it fits nowhere. The spans under the box at each span are a window whose two ends only
/// move right, and `window` holds the indices in it whose depth no later span in it reaches, so
/// its front is the deepest: one call takes time in proportion to the number of spans.
fn find(&self, w: f64, h: f64) -> Option<(f64, f64)> {
let mut best: Option<(f64, f64)> = None;
let mut window: VecDeque<usize> = VecDeque::new();
let mut end = 0;
for (i, s) in self.spans.iter().enumerate() {
if s.x + w > self.width + EPS {
break;
}
while window.front().is_some_and(|&j| j < i) {
window.pop_front();
}
end = end.max(i);
while let Some(t) = self.spans.get(end)
&& (end == i || t.x < s.x + w - EPS)
{
while window.back().and_then(|&j| self.spans.get(j)).is_some_and(|b| b.y <= t.y) {
window.pop_back();
}
window.push_back(end);
end += 1;
}
let y = window.front().and_then(|&j| self.spans.get(j)).map_or(0.0, |t| t.y.max(0.0));
if y + h > self.height + EPS {
continue;
}
// The box is `h` tall at every place, so the place with the highest bottom edge is the
// place with the highest top edge.
if best.is_none_or(|(bx, by)| y < by - EPS || ((y - by).abs() <= EPS && s.x < bx)) {
best = Some((s.x, y));
}
}
best
}
/// Fills the skyline down to `y + h` from `x` across `w`.
fn place(&mut self, x: f64, y: f64, w: f64, h: f64) {
if w <= 0.0 {
return;
}
let end = x + w;
let mut out = Vec::with_capacity(self.spans.len() + 2);
let mut added = false;
for s in &self.spans {
let s_end = s.x + s.w;
if s_end <= x || s.x >= end {
out.push(*s);
continue;
}
if s.x < x {
out.push(Span { x: s.x, w: x - s.x, y: s.y });
}
if !added {
out.push(Span { x, w, y: y + h });
added = true;
}
if s_end > end {
out.push(Span { x: end, w: s_end - end, y: s.y });
}
}
// Neighbors filled to the same depth are one span.
let mut merged: Vec<Span> = Vec::with_capacity(out.len());
for s in out {
match merged.last_mut() {
Some(l) if l.y == s.y => l.w = s.x + s.w - l.x,
_ => merged.push(s),
}
}
self.spans = merged;
}
}
/// One box to pack: its width and height as it stands, and when it may turn, as it is turned.
type Sizes = ((f64, f64), Option<(f64, f64)>);
/// The side a box is ordered by: its height, or its longest side when it may turn.
fn lead(b: &Sizes) -> (f64, f64) {
let ((w, h), turned) = *b;
if turned.is_some() { (w.max(h), w.min(h)) } else { (h, w) }
}
/// Packs `boxes` onto a strip `width` wide and `height` deep, the tallest first (a box that may
/// turn by its longest side; then the widest, then in their order), each where [`Skyline::find`]
/// puts it, turned when that puts its bottom edge higher (then further left), or when only the
/// turned box fits. Gives each box's top-left corner and whether it is turned, or `None` for a box
/// that does not fit.
fn pack(boxes: &[Sizes], width: f64, height: f64) -> Vec<Option<(f64, f64, bool)>> {
let mut order: Vec<usize> = (0..boxes.len()).collect();
order.sort_by(|&a, &b| {
let (la, lb) = (lead(&boxes[a]), lead(&boxes[b]));
lb.0.total_cmp(&la.0).then(lb.1.total_cmp(&la.1))
});
let mut sky = Skyline::new(width, height);
let mut at = vec![None; boxes.len()];
for i in order {
let Some(&((w, h), turned)) = boxes.get(i) else { continue };
let mut best = sky.find(w, h).map(|(x, y)| (x, y, false, w, h));
if let Some((tw, th)) = turned
&& let Some((x, y)) = sky.find(tw, th)
{
let better = best.is_none_or(|(bx, by, _, _, bh)| {
let (was, now) = (by + bh, y + th);
now < was - EPS || ((now - was).abs() <= EPS && x < bx - EPS)
});
if better {
best = Some((x, y, true, tw, th));
}
}
if let Some((x, y, t, bw, bh)) = best {
sky.place(x, y, bw, bh);
if let Some(slot) = at.get_mut(i) {
*slot = Some((x, y, t));
}
}
}
at
}
/// A quarter turn clockwise on the page about `c`.
fn quarter_turn(c: Point) -> Affine {
Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(90.0) * Affine::translate(-c.to_vec2())
}
fn finite(r: &Rect) -> bool {
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())
}
/// The box `id` is packed by: with `preview`, its visual bounds with geometry effects
/// ([`effects::preview::bounds_of`]) and the reach of its raster effects, such as shadows, glows
/// and blurs ([`vectorcraft_render::drawn_bounds`]); else its geometric bounds.
fn measure(d: &vectorcraft_doc::Document, id: NodeId, preview: bool) -> Option<Rect> {
let b = effects::preview::bounds_of(d, &[id], preview).filter(finite)?;
if !preview {
return Some(b);
}
match d.node(id).and_then(|n| vectorcraft_render::drawn_bounds(d, n)).filter(finite) {
Some(r) => Some(b.union(r)),
None => Some(b),
}
}
/// Whether `id` is a path of a pixel-aligned compound path.
fn in_aligned_compound(d: &Document, id: NodeId) -> bool {
d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned)
}
/// Whether moving `id` snaps it, or an object in it, to the pixel grid: it, an object it holds or
/// the art of a linked opacity mask in it is pixel-aligned, or it is a path of a pixel-aligned
/// compound path.
fn snaps(d: &Document, id: NodeId) -> bool {
if in_aligned_compound(d, id) {
return true;
}
let mut stack: Vec<&Node> = d.node(id).into_iter().collect();
while let Some(n) = stack.pop() {
if n.extras().pixel_aligned {
return true;
}
stack.extend(n.children().map_or(&[][..], Vec::as_slice).iter().map(|c| &**c));
if let Some(m) = n.extras().mask.as_ref()
&& m.linked
{
stack.push(&*m.art);
}
}
false
}
fn nest(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["patterns"], NEST)?;
let roll = switch_or(p, "roll", false, NEST)?;
let width = length(p, "width", 0.0, MAX_SIZE)?;
let height = length(p, "height", 0.0, MAX_SIZE)?;
let margin = length(p, "margin", 18.0, MAX_GAP)?;
let spacing = length(p, "spacing", 9.0, MAX_GAP)?;
let turn = switch_or(p, "rotate", false, NEST)?;
let preview = switch_or(p, "usePreviewBounds", true, NEST)?;
let named = match p.get("artboard") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(NEST, "`artboard` must be an artboard's index"))?),
};
// A path of a compound path selected on its own moves without the rest of the compound path.
let ids = selected_roots_to_transform(s)?;
if ids.len() > MAX_SHAPES {
return Err(bad(NEST, format!("select at most {MAX_SHAPES} objects to nest")));
}
// Objects without a finite box (an empty group, empty type) are left where they are and
// listed as `skipped`.
let mut skipped = vec![];
let (items, board): (Vec<(NodeId, Rect)>, Rect) = {
let d = &s.doc()?.doc;
let mut items: Vec<(NodeId, Rect)> = Vec::with_capacity(ids.len());
for id in &ids {
match measure(d, *id, preview) {
Some(r) => items.push((*id, r)),
None => skipped.push(id.0),
}
}
let board = match named {
Some(i) => d.artboards.get(i).ok_or_else(|| bad(NEST, format!("there is no artboard {i}")))?.rect,
None => {
let all = items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b));
let i = all.and_then(|r| d.artboard_at(r.center())).unwrap_or(0);
d.artboards.get(i).ok_or_else(|| bad(NEST, "there is no artboard for the sheet"))?.rect
}
};
(items, board)
};
if items.is_empty() {
return Err(bad(NEST, "the selection has nothing to nest"));
}
let sheet_w = if width > 0.0 { width } else { board.width() };
let sheet_h = if roll {
f64::INFINITY
} else if height > 0.0 {
height
} else {
board.height()
};
// Every box is `spacing` wider and taller, and the strip is `spacing` wider and deeper than
// the room inside the margins, so the spacing falls between boxes and not at the far edges.
let room_w = sheet_w - 2.0 * margin;
let room_h = if roll { f64::INFINITY } else { sheet_h - 2.0 * margin };
if room_w <= 0.0 || room_h <= 0.0 {
return Err(bad(NEST, "the margin leaves no room on the sheet"));
}
let all: Vec<NodeId> = items.iter().map(|(id, _)| *id).collect();
let grid: Vec<bool> = {
let d = &s.doc()?.doc;
all.iter().map(|id| snaps(d, *id)).collect()
};
let sc = Scaling { patterns: transform_patterns(s, p, &all)?, ..Scaling::default() };
// With `rotate`, each object is turned in a copy of the document and measured there, so the
// box packed for a turned object is the box its turned strokes and effects take. A path of a
// pixel-aligned compound path keeps its orientation: turning it snaps the whole compound path
// again, which would move the compound's other paths away from where they were measured.
let turned: Vec<Option<(Affine, Rect)>> = if turn {
let mut t = vectorcraft_doc::Document::clone(&s.doc()?.doc);
let xfs: Vec<Option<Affine>> = items.iter().map(|(id, r)| (!in_aligned_compound(&t, *id)).then(|| quarter_turn(r.center()))).collect();
for ((id, _), xf) in items.iter().zip(&xfs) {
if let (Some(xf), Some(n)) = (xf, t.node_mut(*id)) {
transform_node(n, *xf, sc, true);
}
}
items.iter().zip(xfs).map(|((id, _), xf)| xf.and_then(|xf| measure(&t, *id, preview).map(|r| (xf, r)))).collect()
} else {
vec![None; items.len()]
};
// An object that snaps to the pixel grid moves by whole points, so it stays on the grid and the
// snap after the move does not shift it; its box is 1 pt wider and taller to hold the rounding.
let slack = |g: bool| if g { 1.0 } else { 0.0 };
let boxes: Vec<Sizes> = items
.iter()
.zip(&turned)
.zip(&grid)
.map(|(((_, r), t), g)| {
let pad = spacing + slack(*g);
((r.width() + pad, r.height() + pad), t.map(|(_, q)| (q.width() + pad, q.height() + pad)))
})
.collect();
let at = pack(&boxes, room_w + spacing, room_h + spacing);
let origin = Vec2::new(board.x0 + margin, board.y0 + margin);
// The move that puts the top-left corner of box `b` at `to`: rounded up to whole points for an
// object on the pixel grid, so it moves at most 1 pt further right and down, into its slack.
let shift = |b: &Rect, to: Vec2, g: bool| {
let v = Vec2::new(to.x - b.x0, to.y - b.y0);
if g { Vec2::new(v.x.ceil(), v.y.ceil()) } else { v }
};
// Each move: the quarter turn first, when the object turns, then the shift.
let mut moves: Vec<(NodeId, Option<Affine>, Vec2)> = vec![];
let mut aside: Vec<(NodeId, Option<Affine>, Vec2)> = vec![];
let mut unplaced = vec![];
let mut rotated = vec![];
let mut bottom = 0.0_f64;
// Objects that do not fit go in a column to the right of the sheet, `spacing` from its edge
// and from each other, so that no object placed on the sheet covers them.
let aside_x = board.x0 + sheet_w + spacing;
let mut aside_y = board.y0;
for ((((id, r), spot), t), g) in items.iter().zip(&at).zip(&turned).zip(&grid) {
match (spot, t) {
(Some((x, y, true)), Some((xf, q))) => {
let dv = shift(q, Vec2::new(origin.x + x, origin.y + y), *g);
moves.push((*id, Some(*xf), dv));
rotated.push(id.0);
bottom = bottom.max(q.y1 + dv.y - origin.y);
}
(Some((x, y, _)), _) => {
let dv = shift(r, Vec2::new(origin.x + x, origin.y + y), *g);
moves.push((*id, None, dv));
bottom = bottom.max(r.y1 + dv.y - origin.y);
}
(None, _) => {
aside.push((*id, None, shift(r, Vec2::new(aside_x, aside_y), *g)));
aside_y += r.height() + spacing + slack(*g);
unplaced.push(id.0);
}
}
}
if moves.is_empty() {
return Err(bad(NEST, "no selected object fits on the sheet"));
}
moves.extend(aside);
let length = 2.0 * margin + bottom;
let placed = moves.len() - unplaced.len();
let result = json!({ "placed": placed, "unplaced": unplaced, "rotated": rotated, "skipped": skipped, "length": length });
if moves.iter().all(|(_, xf, dv)| xf.is_none() && dv.x.abs() <= EPS && dv.y.abs() <= EPS) {
return Ok(result);
}
s.edit("Nest Shapes", |d, _| {
for (id, xf, dv) in &moves {
// The turn is the one the object was measured with in the copy, and the shift after it
// is whole points for an object on the pixel grid.
for step in xf.iter().copied().chain([Affine::translate(*dv)]) {
if let Some(n) = d.node_mut(*id) {
transform_node(n, step, sc, true);
}
keep_compound_aligned(d, *id, sc);
}
}
Ok(())
})?;
Ok(result)
}
@@ -0,0 +1,433 @@
//! Tests for `addon.cutting.nest`: packing the selected objects onto a sheet or a roll.
use serde_json::{Value, json};
use vectorcraft_geom::Rect;
use super::{Skyline, pack};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
}
fn bounds(s: &Session, id: NodeId) -> Rect {
s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap()
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn overlap(a: Rect, b: Rect) -> bool {
a.x0 < b.x1 - 1e-9 && b.x0 < a.x1 - 1e-9 && a.y0 < b.y1 - 1e-9 && b.y0 < a.y1 - 1e-9
}
#[test]
fn boxes_pack_tallest_first_from_the_top_left() {
// 100 wide: the 60 × 50 box goes first at the left and the 40 × 30 one beside it. The 50 × 20
// one is too wide for the 40 pt beside the first box, so it goes below the first box.
let at = pack(&fixed(&[(40.0, 30.0), (60.0, 50.0), (50.0, 20.0)]), 100.0, f64::INFINITY);
assert_eq!(at, vec![Some((60.0, 0.0, false)), Some((0.0, 0.0, false)), Some((0.0, 50.0, false))]);
}
#[test]
fn a_box_that_does_not_fit_is_left_out() {
let at = pack(&fixed(&[(80.0, 80.0), (80.0, 80.0), (120.0, 10.0)]), 100.0, 100.0);
assert_eq!(at, vec![Some((0.0, 0.0, false)), None, None]);
}
/// Boxes that keep their orientation.
fn fixed(b: &[(f64, f64)]) -> Vec<super::Sizes> {
b.iter().map(|&s| (s, None)).collect()
}
/// Boxes that may turn a quarter.
fn turning(b: &[(f64, f64)]) -> Vec<super::Sizes> {
b.iter().map(|&(w, h)| ((w, h), Some((h, w)))).collect()
}
#[test]
fn a_box_turns_where_its_bottom_edge_ends_higher_or_only_turned_it_fits() {
// A 20 × 90 box lies down as 90 × 20 at the top; a 120 × 10 box only fits the 100 pt strip
// turned, as 10 × 120.
let at = pack(&turning(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY);
assert_eq!(at, vec![Some((10.0, 0.0, true)), Some((0.0, 0.0, true))]);
// Without turning, the 120 pt wide box is left out and the other stands up.
let at = pack(&fixed(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY);
assert_eq!(at, vec![Some((0.0, 0.0, false)), None]);
// A square box is never turned: turned, it is no better.
let at = pack(&turning(&[(30.0, 30.0)]), 100.0, 100.0);
assert_eq!(at, vec![Some((0.0, 0.0, false))]);
}
#[test]
fn the_skyline_fills_and_merges_spans() {
let mut sky = Skyline::new(100.0, f64::INFINITY);
sky.place(0.0, 0.0, 30.0, 10.0);
sky.place(30.0, 0.0, 30.0, 10.0);
assert_eq!(sky.spans.len(), 2, "two spans at the same depth are one: {:?}", sky.spans);
assert_eq!(sky.find(50.0, 5.0), Some((0.0, 10.0)), "50 wide does not fit in the 40 left at the top");
assert_eq!(sky.find(40.0, 5.0), Some((60.0, 0.0)));
}
#[test]
fn selected_objects_are_nested_on_the_artboard_as_one_undo_step() {
let mut s = session();
let ids: Vec<NodeId> = (0..6).map(|i| rect(&mut s, 900.0 + 300.0 * i as f64, 700.0, 150.0, 100.0 + 10.0 * i as f64)).collect();
select(&mut s, &ids);
let n = steps(&s);
let r = s.execute("addon.cutting.nest", &json!({"margin": 10, "spacing": 5, "usePreviewBounds": false})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(r["placed"], json!(6));
assert_eq!(r["unplaced"], json!([]));
let boxes: Vec<Rect> = ids.iter().map(|id| bounds(&s, *id)).collect();
for (i, a) in boxes.iter().enumerate() {
assert!(a.x0 >= 10.0 - 1e-9 && a.y0 >= 10.0 - 1e-9 && a.x1 <= 790.0 + 1e-9 && a.y1 <= 590.0 + 1e-9, "{a:?} inside the margins");
assert!((a.width(), a.height()) == (150.0, 100.0 + 10.0 * i as f64), "moved, not resized");
for b in &boxes[i + 1..] {
assert!(!overlap(a.inflate(2.5, 2.5), b.inflate(2.5, 2.5)), "{a:?} and {b:?} are 5 pt apart");
}
}
// The tallest (150 pt) is at the top-left corner inside the margin, and five 150 pt wide
// boxes with 5 pt between them fill the 780 pt inside the margins. The shortest goes 5 pt below
// the 110 pt tall box at the right, where its bottom edge is highest.
assert_eq!((boxes[5].x0, boxes[5].y0), (10.0, 10.0));
assert_eq!(boxes.iter().filter(|b| b.y0 == 10.0).count(), 5);
assert_eq!((boxes[0].x0, boxes[0].y0), (630.0, 125.0));
assert_eq!(r["length"], json!(10.0 + 115.0 + 100.0 + 10.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(bounds(&s, ids[0]), Rect::new(900.0, 700.0, 1050.0, 800.0));
}
#[test]
fn objects_that_do_not_fit_go_beside_the_sheet() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 500.0, 400.0);
let b = rect(&mut s, 1500.0, 0.0, 500.0, 400.0);
let big = rect(&mut s, 2100.0, 0.0, 900.0, 100.0);
select(&mut s, &[a, b, big]);
let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap();
assert_eq!(r["placed"], json!(1));
assert_eq!(r["unplaced"], json!([b.0, big.0]));
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 500.0, 400.0));
// A column 5 pt to the right of the 800 pt sheet, in stacking order, 5 pt apart.
assert_eq!(bounds(&s, b), Rect::new(805.0, 0.0, 1305.0, 400.0));
assert_eq!(bounds(&s, big), Rect::new(805.0, 405.0, 1705.0, 505.0));
}
#[test]
fn the_column_beside_the_sheet_is_in_stacking_order() {
let mut s = session();
let back = rect(&mut s, 900.0, 0.0, 900.0, 100.0);
let front = rect(&mut s, 900.0, 200.0, 900.0, 50.0);
let small = rect(&mut s, 900.0, 400.0, 50.0, 50.0);
// Selected front first: the column still starts with the object at the back.
select(&mut s, &[front, small, back]);
let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap();
assert_eq!(r["unplaced"], json!([back.0, front.0]));
assert_eq!(bounds(&s, back), Rect::new(805.0, 0.0, 1705.0, 100.0));
assert_eq!(bounds(&s, front), Rect::new(805.0, 105.0, 1705.0, 155.0));
}
#[test]
fn objects_without_bounds_are_skipped_and_listed() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0);
let layer = s.doc().unwrap().doc.parent_of(a);
let empty = s
.edit("empty group", |d, _| {
let g = vectorcraft_doc::Node::new(d.alloc_id(), vectorcraft_doc::NodeKind::Group { children: vec![], clip: false });
Ok(d.insert(layer, usize::MAX, g).unwrap())
})
.unwrap();
select(&mut s, &[a, empty]);
let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap();
assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["skipped"].clone()), (json!(1), json!([]), json!([empty.0])));
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 50.0, 50.0));
}
#[test]
fn the_sheet_is_the_artboard_under_the_center_of_the_selection() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap();
let a = rect(&mut s, 1100.0, 100.0, 50.0, 50.0);
let b = rect(&mut s, 1200.0, 200.0, 40.0, 40.0);
select(&mut s, &[a, b]);
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap();
assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0), "on the second artboard, not the first");
assert_eq!(bounds(&s, b), Rect::new(1050.0, 0.0, 1090.0, 40.0));
}
#[test]
fn rotate_turns_clockwise() {
let mut s = session();
// A 400 × 100 group with a 20 pt mark at its top-left corner. Turned clockwise on the page, the
// top-left corner goes to the top-right.
let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0);
let mark = rect(&mut s, 900.0, 0.0, 20.0, 20.0);
select(&mut s, &[long, mark]);
s.execute("object.group", &json!({})).unwrap();
let r = s
.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false}))
.unwrap();
assert_eq!(r["rotated"].as_array().map(Vec::len), Some(1));
assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0));
assert_eq!(bounds(&s, mark), Rect::new(80.0, 0.0, 100.0, 20.0), "the mark is at the top-right");
}
#[test]
fn a_path_of_a_pixel_aligned_compound_path_is_not_turned() {
let mut s = session();
let outer = rect(&mut s, 900.0, 100.0, 500.0, 200.0);
let hole = rect(&mut s, 950.0, 150.0, 400.0, 100.0);
select(&mut s, &[outer, hole]);
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("object.setPixelAligned", &json!({})).unwrap();
select(&mut s, &[hole]);
// The 400 pt wide path fits the 300 pt sheet only turned, and it keeps its orientation.
let r =
s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false}));
let e = r.unwrap_err().to_string();
assert!(e.contains("no selected object fits"), "{e}");
}
/// [`Skyline::find`] as a search of every span and every span under the box.
fn find_by_search(sky: &Skyline, w: f64, h: f64) -> Option<(f64, f64)> {
let mut best: Option<(f64, f64)> = None;
for (i, s) in sky.spans.iter().enumerate() {
if s.x + w > sky.width + 1e-9 {
break;
}
let y = sky.spans[i..].iter().take_while(|t| t.x == s.x || t.x < s.x + w - 1e-9).fold(0.0_f64, |m, t| m.max(t.y));
if y + h > sky.height + 1e-9 {
continue;
}
if best.is_none_or(|(bx, by)| y < by - 1e-9 || ((y - by).abs() <= 1e-9 && s.x < bx)) {
best = Some((s.x, y));
}
}
best
}
#[test]
fn find_matches_a_search_of_every_span() {
// A fixed pseudo-random sequence of boxes, each placed where `find` puts it.
let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
let mut next = |n: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % n) as f64 + 1.0
};
let mut sky = Skyline::new(200.0, 400.0);
for _ in 0..400 {
let (w, h) = (next(60), next(30));
let got = sky.find(w, h);
assert_eq!(got, find_by_search(&sky, w, h), "{w} × {h} on {:?}", sky.spans);
if let Some((x, y)) = got {
sky.place(x, y, w, h);
}
}
}
#[test]
fn an_object_that_does_not_fit_is_not_covered_by_the_others() {
let mut s = session();
// The wide object sits on the sheet and does not fit; the small one must not land on it.
let wide = rect(&mut s, 0.0, 0.0, 900.0, 100.0);
let small = rect(&mut s, 300.0, 300.0, 50.0, 50.0);
select(&mut s, &[wide, small]);
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap();
assert!(!overlap(bounds(&s, wide), bounds(&s, small)), "{:?} {:?}", bounds(&s, wide), bounds(&s, small));
}
#[test]
fn objects_on_the_pixel_grid_keep_the_margin_and_spacing() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 1100.0, 0.0, 100.0, 90.0);
select(&mut s, &[a, b]);
s.execute("object.setPixelAligned", &json!({})).unwrap();
let on_grid = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| (v * 2.0).fract() == 0.0);
assert!(on_grid(bounds(&s, a)) && on_grid(bounds(&s, b)));
s.execute("addon.cutting.nest", &json!({"margin": 0.6, "spacing": 0.6, "usePreviewBounds": false})).unwrap();
let (ba, bb) = (bounds(&s, a), bounds(&s, b));
assert!(on_grid(ba) && on_grid(bb), "still on the grid: {ba:?} {bb:?}");
assert!(ba.x0 >= 0.6 && ba.y0 >= 0.6 && bb.y0 >= 0.6, "inside the margin: {ba:?} {bb:?}");
assert!(bb.x0 >= ba.x1 + 0.6, "0.6 pt apart: {ba:?} {bb:?}");
assert!(ba.x1.max(bb.x1) <= 800.0 - 0.6, "inside the margin: {ba:?} {bb:?}");
}
#[test]
fn preview_bounds_take_in_a_drop_shadow() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0);
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [a.0], "params": {"x": 20, "y": 0, "blur": 0}})).unwrap();
select(&mut s, &[a, b]);
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap();
let (ba, bb) = (bounds(&s, a), bounds(&s, b));
let shadow = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(a).unwrap()).unwrap();
assert!(shadow.x1 >= ba.x1 + 20.0 - 1e-9, "the shadow reaches 20 pt right: {shadow:?}");
let shadow_b = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(b).unwrap()).unwrap_or(bb);
assert!(!overlap(shadow, shadow_b.union(bb)), "the shadow {shadow:?} does not reach {bb:?}");
}
#[test]
fn a_roll_has_no_end() {
let mut s = session();
let ids: Vec<NodeId> = (0..5).map(|i| rect(&mut s, 900.0, 300.0 * i as f64, 500.0, 400.0)).collect();
select(&mut s, &ids);
let r = s.execute("addon.cutting.nest", &json!({"roll": true, "margin": 0, "spacing": 10, "usePreviewBounds": false})).unwrap();
assert_eq!((r["placed"].clone(), r["unplaced"].clone()), (json!(5), json!([])));
let mut tops: Vec<f64> = ids.iter().map(|id| bounds(&s, *id).y0).collect();
tops.sort_by(f64::total_cmp);
assert_eq!(tops, vec![0.0, 410.0, 820.0, 1230.0, 1640.0], "one 500 pt wide shape per row on the 800 pt roll");
assert_eq!(r["length"], json!(2040.0));
}
#[test]
fn width_and_height_set_the_sheet_from_the_artboard_corner() {
let mut s = session();
let ids: Vec<NodeId> = (0..3).map(|i| rect(&mut s, 50.0 * i as f64, 300.0, 40.0, 40.0)).collect();
select(&mut s, &ids);
let r = s.execute("addon.cutting.nest", &json!({"width": "1 in", "height": 200, "margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap();
assert_eq!(r["placed"], json!(3));
for id in &ids {
let b = bounds(&s, *id);
assert!(b.x0 == 0.0 && b.x1 <= 72.0, "one 40 pt shape per row on a 72 pt sheet: {b:?}");
}
}
#[test]
fn preview_bounds_keep_strokes_apart() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0);
select(&mut s, &[a, b]);
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap();
let (ba, bb) = (bounds(&s, a), bounds(&s, b));
assert_eq!((ba.x0, ba.y0), (5.0, 5.0), "the stroke's outer half is inside the sheet");
assert_eq!((bb.x0 - ba.x1), 10.0, "the strokes touch and do not overlap");
}
#[test]
fn a_selection_already_nested_adds_no_undo_step() {
let mut s = session();
let a = rect(&mut s, 18.0, 18.0, 100.0, 100.0);
select(&mut s, &[a]);
let n = steps(&s);
let r = s.execute("addon.cutting.nest", &json!({"usePreviewBounds": false})).unwrap();
assert_eq!(r["placed"], json!(1));
assert_eq!(steps(&s), n, "nothing moved");
}
#[test]
fn bad_params_are_refused_and_change_nothing() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
select(&mut s, &[a]);
let n = steps(&s);
let bad: [(Value, &str); 10] = [
(json!({"rotate": 1}), "`rotate` must be true or false"),
(json!({"width": -1}), "`width` must be from 0"),
(json!({"height": 2e6}), "`height` must be from 0"),
(json!({"margin": "x"}), "`margin` must be a number"),
(json!({"spacing": 1e6}), "`spacing` must be from 0"),
(json!({"roll": "yes"}), "`roll` must be true or false"),
(json!({"usePreviewBounds": 1}), "`usePreviewBounds` must be true or false"),
(json!({"artboard": 3}), "there is no artboard 3"),
(json!({"artboard": -1}), "`artboard` must be"),
(json!({"margin": 400}), "the margin leaves no room"),
];
for (p, want) in bad {
let e = s.execute("addon.cutting.nest", &p).expect_err(&p.to_string()).to_string();
assert!(e.contains(want), "{p}: {e}");
}
let e = s.execute("addon.cutting.nest", &json!({"width": 50, "margin": 0})).unwrap_err().to_string();
assert!(e.contains("no selected object fits"), "{e}");
let e = s.execute("addon.cutting.nest", &json!({"patterns": "no"})).unwrap_err().to_string();
assert!(e.contains("`patterns` must be true or false"), "{e}");
assert_eq!(steps(&s), n, "a refused run changes nothing");
assert_eq!(bounds(&s, a), Rect::new(900.0, 0.0, 1000.0, 100.0));
}
#[test]
fn the_named_artboard_is_the_sheet() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap();
let a = rect(&mut s, 100.0, 100.0, 50.0, 50.0);
select(&mut s, &[a]);
s.execute("addon.cutting.nest", &json!({"artboard": 1, "margin": 0, "usePreviewBounds": false})).unwrap();
assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0));
}
#[test]
fn rotate_turns_objects_a_quarter_to_fit_the_sheet() {
let mut s = session();
// On a 300 × 500 sheet with no margin, a 400 × 100 object only fits standing up.
let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0);
let small = rect(&mut s, 900.0, 300.0, 50.0, 40.0);
select(&mut s, &[long, small]);
let p = json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "usePreviewBounds": false});
let r = s.execute("addon.cutting.nest", &p).unwrap();
assert_eq!((r["unplaced"].clone(), r["rotated"].clone()), (json!([long.0]), json!([])), "without rotate it does not fit");
s.execute("edit.undo", &json!({})).unwrap();
let mut p = p;
p["rotate"] = json!(true);
let n = steps(&s);
let r = s.execute("addon.cutting.nest", &p).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["rotated"].clone()), (json!(2), json!([]), json!([long.0])));
assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0), "turned and at the corner");
// The 50 × 40 object stays as it is: turned, its bottom edge would be lower.
assert_eq!(bounds(&s, small), Rect::new(100.0, 0.0, 150.0, 40.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(bounds(&s, long), Rect::new(900.0, 0.0, 1300.0, 100.0), "undo turns it back");
}
#[test]
fn rotate_measures_the_turned_preview_bounds() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 400.0, 100.0);
select(&mut s, &[a]);
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
let r = s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true})).unwrap();
assert_eq!(r["rotated"], json!([a.0]));
assert_eq!(bounds(&s, a), Rect::new(5.0, 5.0, 105.0, 405.0), "the turned stroke's outer half is inside the sheet");
}
#[test]
fn a_compound_paths_path_selected_alone_moves_alone() {
let mut s = session();
let outer = rect(&mut s, 900.0, 100.0, 40.0, 40.0);
let hole = rect(&mut s, 910.0, 110.0, 10.0, 10.0);
select(&mut s, &[outer, hole]);
s.execute("object.compoundPath.make", &json!({})).unwrap();
select(&mut s, &[hole]);
s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap();
assert_eq!(bounds(&s, hole), Rect::new(0.0, 0.0, 10.0, 10.0), "the path moved");
assert_eq!(bounds(&s, outer), Rect::new(900.0, 100.0, 940.0, 140.0), "the rest of the compound path stayed");
}
#[test]
fn a_group_is_nested_as_one_object() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0);
let b = rect(&mut s, 1000.0, 100.0, 50.0, 50.0);
select(&mut s, &[a, b]);
s.execute("object.group", &json!({})).unwrap();
s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap();
assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(0.0, 0.0, 50.0, 50.0), Rect::new(100.0, 100.0, 150.0, 150.0)));
}
+6 -4
View File
@@ -498,8 +498,9 @@ pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec<NodeId> {
}
/// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it.
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. The graph stops keeping the
/// groups' opacity, blend mode, isolation and knockout. Returns whether what a graph keeps changed.
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) -> bool {
for id in groups {
if let Some(n) = d.node_mut(*id) {
clear(n);
@@ -507,6 +508,7 @@ pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
n.extras_mut().graphic_style = None;
}
}
super::graph::capture_series_object_opacity(d, groups)
}
/// [`whole_targets`] of `cmd`, which needs at least one.
@@ -943,7 +945,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
(src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
super::object::snap_if_aligned(to);
}
clear_stood_for(d, &group);
let forgot = clear_stood_for(d, &group);
for id in &cleared {
if let Some(n) = d.node_mut(*id) {
clear(n);
@@ -961,7 +963,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
// The targets last: on two labels of one kind, the target's rows are the ones the kind keeps.
let labels = super::graph::capture_label_rows(d, &changed);
let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect();
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels))
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot))
})?;
s.active_appearance_item = None;
Ok(json!({ "source": source.0, "target": target.0 }))
+5 -11
View File
@@ -6,8 +6,8 @@ use vectorcraft_doc::Scaling;
use vectorcraft_geom::{Rect, Vec2};
use super::object::choice;
use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or};
use super::panelcmds::{artboard_at, artboards_art, locked_and_hidden, named_or_selected, note_artboards, on_board};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, index, switch_or};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
@@ -63,13 +63,7 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> {
check_switches(p, &["patterns"], cmd)?;
let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard");
let indices = named_or_selected(s, p, cmd)?;
let given = |key: &str| -> Result<Option<usize>> {
match p.get(key).filter(|v| !v.is_null()) {
Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some),
None => Ok(None),
}
};
let (named, recorded) = (given("artboard")?, given("activeArtboard")?);
let (named, recorded) = (artboard_at(&s.doc()?.doc, p, "artboard", cmd)?, artboard_at(&s.doc()?.doc, p, "activeArtboard", cmd)?);
let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?;
let locked_art = locked_and_hidden(s, p, move_art, cmd)?;
note_artboards(s, p, &indices);
@@ -78,8 +72,8 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> {
(false, _) => None,
(true, Some(i)) => Some(i),
(true, None) => {
let active = s.tool_options_of("artboard")["active"].clone();
Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?)
let active = s.tool_options_of("artboard")["active"].as_u64().map(index);
Some(active.map_or_else(|| Err(EngineError::Other("no such artboard".into())), |i| on_board(&s.doc()?.doc, i))?)
}
};
if let Some(i) = reference.filter(|_| named.is_none()) {
+20 -4
View File
@@ -89,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Asset Export Settings",
[],
None,
"{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step",
"{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?: true|false (Create Sub-folders: true sorts the files into a folder per row; false puts assets.export's files in the folder itself and, given without exportPreset, sets a remembered folder per format or item to none as well), antiAlias?, openLocation?: true|false (Open Location after Export: remembered in document.exportSettings, not in presets or the reply; given alone to a document without settings, Create Sub-folders stays on)} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step",
has_doc,
settings_set
),
@@ -435,19 +435,35 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
fn settings_set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "assets.settings.set";
let o = p.as_object().ok_or_else(|| bad(C, "give the settings to change, e.g. {\"formats\": [{\"format\": \"png\", \"scale\": \"2x\"}]}"))?;
if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && k.as_str() != "exportPreset") {
return Err(bad(C, format!("`{k}` isn't an export setting: {}", SCREEN_SETTINGS_KEYS.join(", "))));
if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && !matches!(k.as_str(), "exportPreset" | "openLocation")) {
return Err(bad(C, format!("`{k}` isn't an export setting: {}, openLocation", SCREEN_SETTINGS_KEYS.join(", "))));
}
for k in ["subfolders", "openLocation"] {
if o.get(k).is_some_and(|v| !v.is_boolean() && !v.is_null()) {
return Err(bad(C, format!("`{k}` is true or false")));
}
}
let mut settings = s.doc()?.doc.export_settings.clone();
let mut given = o.clone();
// Create Sub-folders is on for a document without settings (Export for Screens opens so), and
// Open Location after Export set on its own leaves it on.
if settings.is_empty() && o.len() == 1 && o.get("openLocation").is_some_and(Value::is_boolean) {
given.insert("subfolders".into(), json!(true));
}
if let Some(name) = given.remove("exportPreset") {
let name = name.as_str().ok_or_else(|| bad(C, "`exportPreset` is the name of a preset of document.exportPresets.list"))?;
with_screen_export_preset(s, C, &mut settings, name)?;
}
// Create Sub-folders is Export for Screens' folder per row: the dialog opens on the choice.
// Turned off on its own (the panel menu), it also ends a remembered folder per format or item;
// with an export preset, that preset's folder per format or item stays.
let folders = settings.get("folders").and_then(Value::as_str).map(str::to_string);
let sorted = folders.as_deref().is_some_and(|f| f != "none");
match given.get("subfolders").and_then(Value::as_bool) {
Some(true) => _ = settings.insert("folders".into(), json!("rows")),
Some(false) if settings.get("folders").and_then(Value::as_str) == Some("rows") => _ = settings.insert("folders".into(), json!("none")),
Some(false) if folders.as_deref() == Some("rows") || (sorted && !o.contains_key("exportPreset")) => {
_ = settings.insert("folders".into(), json!("none"))
}
_ => {}
}
overlay(&mut settings, &given);
+2 -2
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Shape Builder",
[],
None,
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one",
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it, where filled means any fill row is shown, painted and above 0% opacity, whichever row is on top; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one",
has_selection_or_ids,
sb_merge
),
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Info",
[],
None,
"{group, id?: object id (default: the selection)} → {faces: [{id, fill, bounds}], edges: [{id, stroke, width}], sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}",
"{group?|id?: Live Paint group id (one required; id is read when group is left out)} → {faces: [{id, fill (top fill), bounds, appearance: [row…]}], edges: [{id, stroke (top stroke), width (top stroke's), appearance: [row…]}], where a row is {index (in the part's fill and stroke stack, bottom first), kind: \"fill\"|\"stroke\", paint, opacity: 0..1, visible, width?: pt (strokes only), drawn (the part is shown with opacity above 0, and the row is shown, has paint and opacity above 0, a stroke also width above 0)}, sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}",
has_doc,
lp_info
),
+49 -5
View File
@@ -1,7 +1,8 @@
use super::{
Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, PathData, Point, Rect,
Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint, json,
number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or,
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json,
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
switch_or,
};
/// `options` as stored on a Live Paint group: none for the defaults.
@@ -524,6 +525,37 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "group": g.0, "edge": edge.0 }))
}
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
/// row is `drawn` when the part is shown with an opacity above 0 and the row is shown, has paint
/// and has an opacity above 0 (a stroke also a weight above 0): the rule of [`draws`], row by row.
fn appearance_rows(n: &Node) -> Vec<Value> {
let part_shown = n.visible && n.opacity > 0.0;
n.appearance
.items
.iter()
.enumerate()
.map(|(i, item)| {
let shown = part_shown && item.visible() && !item.paint().is_none() && item.opacity() > 0.0;
let mut row = json!({
"index": i,
"kind": item.kind_name(),
"paint": item.paint().label(),
"opacity": item.opacity(),
"visible": item.visible(),
});
let drawn = match item {
AppearanceItem::Fill(_) => shown,
AppearanceItem::Stroke(st) => {
row["width"] = json!(st.width);
shown && st.width > 0.0
}
};
row["drawn"] = json!(drawn);
row
})
.collect()
}
pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
let g = match object_param(p, "group", "livePaint.info")? {
Some(g) => g,
@@ -535,12 +567,24 @@ pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
.iter()
.map(|f| {
let bb = f.geometric_bounds().unwrap_or(Rect::ZERO);
json!({ "id": f.id.0, "fill": f.appearance.fill_paint().label(), "bounds": [bb.x0, bb.y0, bb.x1, bb.y1] })
json!({
"id": f.id.0,
"fill": f.appearance.fill_paint().label(),
"bounds": [bb.x0, bb.y0, bb.x1, bb.y1],
"appearance": appearance_rows(f),
})
})
.collect();
let edges: Vec<Value> = b::edges(n)
.iter()
.map(|e| json!({ "id": e.id.0, "stroke": e.appearance.stroke_paint().label(), "width": e.appearance.stroke_width() }))
.map(|e| {
json!({
"id": e.id.0,
"stroke": e.appearance.stroke_paint().label(),
"width": e.appearance.stroke_width(),
"appearance": appearance_rows(e),
})
})
.collect();
let sources = b::sources(n).and_then(|g| g.children()).map(|c| c.len()).unwrap_or(0);
let options = n.gap_options();
@@ -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
+9 -2
View File
@@ -686,8 +686,15 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color
}
}
let styles = &mut g.label_styles;
for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() {
map_paint_colors(&mut st.fill, f);
// A legend fill of the labels' own stays theirs when `f` makes it black. The default black legend fill stays black,
// so the labels on dark pie wedges are still drawn white.
styles.mark_own_legend_fill();
let own = styles.legend_fill_is_own();
for (st, fill) in [(&mut styles.values, true), (&mut styles.categories, true), (&mut styles.legend, own)] {
let Some(st) = st else { continue };
if fill {
map_paint_colors(&mut st.fill, f);
}
map_paint_colors(&mut st.stroke, f);
}
for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows].into_iter().flatten() {
+14 -5
View File
@@ -671,10 +671,11 @@ fn a_document_replaced_in_the_back_is_measured_before_it_comes_to_the_front() {
}
/// Type a document replaced in the back sets in a composite font that only the front document
/// defines is measured in that font while the front one is registered, and again, as missing, when
/// the replaced document comes to the front.
/// defines is measured as missing, though the front one is registered, also when the replaced
/// document defines no composite font, and still as missing when it comes to the front.
#[test]
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing() {
let db = vectorcraft_text::FontDb::global();
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Lacked"})).unwrap()["id"].as_u64().unwrap();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
@@ -682,8 +683,16 @@ fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Lacked")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
let back = text_in(&s, 0, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &back).bounds;
assert_eq!(back.cached_bounds, Some(expected));
assert!(s.documents()[0].doc.composite_fonts.is_empty());
let in_front = vectorcraft_text::layout(db, &back).bounds;
// The same type set in a family nothing defines.
let mut nowhere = back.clone();
for r in &mut nowhere.runs {
r.style.font_family = "No Such Family CF Lacked".into();
}
let missing = vectorcraft_text::layout(db, &nowhere).bounds;
assert!((in_front.width() - missing.width()).abs() > 1e-6, "the front document's font draws otherwise");
assert_eq!(back.cached_bounds, Some(missing));
assert!(s.set_active(0));
assert!(vectorcraft_text::FontDb::global().composite_font("CF Lacked").is_none());
let actual = text(&s, id);
@@ -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() }))
}
+1 -1
View File
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Smooth",
[],
None,
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag → {ids, before, after}",
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}",
has_selection,
smooth_region
),
+388 -9
View File
@@ -13,9 +13,237 @@ use super::{
/// of path within the reach on either side of it. VectorCraft's own value.
const SMOOTH_SPREAD: f64 = 1.0 / 3.0;
/// The degrees by which a path must turn at an anchor, and over the tool's reach and twice its reach
/// on either side of it, for the Smooth tool to keep the anchor as a corner ([`smooth_corners`]): a
/// turn of more than 57.5°, an angle inside the corner of less than 122.5°. VectorCraft's own value,
/// the same on every drag and at any Fidelity.
const SMOOTH_CORNER_DEG: f64 = 57.5;
/// Most pieces a curved segment is cut into evenly, and most more pieces near each of its ends, to
/// measure lengths along it in [`smooth_corners`].
const CORNER_PIECES: usize = 64;
/// The control polygon's length of `c`, which is at least its length.
fn polygon_len(c: CubicBez) -> f64 {
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
}
/// The places (0 to 1, in order, without 0 and with 1) on the curved segment `c` that
/// [`smooth_corners`] measures it at: up to [`CORNER_PIECES`] evenly spaced, and near each end, over
/// a stretch at least three times `reach` long where the segment is that long, up to as many more
/// that are no more than `reach` / 8 apart along the control polygon, and as many again in each
/// stretch twice as long after it until the pieces reach three times `reach`. The turns over `reach` and
/// twice `reach` from an anchor are then measured along the curve however long the segment is.
fn corner_places(c: CubicBez, reach: f64) -> Vec<f64> {
let piece = reach / 8.0;
let pieces = |len: f64| if piece > 0.0 { (len / piece).ceil().clamp(1.0, CORNER_PIECES as f64) as usize } else { 1 };
let k = pieces(polygon_len(c)).max(4);
let mut places: Vec<f64> = (1..=k).map(|j| j as f64 / k as f64).collect();
if piece > 0.0 {
for from_start in [true, false] {
// The stretch from the end: halved until its control polygon is at most six reaches long.
let first = 1.0 / k as f64;
let mut t = first;
let part = |t: f64| if from_start { c.subsegment(0.0..t) } else { c.subsegment(1.0 - t..1.0) };
for _ in 0..60 {
if polygon_len(part(t)) <= 6.0 * reach {
break;
}
t /= 2.0;
}
let side = |u: f64| if from_start { u } else { 1.0 - u };
let m = pieces(polygon_len(part(t)));
let mut fine: Vec<f64> = (1..=m).map(|j| t * j as f64 / m as f64).collect();
// Then the stretches twice as long in turn, cut as finely, up to the first even place, until
// the pieces reach three reaches from the end, so twice the reach is measured along the curve
// where a handle that does not reach out makes the curve start more slowly than its polygon.
let mut covered = 0.0;
let mut at = c.eval(side(0.0));
for u in &fine {
let q = c.eval(side(*u));
covered += at.distance(q);
at = q;
}
let (mut from, mut levels) = (t, 0);
while covered < 3.0 * reach && from < first && levels < 60 {
let to = (2.0 * from).min(first);
let piece_len = polygon_len(if from_start { c.subsegment(from..to) } else { c.subsegment(1.0 - to..1.0 - from) });
let m = pieces(piece_len);
for j in 1..=m {
let u = from + (to - from) * j as f64 / m as f64;
let q = c.eval(side(u));
covered += at.distance(q);
at = q;
fine.push(u);
}
(from, levels) = (to, levels + 1);
}
places.extend(fine.into_iter().map(side));
}
}
places.retain(|u| *u > 0.0 && *u <= 1.0);
places.sort_by(f64::total_cmp);
places.dedup();
places
}
/// The degrees between the directions `u` and `v`, `None` when either has no length or is not a
/// number.
fn turn_between(u: kurbo::Vec2, v: kurbo::Vec2) -> Option<f64> {
let (lu, lv) = (u.hypot(), v.hypot());
if !(lu.is_finite() && lv.is_finite() && lu > 1e-12 && lv > 1e-12) {
return None;
}
let deg = u.cross(v).atan2(u.dot(v)).abs().to_degrees();
deg.is_finite().then_some(deg)
}
/// Which anchors of `anchors` (a closed path when `closed`) the Smooth tool keeps as corners: those
/// where the path turns by more than [`SMOOTH_CORNER_DEG`] at the anchor itself, between the
/// direction it arrives along and the one it leaves along, and also over `reach` and over twice
/// `reach` on either side of it, between the direction from the point that far back along the path
/// to the anchor and the direction from the anchor to the point that far ahead. The points are taken
/// no farther than the ends of an open path, and no more than an eighth of the way round a closed
/// one. A jag or a bump smaller than the reach turns sharply at its anchor but not over twice the
/// reach, and an anchor in the middle of a tight curve turns over the reach but not at the anchor, so
/// neither is kept. An open path's first and last anchors are never corners.
fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
let n = anchors.len();
let mut corners = vec![false; n];
if n < 2 || (n < 3 && !closed) {
return corners;
}
// The distances on either side the turn is measured over: one reach and two, no more than an
// eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a
// loop shorter than the reach is not all corners, while a square's or a triangle's corners still are.
let mut spans = [reach, 2.0 * reach];
if closed {
let mut total = 0.0;
for i in 0..n {
total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1;
}
if !(total.is_finite() && total > 0.0) {
return corners;
}
spans = spans.map(|r| r.min(total / 8.0));
}
for (i, flag) in corners.iter_mut().enumerate() {
if !closed && (i == 0 || i == n - 1) {
continue;
}
let (prev, a, next) = (anchors[(i + n - 1) % n], anchors[i], anchors[(i + 1) % n]);
let arrive = [a.p - a.h_in, a.p - prev.h_out, a.p - prev.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
let leave = [a.h_out - a.p, next.h_in - a.p, next.p - a.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) {
continue;
}
let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue };
let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue };
*flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])]
.into_iter()
.all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG));
}
corners
}
/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each
/// anchor on a path of very many very short segments.
const MAX_CORNER_WALK: usize = 256;
/// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise,
/// past no more than `segments` segments, measured along the lines between each curved segment's
/// points at [`corner_places`]. It gives the points at the distances `to` (in order, the nearer
/// first), an open path's end for one beyond the end, and `None` for one it did not reach within
/// `segments` segments, and the length it walked. Both points are `None` when it meets a length that
/// is not a number or is too large to add, and the length is then infinite.
fn walk(anchors: &[Anchor], closed: bool, from: (usize, bool), to: [f64; 2], reach: f64, segments: usize) -> ([Option<Point>; 2], f64) {
let (n, forward) = (anchors.len(), from.1);
let Some(mut here) = anchors.get(from.0).map(|a| a.p) else { return ([None; 2], 0.0) };
let (mut at, mut gone) = (from.0, 0.0);
let mut found: [Option<Point>; 2] = [None; 2];
let mut at_end = false;
'segments: for _ in 0..segments {
let next = match (forward, closed) {
(true, _) if at + 1 < n => at + 1,
(true, true) => 0,
(false, _) if at > 0 => at - 1,
(false, true) => n - 1,
_ => {
at_end = true;
break;
}
};
let (a, b) = (anchors[at], anchors[next]);
let c = if forward { CubicBez::new(a.p, a.h_out, b.h_in, b.p) } else { CubicBez::new(a.p, a.h_in, b.h_out, b.p) };
let places = if c.p1 == c.p0 && c.p2 == c.p3 { vec![1.0] } else { corner_places(c, reach) };
for u in places {
let q = if u >= 1.0 { c.p3 } else { c.eval(u) };
let d = here.distance(q);
if !(d.is_finite() && (gone + d).is_finite()) {
return ([None; 2], f64::INFINITY);
}
for (slot, &dist) in found.iter_mut().zip(&to) {
if slot.is_none() && gone + d >= dist {
let t = if d > 0.0 { ((dist - gone) / d).clamp(0.0, 1.0) } else { 1.0 };
*slot = Some(here.lerp(q, t));
}
}
gone += d;
here = q;
if found.iter().all(Option::is_some) {
break 'segments;
}
}
at = next;
}
// An open path that ends after the last segment walked ends there too.
if !closed && at == if forward { n - 1 } else { 0 } {
at_end = true;
}
(found.map(|p| p.or(at_end.then_some(here))), gone)
}
/// Whether `a` and `b` are the same anchors, to within a rounding error.
fn same_anchors(a: &[Anchor], b: &[Anchor]) -> bool {
let near = |p: Point, q: Point| p.distance(q) <= 1e-9;
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out))
}
/// [`refit_run`] of the open run `anchors` cut at its anchors marked in `corners`: each part between
/// two corners is smoothed and refitted on its own, so each corner keeps its place and the direction
/// the path arrives and leaves along. `free` applies to the run's first and last anchors only.
fn refit_split(anchors: &[Anchor], corners: &[bool], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<Anchor> {
let last = anchors.len().saturating_sub(1);
let mut cuts: Vec<usize> = (1..last).filter(|&i| corners.get(i).copied().unwrap_or(false)).collect();
if cuts.is_empty() {
return refit_run(anchors, tol, sigma, free);
}
cuts.insert(0, 0);
cuts.push(last);
let mut out: Vec<Anchor> = Vec::with_capacity(anchors.len());
for w in cuts.windows(2) {
let (a, b) = (w[0], w[1]);
let part = refit_run(&anchors[a..=b], tol, sigma, [free[0] && a == 0, free[1] && b == last]);
match out.pop() {
// The corner ends one part and starts the next: it keeps its place, and takes the handle
// in from the part before and the handle out from the part after.
Some(end) => {
let mut rest = part.into_iter();
if let Some(start) = rest.next() {
out.push(Anchor::with_handles(anchors[a].p, end.h_in, start.h_out));
}
out.extend(rest);
}
None => out.extend(part),
}
}
out
}
/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of
/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the
/// smoothing moved it, keeping a corner only where the path turns back on itself. `free` says whether
/// smoothing moved it. The tool cuts the path at its corners first ([`smooth_corners`]), so within a
/// part the refit keeps a corner only where the path turns back on itself. `free` says whether
/// the start and the end of the stretch refitted are ends of an open path, whose direction then
/// follows the smoothed path within the reach rather than the first or last segment.
fn refit_options(tol: f64, sigma: f64, free: [bool; 2]) -> SimplifyOptions {
@@ -321,9 +549,31 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
if sp.closed {
let start = sp.anchors[0].p;
let Some(k) = marked.iter().position(|m| !m) else {
// Everything is in range: smooth the whole closed path, across its start too.
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2]));
return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp));
let corners = smooth_corners(&sp.anchors, true, radius);
let Some(c) = corners.iter().position(|c| *c) else {
// Everything is in range and nothing is a corner: smooth the whole closed path,
// across its start too.
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2]));
return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp));
};
// Cut the path open at a corner, which then ends the last part as well as starting the first.
let mut open = sp.anchors.clone();
open.rotate_left(c);
let mut cut = corners;
cut.rotate_left(c);
open.push(open[0]);
cut.push(true);
let mut res = refit_split(&open, &cut, tol, sigma, [false; 2]);
if same_anchors(&res, &open) {
return None;
}
let l = res.pop()?;
if let Some(r0) = res.first_mut() {
*r0 = Anchor::with_handles(r0.p, l.h_in, r0.h_out);
}
// The path starts where it did when the refit keeps an anchor there, and otherwise at its
// point nearest there.
return Some(start_nearest(SubPath::new(res, true), start, sp));
};
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
let mut open = sp.clone();
@@ -333,7 +583,10 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
open.anchors.push(open.anchors[0]);
m.push(false);
open.closed = false;
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, false);
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, radius, false);
if same_anchors(&res, &open.anchors) {
return None;
}
let l = res.pop()?;
if let Some(r0) = res.first_mut() {
r0.h_in = l.h_in;
@@ -342,7 +595,8 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
let res = SubPath::new(res, true);
return Some(if k == 0 { res } else { start_nearest(res, start, sp) });
}
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma, true), false))
let res = smooth_open(&sp.anchors, &marked, near, tol, sigma, radius, true);
(!same_anchors(&res, &sp.anchors)).then(|| SubPath::new(res, false))
}
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
@@ -376,8 +630,10 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next
/// to it stays as it was (#1512). With `open`, `anchors` are an open path, and the curve at its first
/// or last anchor turns with the smoothing when a run's refit reaches that anchor; a run's other ends,
/// and those of the open run a closed path is cut into, keep their direction.
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, open: bool) -> Vec<Anchor> {
/// and those of the open run a closed path is cut into, keep their direction. Each run keeps its
/// corners ([`smooth_corners`] within `radius`, the tool's reach, measured within the run), and a run
/// whose refit changes nothing stays as it was.
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, radius: f64, open: bool) -> Vec<Anchor> {
let n = anchors.len();
let mut runs = vec![];
let mut i = 0;
@@ -418,7 +674,11 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
*outer = Anchor::with_handles(far.p3, far.p2, reach.p1);
}
let free = [open && lo == 0 && head.is_none(), open && hi == n - 1 && tail.is_none()];
let new = refit_run(&piece, tol, sigma, free);
let corners = smooth_corners(&piece, false, radius);
let new = refit_split(&piece, &corners, tol, sigma, free);
if same_anchors(&new, &piece) {
continue;
}
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
}
out
@@ -816,4 +1076,123 @@ mod tests {
assert_eq!(drag_stretches(&one), vec![0]);
assert!((dist_to_stretches(&one, &[0], Point::new(13.0, 14.0)) - 5.0).abs() < 1e-12);
}
fn polyline(pts: &[(f64, f64)]) -> Vec<Anchor> {
pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect()
}
/// Anchors on one point, anchors that are not numbers or are too far out to measure, and a
/// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors
/// are its corners, and an open path's ends never are.
#[test]
fn corners_are_found_only_where_the_path_turns_at_and_around_an_anchor() {
assert_eq!(smooth_corners(&polyline(&[(5.0, 5.0); 4]), false, 12.0), vec![false; 4]);
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (f64::NAN, 1.0), (10.0, 0.0)]), false, 12.0), vec![false; 3]);
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (1e308, 0.0), (1e308, 1e308), (-1e308, 0.0)]), true, 12.0), vec![false; 4]);
let zigzag: Vec<(f64, f64)> = (0..=100_000).map(|i| (f64::from(i), f64::from(i % 2))).collect();
assert!(!smooth_corners(&polyline(&zigzag), false, 12.0).contains(&true));
let square = polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
assert_eq!(smooth_corners(&square, true, 12.0), vec![true; 4]);
assert_eq!(smooth_corners(&square, false, 12.0), vec![false, true, true, false]);
assert_eq!(smooth_corners(&square, false, 0.0), vec![false, true, true, false], "with no reach the turn at the anchor decides");
assert_eq!(smooth_corners(&square[..2], false, 12.0), vec![false; 2]);
}
/// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach
/// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments
/// than it measures before it gets that far, its top is not one, as the path turns by about 51°
/// over that reach.
#[test]
fn a_corner_is_not_kept_where_the_reach_is_not_measured() {
let side = 400.0 * std::f64::consts::SQRT_2;
let steps = side.ceil() as usize;
let mut pts = vec![(-3000.0, 0.0)];
pts.extend((0..steps).map(|j| {
let f = j as f64 / steps as f64;
(-400.0 + 400.0 * f, 400.0 * f)
}));
pts.extend((0..=steps).map(|j| {
let f = j as f64 / steps as f64;
(400.0 * f, 400.0 - 400.0 * f)
}));
pts.push((3000.0, 0.0));
let anchors = polyline(&pts);
let top = steps + 1;
assert_eq!(anchors[top].p, Point::new(0.0, 400.0));
assert!(smooth_corners(&anchors, false, 10.0)[top]);
assert!(!smooth_corners(&anchors, false, 1000.0)[top]);
}
/// A 60° corner between two curved segments 1,000 pt long is found at a reach of 2 pt as it is
/// when each segment is cut into a thousand pieces: the turns over the reach are measured along the
/// curve near the anchor, not along a chord much longer than the reach.
#[test]
fn a_corner_between_long_curves_is_measured_along_them() {
// The curves arrive along x and leave at 60° to it, each bending away from the other.
let d = kurbo::Vec2::from_angle(-60f64.to_radians());
let side = kurbo::Vec2::new(-d.y, d.x) * 1000.0;
let v = Point::new(0.0, 0.0);
let a = Anchor::with_handles(Point::new(-1000.0, 1000.0), Point::new(-1000.0, 1000.0), Point::new(-300.0, 1000.0));
let b = Anchor::with_handles(v, Point::new(-300.0, 0.0), v + d * 300.0);
let end = v + d * 1000.0 + side;
let c = Anchor::with_handles(end, v + d * 300.0 + side, end);
let long = [a, b, c];
let fine: Vec<Anchor> = {
let sp = SubPath::new(long.to_vec(), false);
let mut pts = vec![];
for i in 0..2 {
let s = sp.segment(i);
for j in 0..1000 {
let p = s.subsegment(f64::from(j) / 1000.0..f64::from(j + 1) / 1000.0);
if j == 0 && i == 0 {
pts.push(Anchor::with_handles(p.p0, p.p0, p.p1));
} else if let Some(last) = pts.last_mut() {
*last = Anchor::with_handles(last.p, last.h_in, p.p1);
}
pts.push(Anchor::with_handles(p.p3, p.p2, p.p3));
}
}
pts
};
let at_v = |anchors: &[Anchor]| {
let corners = smooth_corners(anchors, false, 2.0);
anchors.iter().zip(corners).find(|(x, _)| x.p == v).map(|(_, c)| c)
};
assert_eq!(at_v(&fine), Some(true), "cut finely, the anchor is a corner");
assert_eq!(at_v(&long), Some(true));
}
/// A line that meets a curve leaving with no handle, turning by 58° at the anchor and by about
/// 57.53° over twice a reach of 0.02 pt: the anchor is a corner, measured either way along the path,
/// as the stretch measured finely near the anchor covers twice the reach along the curve.
#[test]
fn a_corner_next_to_a_curve_without_a_handle_is_kept() {
let at = 58f64.to_radians();
let prev = Anchor::corner(Point::new(-100.0 * at.cos(), -100.0 * at.sin()));
let v = Point::new(0.0, 0.0);
let a = Anchor::with_handles(v, v, v);
let end = Point::new(600.0, 600.0);
let next = Anchor::with_handles(end, Point::new(200.0, 0.0), end);
assert_eq!(smooth_corners(&[prev, a, next], false, 0.02), vec![false, true, false]);
let back = |x: Anchor| Anchor::with_handles(x.p, x.h_out, x.h_in);
assert_eq!(smooth_corners(&[back(next), back(a), back(prev)], false, 0.02), vec![false, true, false]);
}
/// A jagged closed path whose length is less than twice the reach: its jags are not corners,
/// while a triangle that small keeps its three.
#[test]
fn a_small_jagged_loop_has_no_corners() {
let ring: Vec<(f64, f64)> = (0..16)
.map(|i| {
let (a, r) = (f64::from(i) / 16.0 * std::f64::consts::TAU, if i % 2 == 0 { 3.0 } else { 2.0 });
(r * a.cos(), r * a.sin())
})
.collect();
let jags = polyline(&ring);
let sp = SubPath::new(jags.clone(), true);
assert!(subpath_len(&sp) < 24.0);
assert!(smooth_corners(&jags, true, 1e-6).iter().all(|c| *c), "each jag turns sharply at its anchor");
assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]);
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]);
}
}
+23 -18
View File
@@ -808,11 +808,11 @@ fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
let created = date_param(p, "created", C)?;
let st = s.doc()?;
// The row as the panel lists it now: keeping an edit in progress below changes the rows.
let chosen = match p.get("index") {
None | Some(Value::Null) => None,
Some(v) => {
let state = v.as_u64().and_then(|row| st.history.state(&st.doc, index(row)));
Some(state.ok_or_else(|| bad(C, format!("no history state {v}")))?.clone())
let chosen = match super::index_opt(p, "index", C)? {
None => None,
Some(row) => {
let v = &p["index"];
Some(st.history.state(&st.doc, row).ok_or_else(|| bad(C, format!("no history state {v}")))?.clone())
}
};
settle_interaction(s)?;
@@ -1276,23 +1276,28 @@ pub(crate) fn place_clip(s: &mut Session, clip: &Clipboard, center: vectorcraft_
/// The artboards Paste in Place, in Front or in Back puts a copy on, in artboard order: `artboard`
/// (the active one, #693), else `artboards`, else, while the Artboard tool is chosen with several
/// artboards selected, those (noted in the journal as `artboards`, so a replay pastes on the same
/// ones); `None` when none is named. A named index that is not an artboard of the document, a
/// repeated one or an empty list is an error.
/// ones); `None` when none is named. A named value that is not a whole number (null included), a
/// named index that is not an artboard of the document, a repeated one or an empty list is an
/// error; every value is checked for its form before any is checked against the artboards.
fn paste_targets(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Vec<usize>>> {
let n = s.doc()?.doc.artboards.len();
let one = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
let single = match p.get("artboard") {
Some(v) => Some(one(v).ok_or_else(|| bad(cmd, "`artboard` must be the index of an artboard of the document"))?),
None => None,
};
let listed = match p.get("artboards") {
let single = p.get("artboard").map(|v| v.as_u64().map(index).ok_or_else(|| bad(cmd, "`artboard` must be a whole number"))).transpose()?;
let entries = match p.get("artboards") {
Some(v) => {
let list = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`artboards` must be a list of artboard indices"))?;
let mut all = list
.iter()
.map(one)
.collect::<Option<Vec<usize>>>()
.ok_or_else(|| bad(cmd, "`artboards` names an artboard the document does not have"))?;
let all = list.iter().map(|i| i.as_u64().map(index)).collect::<Option<Vec<usize>>>();
Some(all.ok_or_else(|| bad(cmd, "`artboards` must contain whole numbers"))?)
}
None => None,
};
if single.is_some_and(|i| i >= n) {
return Err(bad(cmd, "`artboard` must be the index of an artboard of the document"));
}
let listed = match entries {
Some(mut all) => {
if all.iter().any(|i| *i >= n) {
return Err(bad(cmd, "`artboards` names an artboard the document does not have"));
}
all.sort_unstable();
if all.windows(2).any(|w| w[0] == w[1]) {
return Err(bad(cmd, "`artboards` names an artboard twice"));
+10 -8
View File
@@ -265,25 +265,27 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline
/// graphics and color glyphs become other art. Leaves the document as it is and stops at the
/// first such path.
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one
/// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves
/// the document as it is and stops at the first such path.
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
return false;
}
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let first = t.first_style();
let expands = |run: usize, outline: &BezPath| {
let style = t.runs.get(run).map(|r| &r.style);
if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) {
let style = t.runs.get(run).map_or(&first, |r| &r.style);
if !matches!(style.fill, Paint::Gradient(_)) {
return false;
}
let path = PathData::from_bezpath(outline).transformed(t.xf);
let path = PathData::from_bezpath(outline);
if path.is_empty() {
return false;
}
let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance());
gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance))
let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default());
vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
gradient_expands(d, &piece)
};
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
+4 -1
View File
@@ -66,7 +66,10 @@ use serde_json::{Value, json};
pub use action_batch::batch_overwrites_one_file;
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts};
pub use encode::{
ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, export_art_bounds,
note_texts,
};
pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
File diff suppressed because one or more lines are too long
+305 -5
View File
@@ -2,11 +2,13 @@
//! (unknown keys are ignored, so one params object can carry the options of several formats).
use std::borrow::Cow;
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};
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride};
use vectorcraft_geom::Rect;
use vectorcraft_render::AntiAlias;
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
@@ -419,13 +421,15 @@ pub(super) fn use_artboards(cmd: &str, p: &Value) -> Result<Option<bool>> {
/// With `useArtboards: false` in `p`: `doc` without its opacity-mask or symbol editing layer and
/// with one artboard, the bounds of its visible art, and `p` without the artboard choice. `None`
/// when `useArtboards` is absent, null or true. A document with no visible art is refused.
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Document, Value)>> {
/// when `useArtboards` is absent, null or true. The objects that `left_out` picks (layers or
/// objects the format leaves out, see [`hidden_nodes`]) are not measured, and a document with no
/// other visible art is refused.
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value, left_out: impl Fn(&Node) -> bool) -> Result<Option<(Document, Value)>> {
if use_artboards(cmd, p)? != Some(false) {
return Ok(None);
}
let doc = &*doc.without_edit_modes();
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?;
let bounds = bounds_without(doc, &left_out).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?;
let mut q = super::export::without_artboards(p);
if let Some(o) = q.as_object_mut() {
o.remove("useArtboards");
@@ -433,6 +437,272 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
Ok(Some((single_artboard(doc, bounds, "Art"), q)))
}
/// The bounds of the visible art of `doc` that a `format` file of the art's bounds draws, as
/// [`art_page`] measures it with that format's default options: for HP-GL without what a plot
/// leaves out ([`vectorcraft_cad::hpgl::write::plots_nothing`]), for other formats all of it (the
/// non-printing layers a PDF leaves out depend on options chosen after the save panel). `None`
/// when there is none, which such an export refuses.
pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
let doc = &*doc.without_edit_modes();
bounds_without(doc, &|n| format == "hpgl" && vectorcraft_cad::hpgl::write::plots_nothing(doc, n))
}
/// 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 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).
let mut names = HashSet::new();
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) = 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(&src.layers, left_out);
let symbols: Vec<(usize, Arc<Node>)> = entries
.iter()
.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(src);
}
let mut d = remapped_doc.unwrap_or_else(|| doc.clone());
if let Some(layers) = layers {
d.layers = layers;
}
for (i, art) in symbols {
if let Some(s) = d.symbols.get_mut(i) {
s.art = art;
}
}
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. 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(&m)
|| !has_effects(&m)
&& n.extras().shaper.is_none()
&& match &n.kind {
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 {
n.appearance.effects.iter().any(|e| e.visible) || n.appearance.items.iter().any(|i| i.visible())
}
/// `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. 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(&as_drawn(n, changed, at)) || n.extras().shaper.is_some() {
return None;
}
let mut taken = false;
let kept: Vec<Arc<Node>> = children
.iter()
.enumerate()
.filter_map(|(i, c)| {
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();
taken.then(|| {
let mut new = (**n).clone();
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind {
*children = kept;
}
Arc::new(new)
})
}
/// The `rect` param of a raster export: `[x, y, width, height]` in points, y down. `None` when
/// absent; an error when it is not four finite numbers with a positive size, when the format isn't
/// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would
@@ -481,6 +751,35 @@ pub(crate) fn with_single_artboard(mut d: Document, rect: Rect, name: &str) -> D
d
}
/// `nodes` with the visible objects that `left_out` picks hidden, in layers, sublayers and groups
/// that don't clip, at any depth (what an object it picks holds is not looked at); `None` when it
/// picks none of them. Clipping layers are looked in too, as their sublayers can be picked.
pub(super) fn hidden_nodes(nodes: &[Arc<Node>], left_out: &dyn Fn(&Node) -> bool) -> Option<Vec<Arc<Node>>> {
let mut out: Option<Vec<Arc<Node>>> = None;
for (i, l) in nodes.iter().enumerate() {
let new = if left_out(l) {
l.visible.then(|| {
let mut n = (**l).clone();
n.visible = false;
Arc::new(n)
})
} else {
let (NodeKind::Layer { children, .. } | NodeKind::Group { children, clip: false }) = &l.kind else { continue };
hidden_nodes(children, left_out).map(|c| {
let mut n = (**l).clone();
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut n.kind {
*children = c;
}
Arc::new(n)
})
};
if let Some(slot) = new.and_then(|new| Some((out.get_or_insert_with(|| nodes.to_vec()).get_mut(i)?, new))) {
*slot.0 = slot.1;
}
}
out
}
fn boards<T>(r: std::result::Result<T, String>) -> Result<T> {
r.map_err(|e| bad(C, e))
}
@@ -636,8 +935,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
{
return Ok(enc);
}
let left_out = |n: &Node| f.id == "hpgl" && vectorcraft_cad::hpgl::write::plots_nothing(doc, n);
if use_artboards == Some(false)
&& let Some((art, q)) = art_page(C, doc, p)?
&& let Some((art, q)) = art_page(C, doc, p, left_out)?
{
return encode_files(&art, f, &q);
}
+19 -5
View File
@@ -550,9 +550,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// Optical Margin Alignment setting and writing direction. When that changes the direction of a
// frame of a restored document, the story flows through that frame's thread again. Threaded
// frames keep their size: Auto Size is off for them. The story is laid out in the document's
// own composite fonts.
// own composite fonts, and type naming one the document does not define flows as in a missing
// font, also when the document defines none.
let fonts = if doc.text_threads.is_empty() { Default::default() } else { doc.composite_fonts.clone() };
let lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&fonts);
let lent = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&fonts);
if !doc.text_threads.is_empty() && !restored {
crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc);
} else if !doc.text_threads.is_empty() {
@@ -677,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> {
File diff suppressed because one or more lines are too long
+95 -6
View File
@@ -2,11 +2,15 @@
//! and `file.place` read ([`LoadOptions`]), the pages they import and `document.pdfInfo` (pages,
//! boxes, a thumbnail; one page for a PostScript file) for the Import PDF dialog.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{ColorMode, Document};
use vectorcraft_doc::{Artboard, ColorMode, Document, LayerColor, LinkInfo, Node, NodeKind};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_pdf::{Choice, CropTo, ImportOptions, PdfError, TextAs};
use super::super::colormgmt::Grays;
use super::super::place::document;
use super::super::{Result, Session, bad, check_numbers, number_or, parse_range, text_param};
use super::{err, source};
@@ -47,6 +51,9 @@ pub struct LoadOptions {
/// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries;
/// off, it opens as another app would open it, from the editing copy of its art or its pages.
pub native: bool,
/// Each page of a PDF opens as a placed document linked to that page of its file, on an
/// artboard of its own, instead of as editable art (`linkPages`; see [`linked_pages`]).
pub link_pages: bool,
}
impl Default for LoadOptions {
@@ -65,6 +72,7 @@ impl Default for LoadOptions {
trust_editing_data: false,
legacy_names: vectorcraft_eps::NameEncoding::default(),
native: true,
link_pages: false,
}
}
}
@@ -74,8 +82,8 @@ impl LoadOptions {
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `editingData` (true | false | `always`),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF
/// import options).
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
let pages = match p.get("pages").filter(|v| !v.is_null()).or_else(|| p.get("page").filter(|v| !v.is_null())) {
None => None,
@@ -115,6 +123,10 @@ impl LoadOptions {
.and_then(vectorcraft_eps::NameEncoding::from_label)
.ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?,
};
let link_pages = match p.get("linkPages").filter(|v| !v.is_null()) {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
Ok(Self {
pages,
@@ -130,14 +142,15 @@ impl LoadOptions {
trust_editing_data,
legacy_names,
native: true,
link_pages,
})
}
/// Does the document read only part of the file, or read it differently (a page range, another
/// box, a password, without its hidden layers, without the VectorCraft document it carries)?
/// Writing it back would lose the rest, so Save doesn't (it asks for a name).
/// box, a password, without its hidden layers, without the VectorCraft document it carries, its
/// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name).
pub fn is_partial(&self) -> bool {
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
}
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
@@ -201,6 +214,82 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
}
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`), in a row from the left
/// with the gap a PDF's artboards open with, and a layer named after the page. The document opens
/// in CMYK when most of the pages read in CMYK, unless `o.color_mode` names a mode. Refused without a
/// path, for any other file, with a password (a linked page is read again without one), with
/// `textAs: outlines` (a linked page shows the file's own type) and for a file over
/// [`document::MAX_FILE`] → the document and the notes of reading its pages.
pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
const C: &str = "document.open";
let file = super::file_name(name);
if !document::is_pdf(name, bytes) {
return Err(bad(C, format!("linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file")));
}
let path = path.ok_or_else(|| bad(C, "linkPages needs the file's path: linked pages are read from it"))?;
if o.password.is_some() {
return Err(bad(C, "linkPages can't open a file with a password: linked pages are read again without it"));
}
if o.text_as != TextAs::Text {
return Err(bad(C, "linkPages can't be used with textAs: outlines: linked pages show the file's own type"));
}
if bytes.len() > document::MAX_FILE {
return Err(bad(C, format!("linkPages: `{file}` is over {} MB", document::MAX_FILE >> 20)));
}
let count = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?.page_count();
let picked = match &o.pages {
None => (0..count).collect(),
Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?,
};
let bounding = o.crop == CropTo::Bounding;
let mut doc = Document::new(1.0, 1.0);
let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?;
doc.artboards.clear();
doc.layers.clear();
let link = crate::cmd::links::link_info(path, bytes);
let gap = ImportOptions::default().artboard_gap;
// Every page's object keeps the same one copy of the file.
let shared = Arc::new(bytes.to_vec());
let (mut x, mut warnings, mut cmyk_pages) = (0.0, Vec::<String>::new(), 0);
for (i, &index) in picked.iter().enumerate() {
let page = index as u32 + 1;
let s = document::shared_source(name, &shared, Some(path), page, bounding, document::page_box(o.crop), C)?;
cmyk_pages += usize::from(s.color_mode == ColorMode::Cmyk);
let mut node = document::node(&mut doc, &s, LinkInfo { page: Some(page), ..link.clone() }, bounding);
if let NodeKind::PlacedDocument(p) = &mut node.kind {
p.xf = Affine::translate((x, 0.0));
}
node.name = Some(file.clone());
let mut layer = Node::layer(doc.alloc_id(), &format!("Page {page}"), LayerColor::Preset((i % 27) as u8));
if let NodeKind::Layer { children, .. } = &mut layer.kind {
children.push(Arc::new(node));
}
doc.layers.push(Arc::new(layer));
let rect = Rect::new(x, 0.0, x + s.frame.width(), s.frame.height());
doc.artboards.push(Artboard { id: i as u32 + 1, name: format!("Artboard {}", i + 1), rect, ..board.clone() });
x = rect.x1 + gap;
for w in s.warnings {
if !warnings.contains(&w) {
warnings.push(w);
}
}
}
// Pages painted mostly in CMYK read as CMYK documents, as opening them as art does: the
// document opens in CMYK (with the CMYK default swatches) when most of its pages do.
if cmyk_pages * 2 > picked.len() {
doc.color_mode = ColorMode::Cmyk;
let (swatches, groups) = vectorcraft_color::default_swatches(ColorMode::Cmyk.model());
(doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into());
}
if let Some(mode) = o.color_mode.filter(|m| *m != doc.color_mode) {
super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, o.grays);
}
Ok((doc, warnings))
}
const INFO: &str = "document.pdfInfo";
/// `document.pdfInfo`.
+9 -152
View File
@@ -3,26 +3,22 @@
//! header's HDpi and VDpi, JP2 capture and display resolution boxes, or a HEIF image's EXIF
//! resolution tags. Place
//! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it
//! as a `pHYs` chunk.
//! as a `pHYs` chunk. The formats the image decoder reads are read by [`vectorcraft_doc::ppi`].
pub(super) use vectorcraft_doc::ppi::png_chunks;
use vectorcraft_doc::ppi::tiff;
pub use vectorcraft_doc::ppi::with_png_resolution;
const INCH_M: f64 = 0.0254;
const INCH_CM: f64 = 2.54;
/// The resolution a file declares as (horizontal, vertical) ppi; `None` when it declares none (or
/// only an aspect ratio).
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
png(bytes)
} else if bytes.starts_with(&[0xff, 0xd8]) {
jpeg(bytes)
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
tiff(bytes)
} else if super::jxlread::is_jxl(bytes) {
if vectorcraft_doc::ppi::reads(bytes) {
return vectorcraft_doc::ppi::resolution(bytes);
}
let r = if super::jxlread::is_jxl(bytes) {
jxl(bytes)
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
webp(bytes)
} else if bytes.starts_with(b"BM") {
bmp(bytes)
} else if super::psdread::is_psd(bytes) {
super::psdread::resolution(bytes)
} else if super::pcxread::is_pcx(bytes) {
@@ -82,121 +78,9 @@ fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> {
fn bytes<const N: usize>(b: &[u8], at: usize) -> Option<[u8; N]> {
slice(b, at, N)?.try_into().ok()
}
fn be16(b: &[u8], at: usize) -> Option<u16> {
bytes(b, at).map(u16::from_be_bytes)
}
fn be32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_be_bytes)
}
fn le32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_le_bytes)
}
/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when
/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi).
fn per_metre(ppm: u32) -> f64 {
let v = ppm as f64 * INCH_M;
let whole = v.round();
if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v }
}
/// PNG chunks after the signature: (type, data).
pub(super) fn png_chunks(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
let mut at = 8;
std::iter::from_fn(move || {
let len = be32(b, at)? as usize;
let ty = slice(b, at + 4, 4)?;
let data = slice(b, at + 8, len)?;
at = at.checked_add(12 + len)?;
Some((ty, data))
})
}
fn png(b: &[u8]) -> Option<(f64, f64)> {
let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?;
// Unit 1 = metre; 0 only gives the pixel aspect ratio.
(d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0))))
}
fn jpeg(b: &[u8]) -> Option<(f64, f64)> {
let (mut jfif, mut exif) = (None, None);
let mut at = 2;
while at + 4 <= b.len() && b[at] == 0xff {
let marker = b[at + 1];
// 0xff fill bytes pad between segments.
if marker == 0xff {
at += 1;
continue;
}
if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
at += 2;
continue;
}
// Start of scan or end of image: no more metadata.
if marker == 0xda || marker == 0xd9 {
break;
}
let len = be16(b, at + 2)? as usize;
let seg = slice(b, at + 4, len.checked_sub(2)?)?;
match marker {
0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => {
let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64);
jfif = match seg[7] {
1 => Some((x, y)),
2 => Some((x * INCH_CM, y * INCH_CM)),
_ => None,
};
}
0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]),
_ => {}
}
at += 2 + len;
}
jfif.or(exif)
}
/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit.
fn tiff(b: &[u8]) -> Option<(f64, f64)> {
let le = b.starts_with(b"II");
let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes });
let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes });
let ifd = u32_at(4)? as usize;
let (mut x, mut y, mut unit) = (None, None, 2);
for i in 0..u16_at(ifd)? as usize {
let e = ifd.checked_add(2 + i * 12)?;
let rational = || -> Option<f64> {
let at = u32_at(e + 8)? as usize;
let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
(d != 0).then(|| n as f64 / d as f64)
};
match u16_at(e)? {
282 => x = rational(),
283 => y = rational(),
296 => unit = u16_at(e + 8)?,
_ => {}
}
}
let k = match unit {
2 => 1.0,
3 => INCH_CM,
_ => return None,
};
let x = x?;
Some((x * k, y.unwrap_or(x) * k))
}
fn webp(b: &[u8]) -> Option<(f64, f64)> {
let mut at = 12;
while at + 8 <= b.len() {
let len = le32(b, at + 4)? as usize;
let data = b.get(at + 8..at + 8 + len)?;
if &b[at..at + 4] == b"EXIF" {
return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data));
}
at += 8 + len + (len & 1);
}
None
}
fn jxl(b: &[u8]) -> Option<(f64, f64)> {
if !b.starts_with(&[0, 0, 0, 12, b'J', b'X', b'L', b' ', 13, 10, 135, 10]) {
@@ -224,33 +108,6 @@ fn jxl(b: &[u8]) -> Option<(f64, f64)> {
None
}
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
if le32(b, 14)? < 40 {
return None;
}
let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre);
Some((ppm(38)?, ppm(42)?))
}
/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced).
pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> {
let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() };
let chunk = vectorcraft_render::encode::png::phys_chunk(x, y);
let mut out = Vec::with_capacity(png.len() + chunk.len());
out.extend_from_slice(head);
out.extend_from_slice(&chunk);
let mut at = head.len();
while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) {
if chunk.get(4..8) != Some(b"pHYs") {
out.extend_from_slice(chunk);
}
at += chunk.len();
}
out.extend_from_slice(png.get(at..).unwrap_or_default());
out
}
#[cfg(test)]
mod tests {
use super::*;
+15 -6
View File
@@ -757,8 +757,9 @@ pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str =
pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false";
/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of
/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor
/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
/// `doc`'s visible art on the layers its pages draw ([`super::pdf::art_page`]). It carries neither
/// the native document nor the editing copy for other apps, and its notes end with
/// [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy
/// version 7 `.ai` file.
pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Option<Encoded>> {
@@ -768,7 +769,7 @@ pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Valu
if !bool_or(p, "pdfCompatible", true) {
return Err(bad(cmd, ART_PAGE_NEEDS_PDF));
}
let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
let Some((art, q)) = super::pdf::art_page(cmd, doc, &ai_pdf_params(p, false))? else { return Ok(None) };
let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?;
enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string());
Ok(Some(enc))
@@ -784,9 +785,10 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
encode_ai_pages(cmd, f, doc, p, true)
}
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
/// the editing copy for other apps when `editing` is true, and neither otherwise.
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
/// `p` with the PDF options a `.ai` file is written with: Preserve Editing when `editing` is true,
/// layers unless a standard decides, long pages with a `UserUnit`, and `compress` as
/// `compression.compressText`.
fn ai_pdf_params(p: &Value, editing: bool) -> Value {
let mut params = if p.is_object() { p.clone() } else { json!({}) };
if let Some(o) = params.as_object_mut() {
o.insert("preserveEditing".into(), json!(editing));
@@ -805,6 +807,13 @@ fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bo
}
}
}
params
}
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
/// the editing copy for other apps when `editing` is true, and neither otherwise.
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
let params = ai_pdf_params(p, editing);
let pdf_compatible = bool_or(&params, "pdfCompatible", true);
let f = &if pdf_compatible { *f } else { without_pdf(f) };
let native_options = super::native::ai_options(cmd, f, doc, &params)?;
+191
View File
@@ -170,6 +170,197 @@ fn a_plot_reads_back_as_its_art() {
assert!((board.height() - (30.0 + pen)).abs() < 0.1, "{board:?}");
}
/// A plot of the art's bounds is measured on the art it plots: art on a non-printing layer, on a
/// layer at 0% opacity or at 0% opacity in a group, a placed image and a path that paints nothing
/// don't move its origin, a clipping layer is measured as clipped, and a document whose only
/// visible art is such art is refused.
#[test]
fn a_plot_of_the_arts_bounds_leaves_out_the_layers_it_does_not_plot() {
let mut s = two_boards();
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
let alone = plot(&mut s).unwrap();
let printing = s.doc().unwrap().doc.layers[0].id;
for props in [json!({"printable": false}), json!({})] {
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
if props.as_object().unwrap().is_empty() {
s.execute("transparency.set", &json!({"ids": [layer], "opacity": 0})).unwrap();
} else {
let mut p = props.clone();
p["id"] = layer.clone();
s.execute("layer.setProps", &p).unwrap();
}
s.execute("shape.rectangle", &json!({"x": -300, "y": 500, "width": 20, "height": 20})).unwrap();
assert_eq!(plot(&mut s).unwrap(), alone, "{props}");
}
// An object at 0% opacity in a group, on a layer that plots.
s.execute("layer.new", &json!({})).unwrap();
let far = s.execute("shape.rectangle", &json!({"x": -500, "y": 700, "width": 20, "height": 20})).unwrap()["id"].clone();
s.execute("object.group", &json!({"ids": [far]})).unwrap();
s.execute("transparency.set", &json!({"ids": [far], "opacity": 0})).unwrap();
assert_eq!(plot(&mut s).unwrap(), alone, "0% opacity in a group");
// A placed image and a path whose fill and stroke paint nothing.
let mut png = vec![];
image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap();
assert_eq!(plot(&mut s).unwrap(), alone, "a placed image");
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();
assert_eq!(plot(&mut s).unwrap(), alone, "a path that paints nothing");
// A clipping layer's clipping path, which loses its paint, still clips the art measured: a
// large square clipped to the first square draws nothing more.
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
s.execute("shape.rectangle", &json!({"x": -300, "y": -300, "width": 800, "height": 800})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
assert_eq!(plot(&mut s).unwrap(), alone, "a clipping layer");
s.execute("layer.setProps", &json!({"id": clipping, "visible": false})).unwrap();
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
let e = plot(&mut s).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
}
/// A placed image in a symbol's art doesn't move a plot of the art's bounds either, and a
/// document whose only other visible art is an instance of that symbol is refused.
#[test]
fn a_plot_of_the_arts_bounds_leaves_out_images_in_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 alone = plot(&mut s).unwrap();
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();
s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap();
s.execute("symbol.new", &json!({"name": "Far"})).unwrap();
assert!(s.doc().unwrap().doc.symbols.iter().any(|sym| sym.name == "Far"));
assert_eq!(plot(&mut s).unwrap(), alone, "an image in symbol art");
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
let e = plot(&mut s).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
// A symbol of a square and an image is measured by its square.
let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap();
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone();
let before = bounds(&s);
let image = s.execute("file.place", &json!({"name": "near.png", "dataBase64": b64(&png), "at": [400, 600]})).unwrap()["ids"][0].clone();
s.execute("symbol.new", &json!({"name": "Both", "ids": [square, image]})).unwrap();
assert_eq!(s.doc().unwrap().doc.symbols.len(), 2);
let after = bounds(&s);
for (a, b) in [(before.x0, after.x0), (before.y0, after.y0), (before.x1, after.x1), (before.y1, after.y1)] {
assert!((a - b).abs() < 1e-6, "{before:?} {after:?}");
}
}
/// 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]
fn a_plot_of_the_arts_bounds_measures_images_by_their_halftone_dots() {
let mut s = two_boards();
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
let printing = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.new", &json!({})).unwrap();
let mut png = vec![];
image::DynamicImage::new_rgb8(100, 100).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.execute("file.place", &json!({"name": "dots.png", "dataBase64": b64(&png), "at": [300, 300]})).unwrap();
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
// At 300 lines per inch a 100 pt image takes more cells than the effect makes.
s.execute("effect.apply", &json!({"effect": "addon.color.halftone", "params": {"frequency": 300}})).unwrap();
let e = plot(&mut s).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
s.execute("effect.apply", &json!({"effect": "addon.color.halftone", "params": {"frequency": 20}})).unwrap();
let out = String::from_utf8(plot(&mut s).unwrap()).unwrap();
assert!(out.contains("PD"), "{out}");
}
#[test]
fn export_options_are_checked() {
let mut s = two_boards();
+42
View File
@@ -103,6 +103,48 @@ fn use_artboards_false_writes_one_page_of_the_arts_bounds() {
}
}
/// A page of the art's bounds is measured on the layers the PDF draws: a non-printing layer that
/// the PDF leaves out doesn't make it larger, unless `includeNonPrinting` or `createLayers` keeps
/// the layer. A `.ai` file of the art's bounds, which keeps layers by default, measures it unless
/// `createLayers` is off. A document whose only visible art doesn't print is refused.
#[test]
fn a_page_of_the_arts_bounds_leaves_out_non_printing_layers() {
let mut s = session(1);
let printing = s.doc().unwrap().doc.layers[0].id;
let notes = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap();
s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap();
let size = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().artboards[0].rect.size();
let printed = size(&b64(&export(&mut s, json!({"useArtboards": false}))));
assert!(printed.width < 50.0 && printed.height < 40.0, "{printed:?}");
let through_export = s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap();
assert_eq!(size(&b64(&through_export)), printed);
let ai = |s: &mut Session, extra: Value| {
let mut p = json!({"format": "ai", "useArtboards": false});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
size(&b64(&s.execute("document.export", &p).unwrap_or_else(|e| panic!("{p}: {e}"))))
};
assert_eq!(ai(&mut s, json!({"createLayers": false})), printed);
let kept = [
size(&b64(&export(&mut s, json!({"useArtboards": false, "includeNonPrinting": true})))),
size(&b64(&export(&mut s, json!({"useArtboards": false, "createLayers": true})))),
ai(&mut s, json!({})),
];
for all in kept {
assert!(all.width > 200.0 && all.height > 200.0, "{all:?}");
}
// Only the non-printing layer shows: the PDF would draw nothing.
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
for p in [json!({"useArtboards": false}), json!({"useArtboards": false, "includeNonPrinting": false})] {
let e = s.execute("document.exportPdf", &p).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{p}: {e}");
}
let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "createLayers": false})).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
assert!(size(&b64(&export(&mut s, json!({"useArtboards": false, "includeNonPrinting": true})))).width < 25.0);
}
/// In a PDF without a standard, the warning for a page longer than 14,400 pt written with a
/// `UserUnit` above 1 names "Write pages longer than 200 in at full size in points": at PDF 1.5
/// (written as 1.6) and later, through `document.exportPdf`, `document.export`, a page of the
+79 -7
View File
@@ -797,22 +797,47 @@ fn place_of(d: &Document, roots: &[NodeId]) -> Option<NodeId> {
}
/// The ruler guides of each of `roots` that is a sublayer (in its sublayers too), with the layer
/// that holds it, in order. Other objects hold none.
/// that holds it, in order. Other objects hold none. Each root, and each child of it and of its
/// sublayers, is looked at once.
fn held_guides(d: &Document, roots: impl IntoIterator<Item = NodeId>) -> Vec<(NodeId, Node)> {
let mut out = vec![];
for id in roots {
let (Some(n), Some(parent)) = (d.node(id), d.parent_of(id)) else { continue };
if n.holds_ruler_guides() {
n.walk(&mut |c| {
if c.is_ruler_guide() {
out.push((parent, c.clone()));
}
});
guide_seen(n);
if n.is_layer() {
guides_of(n, parent, &mut out);
}
}
out
}
/// Push each ruler guide of `layer` and of its sublayers onto `out` in paint order, with `parent`.
fn guides_of(layer: &Node, parent: NodeId, out: &mut Vec<(NodeId, Node)>) {
for c in layer.children().into_iter().flatten() {
guide_seen(c);
if c.is_ruler_guide() {
out.push((parent, Node::clone(c)));
} else if c.is_layer() {
guides_of(c, parent, out);
}
}
}
#[cfg(test)]
thread_local! {
/// The nodes that [`held_guides`] has looked at on this thread, in order.
static GUIDES_SEEN: std::cell::RefCell<Vec<NodeId>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Note that [`held_guides`] looked at `n`.
#[cfg(test)]
fn guide_seen(n: &Node) {
GUIDES_SEEN.with(|s| s.borrow_mut().push(n.id));
}
#[cfg(not(test))]
fn guide_seen(_: &Node) {}
/// An image of `r` (in a clip group when it is clipped).
fn raster_node(d: &mut Document, r: Raster) -> Node {
let key = unique_key(d, "flattened");
@@ -922,6 +947,53 @@ mod tests {
assert_eq!(flat.children(Some(layer)).and_then(|c| c.last()).map(|c| c.id), Some(g));
}
/// The guides of a sublayer and of its sublayers are gathered in paint order with the layer
/// that holds it, looking at the sublayer and each child of it and of its sublayers once.
/// Other roots give none.
#[test]
fn held_guides_look_at_each_node_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let layer = s.doc().unwrap().doc.layers[0].id;
let sublayer =
|s: &mut Session, parent: NodeId| NodeId(s.execute("layer.newSublayer", &json!({"parent": parent.0})).unwrap()["id"].as_u64().unwrap());
let rect = |s: &mut Session, on: NodeId| {
s.execute("layer.setCurrent", &json!({"id": on.0})).unwrap();
NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap())
};
let sub = sublayer(&mut s, layer);
let deep = sublayer(&mut s, sub);
let empty = sublayer(&mut s, layer);
let (a, b, c) = (rect(&mut s, sub), rect(&mut s, deep), rect(&mut s, empty));
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let mut guide = |on: NodeId, pos: f64| {
let g = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: true, pos, artboard: None });
d.insert(Some(on), usize::MAX, g).unwrap()
};
let (g1, g2, g3) = (guide(sub, 1.0), guide(deep, 2.0), guide(sub, 3.0));
let doc = &s.doc().unwrap().doc;
let ids = |n: &Node| {
let mut v = vec![];
n.walk(&mut |c| v.push(c.id));
v
};
assert_eq!(ids(doc.node(sub).unwrap()), vec![sub, deep, b, g2, a, g1, g3]);
let run = |roots: &[NodeId]| {
GUIDES_SEEN.with(|v| v.borrow_mut().clear());
let got: Vec<_> = held_guides(doc, roots.iter().copied()).into_iter().map(|(p, g)| (p, g.id)).collect();
(got, GUIDES_SEEN.with(|v| v.take()))
};
// Every node of the sublayer is looked at once, and the guides keep their paint order.
assert_eq!(run(&[sub]), (vec![(layer, g2), (layer, g1), (layer, g3)], vec![sub, deep, b, g2, a, g1, g3]));
// A sublayer that holds none gives none; a path holds none; a missing root and a top-level
// layer, which has no parent, are skipped.
assert_eq!(run(&[empty]), (vec![], vec![empty, c]));
assert_eq!(run(&[a]), (vec![], vec![a]));
assert_eq!(run(&[NodeId(u64::MAX), layer]), (vec![], vec![]));
// A deeper sublayer gives its guides to the sublayer that holds it.
assert_eq!(run(&[deep, deep]).0, vec![(sub, g2), (sub, g2)]);
}
/// In a file without transparency with Clip Complex Regions on, art under a group's opaque
/// image within one of its pixels joins the group, also where a long image is made at a lower
/// resolution and its pixels are wider than at the preset's.
+135 -30
View File
@@ -6,20 +6,34 @@
//! (<https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html>), in our words:
//!
//! - With one object selected, Start Global Edit finds the objects that repeat its shape: the
//! same outline, wherever it lies and at whatever size. Two options narrow the match: Appearance
//! (the same fill and stroke too) and Size (the same width and height too). The search covers
//! every artboard and the canvas around them by default; it can be limited to a range of
//! artboards (`1, 3-5`) and can leave out the objects that lie on no artboard. Images, type,
//! masks, linked files and selections of more than one object are not supported.
//! same outline, wherever it lies, at whatever size and at whatever angle. Two options narrow
//! the match: Appearance (the same fill and stroke too) and Size (the same width and height
//! too). The search covers every artboard and the canvas around them by default; it can be
//! limited to a range of artboards (`1, 3-5`) and can leave out the objects that lie on no
//! artboard. Images, type, masks, linked files and selections of more than one object are not
//! supported.
//! - The help page "Edit groups with similar objects"
//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html>):
//! with a group selected, Start Global Edit finds the groups like it, and an edit made to an
//! object inside one of them is made to the matching object in each of the others. Here a group
//! is like another when it holds as many objects, in the same order, each like the one at its
//! place (paths, compound paths, symbol instances and groups of them, clipping paths included),
//! and they lie the same way relative to each other: the group as a whole is moved or scaled.
//! With Appearance on, each of those objects must have the same fill and stroke too; with Size,
//! the groups the same width and height.
//! and they lie the same way relative to each other: the group as a whole is moved, scaled or
//! rotated. With Appearance on, each of those objects must have the same fill and stroke too;
//! with Size, the groups the same width and height.
//! - The how-to "Design a modern geometric logo"
//! (<https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html>) makes rotated
//! copies of a group of shapes around a point, then starts Global Edit on one object and edits
//! every copy of it at once. Here a rotated copy is found as a moved or scaled one is, and an
//! edit reaches it turned by its own angle: an anchor moved to the right on the selected object
//! moves downward on a copy turned a quarter turn clockwise. The rules below for rotated copies
//! are VectorCraft's own. The angle is the one that lays each anchor and handle of the selected
//! object on the copy's of the same order, so a square whose anchors were turned a quarter turn
//! is a copy turned a quarter turn. A copy is the same shape when, laid so, every anchor and
//! handle lies within a millionth of the larger side of the copy's box of its own ([`SAME`]).
//! A reflected copy is another shape. With Size, a rotated copy has the same size when it is the
//! selected object rotated without scaling: its width and height are compared as they were
//! before the rotation.
//! - Selecting one of the repeated objects with the Selection tool highlights the similar objects
//! at once, before Global Edit starts. Here they are the objects Start Global Edit would take
//! with the current Global Edit Options ([`similar`]).
@@ -29,15 +43,16 @@
//!
//! Here the found objects ([`GlobalEdit::members`]) stay highlighted while the selection keeps the
//! object that was selected, so that the Transform panel and the bounding box measure that object
//! and not the whole set. Each member keeps the transform (a move and a uniform scale) that maps
//! the first object's outline onto its own. After every edit ([`propagate`], run inside
//! [`Session::edit`], so the whole change is one undo step), the first selected member the edit
//! changed is the model: what changed about it is given to every other member, and nothing else,
//! so members found by shape alone keep their own fills and strokes where the edit didn't touch
//! them:
//! and not the whole set. Each member keeps the transform (a move, a uniform scale and, for a
//! rotated copy, a turn) that maps the first object's outline onto its own. After every edit
//! ([`propagate`], run inside [`Session::edit`], so the whole change is one undo step), the first
//! selected member the edit changed is the model: what changed about it is given to every other
//! member, and nothing else, so members found by shape alone keep their own fills and strokes
//! where the edit didn't touch them:
//!
//! - its outline (and anchors), placed through that transform, so in proportion to each member's
//! size. Only geometry is placed so: no stroke weight is scaled to a member's size;
//! size and turned by its angle. Only geometry is placed so: no stroke weight is scaled to a
//! member's size;
//! - its opacity, blending, knockout and the object's effects, each when it changed;
//! - of its fills and strokes, each setting that changed (paint, weight, opacity, blending,
//! effects, caps, dashes, arrowheads …), as it is: it goes to the member's fill or stroke of the
@@ -74,12 +89,12 @@
//! and later edits leave it as it is.
//! The object the edit started from can't be left out (a Shift-click on it selects it or
//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving
//! one out is not an undo step. Rotated copies are not covered.
//! one out is not an undo step.
use serde::Serialize;
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape, Vec2};
use super::wand::{fill_of, stroke_of};
use super::{CommandSpec, Result, Session, bad, bool_or, checked_id, cmd, has_doc};
@@ -98,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Start Global Edit",
["Select"],
None,
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}",
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape, moved, scaled or rotated copies of it and not reflected ones (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height, for a rotated copy before its rotation) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}",
can_toggle,
toggle
),
@@ -181,7 +196,8 @@ pub type Outlines = Vec<(BezPath, [u8; 3])>;
#[derive(Clone, Debug, PartialEq)]
pub struct GlobalEdit {
/// The objects edited together, the one selected at the start first, each with the transform
/// (a move and a uniform scale) that maps that first object's outline onto its own.
/// (a move, a uniform scale and, for a turned copy, a turn) that maps that first object's
/// outline onto its own.
pub members: Vec<(NodeId, Affine)>,
/// [`highlights`] as of a document revision: the canvas asks every frame.
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
@@ -257,14 +273,60 @@ impl Form {
}
}
fn same(&self, o: &Form) -> bool {
self.tag == o.tag
&& self.symbols == o.symbols
&& self.points.len() == o.points.len()
&& self.points.iter().zip(&o.points).all(|(a, b)| a.distance(*b) < 1e-6)
/// The transform that lays this form's object on `o`'s, point for point in order, and whether
/// it turns the object: a move and a uniform scale when the two lie the same way, otherwise a
/// turn too. `None` when `o` is another shape, a reflected copy included.
fn onto(&self, o: &Form) -> Option<(Affine, bool)> {
if self.tag != o.tag || self.symbols != o.symbols || self.points.len() != o.points.len() {
return None;
}
let near = |xf: Affine| self.points.iter().zip(&o.points).all(|(a, b)| (xf * *a).distance(*b) < SAME);
let back = self.frame.inverse();
if near(Affine::IDENTITY) {
return Some((o.frame * back, false));
}
let turn = self.turn_onto(o)?;
near(turn).then(|| (o.frame * turn * back, true))
}
/// The turn, uniform scale and move (both forms in their unit boxes) that best lays this
/// form's points on `o`'s in order, by least squares. A turn within [`SQUARE`] of a quarter
/// turn is that quarter turn exactly.
fn turn_onto(&self, o: &Form) -> Option<Affine> {
let n = self.points.len() as f64;
let middle = |f: &Form| f.points.iter().fold(Vec2::ZERO, |s, p| s + p.to_vec2()) / n;
let (from, to) = (middle(self), middle(o));
// With the points as complex numbers about their middles, the fit is `Σ conj(p) q / Σ |p|²`.
let (mut re, mut im, mut spread) = (0.0, 0.0, 0.0);
for (a, b) in self.points.iter().zip(&o.points) {
let (p, q) = (a.to_vec2() - from, b.to_vec2() - to);
re += p.dot(q);
im += p.cross(q);
spread += p.hypot2();
}
let len = re.hypot(im);
let scale = len / spread;
if !(scale.is_finite() && scale > 0.0) {
return None;
}
let (mut cos, mut sin) = (re / len, im / len);
if cos.abs() < SQUARE {
(cos, sin) = (0.0, sin.signum());
} else if sin.abs() < SQUARE {
(cos, sin) = (cos.signum(), 0.0);
}
let (a, b) = (scale * cos, scale * sin);
Some(Affine::translate(to) * Affine::new([a, b, -b, a, 0.0, 0.0]) * Affine::translate(-from))
}
}
/// How far apart two forms' points may lie, each form in its unit box, for the forms to be the
/// same. For a turned copy this bounds the angle too: a copy turned and then changed by more than
/// a millionth of its larger side is another shape.
const SAME: f64 = 1e-6;
/// A turn whose sine or cosine is below this is taken as a whole number of quarter turns.
const SQUARE: f64 = 1e-9;
/// Global Edit supports paths, compound paths, symbol instances and groups of them; not images,
/// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists
/// images, text, masks and links as unsupported).
@@ -395,8 +457,16 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
}
boards.as_ref().is_none_or(|rs| rs.iter().any(|r| on(*r, b)))
};
// A copy that lies the same way has the size of the selected object when their boxes are as
// wide and as high; a turned copy, when the transform that lays the object on it doesn't scale.
let same_size = |n: &Node, xf: Affine, turned: bool| {
if turned {
close(xf.determinant().abs().sqrt(), 1.0)
} else {
matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))
}
};
let mut out = vec![(*id, Affine::IDENTITY)];
let back = form.frame.inverse();
super::select::walk_selectable(d, st.isolation, |n| {
if n.id == *id || out.len() >= MAX_MEMBERS {
return false;
@@ -413,12 +483,12 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
};
// The object count first: it turns most objects down before their form is made.
if n.children().map(Vec::len) == count
&& let Some(f) = Form::of(n).filter(|f| f.same(&form) && supported(n))
&& (!o.size || matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2)))
&& let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n))
&& (!o.size || same_size(n, xf, turned))
&& (!o.appearance || same_look(key, n))
&& in_scope(n)
{
out.push((n.id, f.frame * back));
out.push((n.id, xf));
// A group taken is taken whole, as compound paths, symbol instances and the others are.
return false;
}
@@ -464,7 +534,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
let o = s.global_edit_options.with(p, &s.doc()?.doc, C)?;
let members = matches(s, &o)?;
if members.len() < 2 {
return Err(bad(C, "no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again"));
return Err(bad(C, "no similar objects found (reflected copies are not matched); change the Global Edit Options and try again"));
}
let ids: Vec<u64> = members.iter().map(|(id, _)| id.0).collect();
let st = s.doc_mut()?;
@@ -795,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 {
@@ -804,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
@@ -1027,6 +1100,38 @@ mod tests {
assert!(taken > 100 && checked - taken > 100 && asked > 200, "{taken} of {checked}, {asked} selected");
}
#[test]
fn a_form_is_laid_on_a_turned_copy_and_on_no_reflected_or_unmeasurable_one() {
let mut d = Document::new(800.0, 600.0);
let mut path = |points: &[(f64, f64)]| {
let anchors = points.iter().map(|(x, y)| Anchor::corner(Point::new(*x, *y))).collect();
Node::path(d.alloc_id(), PathData::new(vec![SubPath::new(anchors, true)]), Appearance::default())
};
let form = Form::of(&path(&[(0.0, 0.0), (30.0, 0.0), (30.0, 70.0)])).unwrap();
let mut onto = |points: &[(f64, f64)]| Form::of(&path(points)).and_then(|f| form.onto(&f));
let near = |xf: Affine, want: [f64; 6]| xf.as_coeffs().iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9);
// The same way at twice the size: a move and a scale, no turn.
let (xf, turned) = onto(&[(100.0, 0.0), (160.0, 0.0), (160.0, 140.0)]).unwrap();
assert!(!turned && near(xf, [2.0, 0.0, 0.0, 2.0, 100.0, 0.0]), "{xf:?}");
// A quarter turn, (x, y) → (−y, x), moved by (100, 0); and a turn by 30° at half the size.
let (xf, turned) = onto(&[(100.0, 0.0), (100.0, 30.0), (30.0, 30.0)]).unwrap();
assert!(turned && near(xf, [0.0, 1.0, -1.0, 0.0, 100.0, 0.0]), "{xf:?}");
let by = Affine::rotate(30f64.to_radians()) * Affine::scale(0.5);
let at = |x: f64, y: f64| {
let p = by * Point::new(x, y);
(p.x, p.y)
};
let (xf, turned) = onto(&[at(0.0, 0.0), at(30.0, 0.0), at(30.0, 70.0)]).unwrap();
assert!(turned && near(xf, by.as_coeffs()), "{xf:?}");
// A reflected copy, a copy with an anchor a thousandth of its size away, and points that
// are not numbers or not finite.
assert!(onto(&[(0.0, 0.0), (-30.0, 0.0), (-30.0, 70.0)]).is_none());
assert!(onto(&[at(0.0, 0.0), at(30.0, 0.0), at(30.0, 70.07)]).is_none());
assert!(onto(&[(f64::NAN, 0.0), (30.0, 0.0), (30.0, 70.0)]).is_none());
assert!(onto(&[(0.0, 0.0), (f64::INFINITY, 0.0), (30.0, 70.0)]).is_none());
assert!(onto(&[(0.0, 0.0), (30.0, 0.0)]).is_none(), "another count of anchors");
}
#[test]
fn support_of_empty_degenerate_and_deep_objects_is_decided_as_building_the_form_decides() {
let mut d = Document::new(800.0, 600.0);
+2 -1
View File
@@ -40,6 +40,7 @@ pub use commands::specs;
pub(crate) use data::apply_csv;
#[cfg(test)]
use data::{fmt_value, parse_csv, to_csv};
pub(crate) use edit::{graphs_holding, keep_placed};
#[cfg(test)]
use generate::generate;
#[cfg(test)]
@@ -47,7 +48,7 @@ use series::default_series_color;
pub(crate) use series::{
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in,
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in,
series_object_opacity_differs, shown_paint,
};
+56 -2
View File
@@ -1,3 +1,5 @@
use vectorcraft_doc::graph::art_bounds;
use super::axis::{MAX_TICK_MARKS, count_given, one_line};
use super::data::apply_data;
use super::generate::{children_bounds, generate};
@@ -17,11 +19,62 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<f64>>> {
}
}
/// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now:
/// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such
/// bounds with a width and a height, or has no art without type now.
fn measured(n: &Node) -> Option<(Rect, Rect)> {
let kept = n.extras().graph.as_deref()?;
let c = n.children()?;
let art = kept.placed_art.filter(|p| p.width() > 1e-9 && p.height() > 1e-9).zip(art_bounds(c));
art.or_else(|| kept.placed.zip(children_bounds(c)))
}
/// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them.
/// `None` when `from` has no width or no height.
fn carried(r: Rect, from: Rect, to: Rect) -> Option<Rect> {
if from.width() <= 1e-9 || from.height() <= 1e-9 {
return None;
}
let (sx, sy) = (to.width() / from.width(), to.height() / from.height());
Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy))
}
/// The graphs holding objects `ids`, each with the bounds of its art without type and of all its art. Give them to
/// [`keep_placed`] after an edit that changes a graph's art without moving the graph.
pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option<Rect>, Option<Rect>)> {
let mut out: Vec<(NodeId, Option<Rect>, Option<Rect>)> = vec![];
for id in ids {
let Some(chain) = d.ancestry(*id) else { continue };
let holder = chain.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(|n| n.extras().graph.is_some()));
let Some(gid) = holder.filter(|g| !out.iter().any(|(o, ..)| o == g)) else { continue };
let children = d.node(gid).and_then(Node::children);
out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c))));
}
out
}
/// After an edit that changed the art of `graphs` (from [`graphs_holding`]) without moving them, set the bounds each
/// keeps so that its next redraw measures the same move or scale as it would have before the edit.
pub(crate) fn keep_placed(d: &mut Document, graphs: &[(NodeId, Option<Rect>, Option<Rect>)]) {
for &(gid, art_was, whole_was) in graphs {
let Some(n) = d.node(gid) else { continue };
let children = n.children();
let (art_now, whole_now) = (children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c)));
let Some(spec) = d.node_mut(gid).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
if let (Some(placed), Some(was), Some(now)) = (spec.placed_art, art_was, art_now) {
spec.placed_art = carried(now, was, placed).or(spec.placed_art);
}
if let (Some(placed), Some(was), Some(now)) = (spec.placed, whole_was, whole_now) {
spec.placed = carried(now, was, placed).or(spec.placed);
}
}
}
/// Regenerate graph `id` from `spec` (adjusting the plot rect for any move/scale since the last
/// generation, which is recorded in the spec's `placed` bounds).
/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them).
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
if let (Some(placed), Some(now)) = (n.extras().graph.as_ref().and_then(|g| g.placed), n.children().and_then(|c| children_bounds(c)))
if let Some((placed, now)) = measured(n)
&& placed.width() > 1e-9
&& placed.height() > 1e-9
&& (placed.x0 - now.x0).abs() + (placed.y0 - now.y0).abs() + (placed.x1 - now.x1).abs() + (placed.y1 - now.y1).abs() > 1e-6
@@ -33,6 +86,7 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R
}
let children = generate(d, &spec);
spec.placed = children_bounds(&children);
spec.placed_art = art_bounds(&children);
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
if let Some(ch) = n.children_mut() {
*ch = children;
+2 -2
View File
@@ -6,7 +6,7 @@ use super::labels::{
recolour_text, runs, shadow_of,
};
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_opacity};
use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_group_opacity, with_series_opacity};
use super::{
Arc, BezPath, Color, Document, GraphKind, GraphSpec, Justify, Node, NodeKind, Paint, PathData, Point, Rect, TickLength, ValueAxisSide, shapes,
};
@@ -1005,7 +1005,7 @@ impl<'a> Plot<'a> {
}
}
let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1));
let grp = self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items)));
let grp = with_series_group_opacity(g, s, self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items))));
self.b.out.push(grp);
}
self.b.out.append(&mut self.on_top);
+111 -30
View File
@@ -475,15 +475,16 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool
settle_series_paints(doc, before)
}
/// Copy the object opacity and blend mode of generated series art just edited (`edited`) into that series' object opacity
/// and blend mode. Called inside the same document edit, so both undo together. Returns whether a series' kept object
/// opacity or blend mode changed.
/// Copy the object transparency of generated series art just edited (`edited`) into what that series keeps: a path
/// directly in a series group sets the paths' object opacity and blend mode, and the series group itself sets the
/// group's opacity, blend mode, isolation, knockout and knockout shape. Called inside the same document edit, so both undo
/// together. Returns whether what a series keeps changed.
pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId]) -> bool {
let mut before = SeriesPaintsBefore::new();
for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) {
for (graph, index, group, look) in object_opacity_captures(doc, edited) {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
// A fully opaque Normal object on a series the graph keeps nothing for leaves the graph as it is.
if opacity.is_none() && blend.is_none() && spec.series_paints.len() <= index {
if look == ObjectOpacity::default() && spec.series_paints.len() <= index {
continue;
}
before.entry(graph).or_insert_with(|| spec.series_paints.clone());
@@ -492,7 +493,12 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
}
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
(slot.opacity, slot.blend) = (opacity, blend);
if group {
(slot.group_opacity, slot.group_blend) = (look.opacity, look.blend);
(slot.group_isolate, slot.group_knockout, slot.group_knockout_shape) = (look.isolate, look.knockout, look.knockout_shape);
} else {
(slot.opacity, slot.blend) = (look.opacity, look.blend);
}
}
settle_series_paints(doc, before)
}
@@ -500,20 +506,50 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId
/// Would [`capture_series_object_opacity`] change what the graph stores for `edited`? Reads the document without copying
/// it.
pub(crate) fn series_object_opacity_differs(doc: &Document, edited: &[NodeId]) -> bool {
let mut after: HashMap<(NodeId, usize), (Option<f32>, Option<BlendMode>)> = HashMap::new();
let stored = |graph: NodeId, index: usize| {
let mut after: HashMap<(NodeId, usize, bool), ObjectOpacity> = HashMap::new();
let stored = |graph: NodeId, index: usize, group: bool| {
let spec = doc.node(graph).and_then(|n| n.extras().graph.as_deref());
spec.and_then(|g| g.series_paints.get(index)).map_or((None, None), |slot| (slot.opacity, slot.blend))
let slot = spec.and_then(|g| g.series_paints.get(index));
slot.map_or_else(ObjectOpacity::default, |slot| {
if group {
ObjectOpacity {
opacity: slot.group_opacity,
blend: slot.group_blend,
isolate: slot.group_isolate,
knockout: slot.group_knockout,
knockout_shape: slot.group_knockout_shape,
}
} else {
ObjectOpacity { opacity: slot.opacity, blend: slot.blend, ..ObjectOpacity::default() }
}
})
};
for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) {
after.insert((graph, index), (opacity, blend));
for (graph, index, group, look) in object_opacity_captures(doc, edited) {
after.insert((graph, index, group), look);
}
after.into_iter().any(|((graph, index), pair)| stored(graph, index) != pair)
after.into_iter().any(|((graph, index, group), look)| stored(graph, index, group) != look)
}
/// The series and object opacity and blend mode (None for 100% and Normal) of each of `edited` that is a path directly in a
/// series group, in order.
fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, Option<f32>, Option<BlendMode>)> {
/// The series groups among `ids`, for an edit that changes only what a group's transparency has beyond its opacity and
/// blend mode (isolation, knockout and knockout shape), which the graph keeps for series groups alone.
pub(crate) fn series_groups_among(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| n.extras().series_index.is_some())).collect()
}
/// An object's transparency as a graph keeps it: the object opacity and blend mode (None for 100% and Normal), and for a
/// series group its isolation, knockout (None for neutral) and knockout shape. Paths keep the first two only.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct ObjectOpacity {
opacity: Option<f32>,
blend: Option<BlendMode>,
isolate: bool,
knockout: Option<vectorcraft_doc::Knockout>,
knockout_shape: bool,
}
/// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object
/// transparency of each of `edited` that is one of those, in order.
fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> {
if edited.is_empty() {
return Vec::new();
}
@@ -524,14 +560,48 @@ fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, us
edited
.iter()
.filter_map(|id| {
// Only the paths the graph draws again, not the copy of a graph design.
let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?;
let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?;
Some((r.graph, r.index, (node.opacity < 1.0).then_some(node.opacity), (node.blend != BlendMode::Normal).then_some(node.blend)))
let r = members.get(id)?;
let group = r.group == *id;
// Only the series group and the paths the graph draws again, not the copy of a graph design.
let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?;
let mut look = ObjectOpacity {
opacity: (node.opacity < 1.0).then_some(node.opacity),
blend: (node.blend != BlendMode::Normal).then_some(node.blend),
..ObjectOpacity::default()
};
if group {
look.isolate = node.isolate;
look.knockout = (node.knockout != vectorcraft_doc::Knockout::Neutral).then_some(node.knockout);
look.knockout_shape = node.knockout_shape;
}
Some((r.graph, r.index, group, look))
})
.collect()
}
/// Series `i`'s group (`group`) with the object opacity, blend mode, isolation, knockout and knockout shape the graph
/// keeps for it. An opacity read from a file is held to 0..1, and one that is not a number is left out.
pub(super) fn with_series_group_opacity(g: &GraphSpec, i: usize, mut group: Arc<Node>) -> Arc<Node> {
let Some(slot) = g.series_paints.get(i) else { return group };
let opacity = slot.group_opacity.filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0));
if opacity.is_none() && slot.group_blend.is_none() && !slot.group_isolate && slot.group_knockout.is_none() && !slot.group_knockout_shape {
return group;
}
let n = Arc::make_mut(&mut group);
if let Some(o) = opacity {
n.opacity = o;
}
if let Some(b) = slot.group_blend {
n.blend = b;
}
if let Some(k) = slot.group_knockout {
n.knockout = k;
}
n.isolate |= slot.group_isolate;
n.knockout_shape |= slot.group_knockout_shape;
group
}
/// Graph Data › Transpose row/column: categories become series and series categories.
pub(super) fn transpose(g: &mut GraphSpec) {
let cells = g.cells();
@@ -631,19 +701,33 @@ pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &
changed
}
/// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). Returns whether
/// the kept style changed.
/// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). A `change` that
/// sets the fill of legend labels marks it as set on them, so a black one stays black on dark pie wedges. Returns whether
/// the kept style or that mark changed.
fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle)) -> bool {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { return false };
let mut style = label_style(&spec.label_styles, role);
// The kept fill can already be the one `change` sets (black, the default): `change` sets the fill when it gives one
// of two different fills something else.
let sets_fill = role == Role::Legend
&& [Paint::None, Paint::solid(Color::BLACK)].into_iter().any(|fill| {
let mut probe = CharStyle { fill: fill.clone(), ..style.clone() };
change(&mut probe);
probe.fill != fill
});
change(&mut style);
let styles = &mut spec.label_styles;
let slot = match role {
Role::Value => &mut spec.label_styles.values,
Role::Category => &mut spec.label_styles.categories,
Role::Legend => &mut spec.label_styles.legend,
Role::Value => &mut styles.values,
Role::Category => &mut styles.categories,
Role::Legend => &mut styles.legend,
};
let changed = slot.as_ref() != Some(&style);
let mut changed = slot.as_ref() != Some(&style);
*slot = Some(style);
if sets_fill && !styles.legend_fill_set {
styles.legend_fill_set = true;
changed = true;
}
changed
}
@@ -872,12 +956,9 @@ fn run_paint_change(was: &Node, now: &Node, fill: bool) -> Option<(CharStyle, Ve
}
/// Does graph `g` pick the fill of its legend labels itself, white on a dark wedge and black on the others: a pie with
/// Legends in Wedges whose legend labels keep no fill of their own?
/// Legends in Wedges whose legend labels keep no fill of their own ([`GraphSpec::picks_legend_fill`])?
pub(super) fn picks_legend_fill(g: &GraphSpec) -> bool {
g.kind == GraphKind::Pie
&& g.legend
&& g.pie_legend_in_wedges
&& !g.label_styles.legend.as_ref().is_some_and(|st| st.fill != Paint::solid(Color::BLACK))
g.picks_legend_fill()
}
/// The graph labels among `roots` and inside them, for an edit that reaches graph labels without naming them.
+454 -2
View File
@@ -923,6 +923,32 @@ fn what_global_edit_gives_the_marks_of_another_series_group_survives_regeneratio
assert!(series(&n, 1).children().unwrap().iter().all(|m| m.appearance.fill_paint() == given));
}
/// With a whole series group picked and Global Edit on, the opacity and blend mode set on that group reach the other
/// series groups of the same form, and the graph stores them for those groups too.
#[test]
fn the_transparency_global_edit_gives_another_series_group_survives_regeneration() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
// Series without names draw no legend, so each series group holds only its columns, laid out like the other's.
let csv = ",,\nQ1,3,3\nQ2,5,5";
let made = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap();
let id = NodeId(made["id"].as_u64().unwrap());
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let (first, other) = (series(&n, 0).id, series(&n, 1).id);
s.execute("object.isolate", &json!({"id": id.0})).unwrap();
s.execute("select.set", &json!({"ids": [first.0]})).unwrap();
let r = s.execute("select.globalEdit", &json!({})).unwrap();
assert!(r["ids"].as_array().unwrap().contains(&json!(other.0)), "{r}");
s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 40, "blend": "multiply"})).unwrap();
let g = s.doc().unwrap().doc.node(other).unwrap().clone();
assert_eq!((g.opacity, g.blend), (0.4, BlendMode::Multiply), "Global Edit reaches the other group");
let kept = spec(&s, id).series_paints[1].clone();
assert_eq!((kept.group_opacity, kept.group_blend), (Some(0.4), Some(BlendMode::Multiply)));
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 1).0, (0.4, BlendMode::Multiply));
}
/// A blend mode set on the top fill or stroke row of one series mark is kept by the graph and drawn on every mark of
/// the series again; Normal forgets it.
#[test]
@@ -2210,8 +2236,8 @@ fn appearance_commands_given_a_series_group_edit_its_marks() {
s.execute("edit.undo", &json!({})).unwrap();
let (rect, blue) = blue_style(&mut s, "Blue", false);
let was = spec(&s, id).series_paints;
s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 50})).unwrap();
let was = spec(&s, id).series_paints;
s.execute("appearance.transfer", &json!({"source": rect.0, "target": group.0, "copy": true})).unwrap();
assert!(series_0_group(&s, id).1);
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().opacity, 1.0, "the appearance replaces the group's own opacity");
@@ -2433,10 +2459,10 @@ fn a_graphic_style_applied_to_a_series_group_styles_its_marks() {
let (mut s, id, marks) = stored_red_stroke();
let (group, _) = series_0_group(&s, id);
let (_, blue) = blue_style(&mut s, "Blue", false);
let was = spec(&s, id).series_paints;
let own = json!({"ids": [group.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "item": null});
s.execute("transparency.set", &own).unwrap();
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
let was = spec(&s, id).series_paints;
let g = s.doc().unwrap().doc.node(group).unwrap().clone();
assert!(g.isolate && g.knockout != Default::default() && g.blend != vectorcraft_color::BlendMode::Normal);
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0]})).unwrap();
@@ -2513,6 +2539,161 @@ fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() {
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
}
/// Series `index`'s group: its object opacity and blend mode, and those of each path directly inside it.
fn group_transparency(s: &Session, id: NodeId, index: u32) -> ((f32, BlendMode), Vec<(f32, BlendMode)>) {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let g = series(&n, index);
((g.opacity, g.blend), g.children().unwrap().iter().map(|m| (m.opacity, m.blend)).collect())
}
/// An object opacity and blend mode set on a selected series group are kept by the graph for the group: the series group
/// has them after the graph is drawn again, the graph's data reads them back unchanged after it is written to JSON, its
/// paths and the other series stay opaque and Normal, setting them again records no step, 100% and Normal forget them,
/// and undo takes them back.
#[test]
fn an_opacity_and_blend_mode_on_a_series_group_survive_regeneration() {
let (mut s, id, _, _) = column_marks();
let (group, _) = series_0_group(&s, id);
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 40, "blend": "multiply"})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.group_opacity, kept.group_blend), (Some(0.4), Some(BlendMode::Multiply)));
assert_eq!((kept.opacity, kept.blend), (None, None), "the paths keep their own");
let restored: GraphSpec = serde_json::from_value(serde_json::to_value(spec(&s, id)).unwrap()).unwrap();
assert_eq!(restored, spec(&s, id));
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
let normal = (1.0, BlendMode::Normal);
let (own, paths) = group_transparency(&s, id, 0);
assert_eq!(own, (0.4, BlendMode::Multiply));
assert!(!paths.is_empty() && paths.iter().all(|t| *t == normal), "{paths:?}");
let (own, paths) = group_transparency(&s, id, 1);
assert_eq!(own, normal);
assert!(paths.iter().all(|t| *t == normal), "{paths:?}");
let (group, _) = series_0_group(&s, id);
let undo = s.doc().unwrap().history.undo.len();
s.execute("object.setProps", &json!({"id": group.0, "opacity": 40, "blend": "multiply"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the values the group and the graph have already");
s.execute("object.setProps", &json!({"id": group.0, "opacity": 100, "blend": "normal"})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.group_opacity, kept.group_blend), (None, None));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"rows": [[2, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 0).0, normal);
for _ in 0..4 {
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(spec(&s, id).series_paints.is_empty(), "undo takes back the edit and what the graph stored");
}
/// Commands that clear a series group's own opacity and blend mode also remove what the graph keeps for it: Clear
/// Appearance on the group, a graphic style applied to it and Move Appearance onto it.
#[test]
fn clearing_a_series_groups_opacity_forgets_what_the_graph_keeps() {
let kept = |s: &Session, id: NodeId| {
let slot = spec(s, id).series_paints[0].clone();
(slot.group_opacity, slot.group_blend)
};
let faded = (Some(0.5), Some(BlendMode::Screen));
let (mut s, id, _, _) = column_marks();
let (rect, _) = blue_style(&mut s, "Blue", false);
let (group, _) = series_0_group(&s, id);
s.execute("object.setProps", &json!({"id": group.0, "opacity": 50, "blend": "screen"})).unwrap();
assert_eq!(kept(&s, id), faded);
let commands = [
("appearance.clear", json!({"ids": [group.0]})),
("graphicStyle.apply", json!({"name": "Blue", "ids": [group.0]})),
("appearance.transfer", json!({"source": rect.0, "target": group.0, "copy": true})),
];
for (cmd, params) in commands {
s.execute(cmd, &params).unwrap();
assert_eq!(kept(&s, id), (None, None), "{cmd}");
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal), "{cmd}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kept(&s, id), faded, "{cmd}");
}
}
/// Redefining a graphic style a series group is linked to clears the group's own opacity and blend mode, and removes
/// what the graph keeps for them.
#[test]
fn redefining_a_style_linked_to_a_series_group_forgets_its_kept_opacity() {
let (mut s, id, _, _) = column_marks();
let (group, _) = series_0_group(&s, id);
let (rect, _) = blue_style(&mut s, "Blue", false);
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
s.edit("Link", |d, _| {
let i = d.graphic_style_index("Blue").unwrap();
(d.graphic_styles[i].opacity, d.graphic_styles[i].blend) = (0.5, BlendMode::Screen);
let g = d.node_mut(group).unwrap();
g.appearance = style.appearance.clone().into();
(g.opacity, g.blend) = (0.5, BlendMode::Screen);
g.extras_mut().graphic_style = Some(style.id);
Ok(())
})
.unwrap();
s.execute("object.setProps", &json!({"id": group.0, "opacity": 50, "blend": "screen"})).unwrap();
let slot = spec(&s, id).series_paints[0].clone();
assert_eq!((slot.group_opacity, slot.group_blend), (Some(0.5), Some(BlendMode::Screen)));
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, Some(style.id), "still linked");
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00"})).unwrap();
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
let slot = spec(&s, id).series_paints.first().cloned().unwrap_or_default();
assert_eq!((slot.group_opacity, slot.group_blend), (None, None));
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal));
}
/// Isolate Blending, a knockout state and Knockout Shape set on a selected series group are kept by the graph for the
/// group, through the graph being drawn again; the other series' group stays as the graph draws it, and turning them off
/// forgets them.
#[test]
fn isolation_and_knockout_on_a_series_group_survive_regeneration() {
let (mut s, id, _, _) = column_marks();
let (group, _) = series_0_group(&s, id);
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("transparency.set", &json!({"isolate": true, "knockout": "off", "knockoutShape": true})).unwrap();
let slot = spec(&s, id).series_paints[0].clone();
assert_eq!((slot.group_isolate, slot.group_knockout, slot.group_knockout_shape), (true, Some(vectorcraft_doc::Knockout::Off), true));
assert_eq!((slot.group_opacity, slot.group_blend, slot.opacity, slot.blend), (None, None, None, None));
let undo = s.doc().unwrap().history.undo.len();
s.execute("object.setProps", &json!({"id": group.0, "isolate": true})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the values the group and the graph have already");
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let (g, other) = (series(&n, 0), series(&n, 1));
assert_eq!((g.isolate, g.knockout, g.knockout_shape), (true, vectorcraft_doc::Knockout::Off, true));
assert_eq!((other.isolate, other.knockout, other.knockout_shape), (false, vectorcraft_doc::Knockout::Neutral, false));
let (group, _) = series_0_group(&s, id);
s.execute("object.setProps", &json!({"id": group.0, "isolate": false, "knockout": "neutral", "knockoutShape": false})).unwrap();
assert!(spec(&s, id).series_paints.iter().all(|p| *p == vectorcraft_doc::SeriesPaint::default()), "nothing is kept");
}
/// Randomize Opacity and Sort Objects given a series group keep the opacity they give it for the group.
#[test]
fn randomize_and_sort_opacity_on_a_series_group_are_kept() {
let (mut s, id, _, _) = column_marks();
let (group, _) = series_0_group(&s, id);
s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [group.0], "min": 30, "max": 60, "seed": 7})).unwrap();
let given = s.doc().unwrap().doc.node(group).unwrap().opacity;
assert!(given < 1.0);
assert_eq!(spec(&s, id).series_paints[0].group_opacity, Some(given));
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 0).0, (given, BlendMode::Normal));
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let (first, second) = (series(&n, 0).id, series(&n, 1).id);
s.execute("object.setProps", &json!({"id": second.0, "opacity": 80})).unwrap();
s.execute("addon.arrange.sort", &json!({"ids": [first.0, second.0], "by": "x", "apply": "opacity", "order": "descending"})).unwrap();
let d = &s.doc().unwrap().doc;
let (a, b) = (d.node(first).unwrap().opacity, d.node(second).unwrap().opacity);
assert_eq!((a, b), (0.8, given), "the opacities trade places");
let kept = &spec(&s, id).series_paints;
assert_eq!((kept[0].group_opacity, kept.get(1).and_then(|k| k.group_opacity)), ((a < 1.0).then_some(a), (b < 1.0).then_some(b)));
}
/// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph.
#[test]
fn default_fill_and_stroke_on_a_series_mark_is_kept() {
@@ -5691,6 +5872,151 @@ fn formatting_one_label_keeps_that_kind_of_label() {
assert!(serde_json::to_value(GraphSpec::default()).unwrap().get("labelStyles").is_none());
}
/// Character and paragraph edits that resize a graph's labels leave the plot where it is when the graph is drawn
/// again, and a move or scale of the graph made after them is still followed.
#[test]
fn restyling_a_graphs_labels_leaves_the_plot_in_place() {
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
let redraw = |s: &mut Session, id: NodeId| s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
redraw(&mut s, id);
assert_eq!(spec(&s, id).rect, rect, "after a size change to every label");
let c = text_id(&s, id, "Axes", "Q2");
s.execute("text.setFormat", &json!({"ids": [c.0], "leftIndent": 20})).unwrap();
redraw(&mut s, id);
assert_eq!(spec(&s, id).rect, rect, "after an indent on the category labels");
let l = text_id(&s, id, "Legend", "2025");
s.execute("text.setStyle", &json!({"ids": [l.0], "size": 4})).unwrap();
redraw(&mut s, id);
assert_eq!(spec(&s, id).rect, rect, "after a smaller size on the legend labels");
// A move and a scale of the whole graph still carry the plot with them.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap();
redraw(&mut s, id);
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{moved:?}");
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
s.execute("object.scale", &json!({"sx": 200, "sy": 100, "origin": [moved.x0, moved.y0]})).unwrap();
redraw(&mut s, id);
let scaled = spec(&s, id).rect;
assert!((scaled.width() - 2.0 * rect.width()).abs() < 1e-6 && (scaled.height() - rect.height()).abs() < 1e-6, "{scaled:?}");
assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}");
}
/// Moving one label of a graph on its own leaves the plot where it is when the graph is drawn again.
#[test]
fn moving_one_label_leaves_the_plot_in_place() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
for (grp, text) in [("Legend", "2025"), ("Axes", "Q2")] {
let l = text_id(&s, id, grp, text);
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
s.execute("object.move", &json!({"dx": 120, "dy": 60})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
assert_eq!(spec(&s, id).rect, rect, "after moving {text}");
}
}
/// Label edits leave the plot in place in graphs whose legend swatches follow the size of the labels at the next
/// drawing: a legend across the top, a legend after a right value axis, and legend labels of several lines. A move of
/// the graph made after them is still followed.
#[test]
fn restyling_the_labels_of_a_graph_whose_legend_follows_them_leaves_the_plot_in_place() {
let csv = ",North|East|Coast,South|West,Inland|Hills|Lakes|Plains\nQ1,3,2,4\nQ2,5,4,1\nQ3,-1,6,2";
for options in [json!({"legendAcrossTop": true}), json!({"valueAxis": "right"}), json!({"valueAxis": "both"}), json!({})] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setType", &options).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let rect = spec(&s, id).rect;
for size in [16, 5] {
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": size})).unwrap();
for _ in 0..2 {
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
assert_eq!(spec(&s, id).rect, rect, "{options}: labels at {size} pt");
}
}
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 30, "dy": 20})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 20.0)).abs() < 1e-6, "{options}: {moved:?}");
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{options}: {moved:?}");
}
}
/// Outlining a graph's labels leaves the plot where it is when the graph is drawn again, and a move of the graph made
/// before them is still followed.
#[test]
fn outlining_a_graphs_labels_leaves_the_plot_in_place() {
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q2").0, text_id(&s, id, "Legend", "2025").0]})).unwrap();
s.execute("type.createOutlines", &json!({})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
assert_eq!(spec(&s, id).rect, rect, "after outlining labels");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 30, "dy": 15})).unwrap();
s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q1").0, text_id(&s, id, "Legend", "2024").0]})).unwrap();
s.execute("type.createOutlines", &json!({})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 15.0)).abs() < 1e-6, "{moved:?}");
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
}
/// A graph whose kept bounds of its art without type have no width follows a move with the bounds of all of its art.
#[test]
fn a_graph_whose_art_without_type_kept_no_width_still_follows_a_move() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
let mut flat = spec(&s, id);
let art = flat.placed_art.unwrap();
flat.placed_art = Some(vectorcraft_geom::Rect::new(art.x0, art.y0, art.x0, art.y1));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(flat));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}");
}
/// A graph saved before it kept the bounds of its art without type follows a move made since with its old bounds.
#[test]
fn a_graph_saved_with_only_its_whole_bounds_still_follows_a_move() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
let mut old = serde_json::to_value(spec(&s, id)).unwrap();
old.as_object_mut().unwrap().remove("placedArt");
let old: GraphSpec = serde_json::from_value(old).unwrap();
assert_eq!(old.placed_art, None);
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}");
assert!(spec(&s, id).placed_art.is_some(), "the next drawing keeps the bounds of the art without type");
}
/// Each Axes and Legend text after the graph is drawn again, with its object rows (fill or stroke, color, opacity, and
/// for a stroke its weight) and its object opacity.
type RowLooks = Vec<(bool, String, f32, f64)>;
@@ -6361,6 +6687,93 @@ fn pie_names_and_wedge_labels_keep_their_style() {
assert_eq!(fills, ["#00ff00", "#00ff00"], "the kept fill, also on the dark wedge");
}
/// On a pie with Legends in Wedges, a black fill given to the white legend label on the dark wedge is kept for every
/// legend label: the graph draws it black on the dark wedge again, also after a native save and open.
#[test]
fn a_black_fill_set_on_a_wedge_legend_label_stays_black_on_dark_wedges() {
let cases = [("paint.setFill", json!({"color": "#000000"})), ("text.setStyle", json!({"fill": "#000000"})), ("edit.colors.invert", json!({}))];
every_case(cases, |(cmd, params)| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = make(&mut s, "pie", ",a,b\nP1,1,2");
s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap();
let legend_fill = |s: &Session, text: &str| {
let NodeKind::Text(t) = label_node(s, id, "Legend", text).kind else { panic!("{text} is not type") };
t.runs[0].style.fill.color().map(|c| c.to_hex()).unwrap_or_default()
};
assert_eq!(legend_fill(&s, "a"), "#ffffff", "white on the black wedge");
let mut p = params.clone();
p["ids"] = json!([text_id(&s, id, "Legend", "a").0]);
s.execute(cmd, &p).unwrap();
assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(!spec(&s, id).label_styles.legend_fill_set, "{cmd}: undone");
assert_eq!(legend_fill(&s, "a"), "#ffffff", "{cmd}: white again after the undo");
s.execute("edit.redo", &json!({})).unwrap();
assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}: redone");
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2]]})).unwrap();
assert_eq!((legend_fill(&s, "a"), legend_fill(&s, "b")), ("#000000".into(), "#000000".into()), "{cmd}: black on both wedges");
let dir = vectorcraft_testkit::TempDir::new("graph-wedge-legend");
let path = dir.join("pie.vectorcraft");
s.execute("document.save", &json!({"path": path})).unwrap();
s.execute("document.open", &json!({"path": path})).unwrap();
assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}: kept through save and open");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "rows": [[2, 1]]})).unwrap();
assert_eq!(legend_fill(&s, "a"), "#000000", "{cmd}: still black after open");
});
}
/// A size given to the legend labels of a pie with Legends in Wedges keeps the default black fill with it. A color mode
/// change leaves that fill black, so the legend label on the dark wedge is still drawn white. A legend fill that is not
/// black, in a file saved without the mark, is marked as set by the change.
#[test]
fn a_color_mode_change_keeps_the_default_wedge_legend_fill() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = make(&mut s, "pie", ",a,b\nP1,1,2");
s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": 11})).unwrap();
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
let styles = spec(&s, id).label_styles;
assert!(!styles.legend_fill_set && !styles.legend_fill_is_own(), "{styles:?}");
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2]]})).unwrap();
let NodeKind::Text(t) = label_node(&s, id, "Legend", "a").kind else { panic!("a is not type") };
assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()), Some("#ffffff".into()), "white on the black wedge");
let red = Paint::solid(vectorcraft_color::Color::from_hex("#ff0000").unwrap());
let styles = vectorcraft_doc::LabelStyles { legend: Some(vectorcraft_doc::CharStyle { fill: red, ..Default::default() }), ..Default::default() };
assert!(!styles.legend_fill_set && styles.legend_fill_is_own(), "{styles:?}");
s.edit("legacy", |d, _| {
d.node_mut(id).unwrap().extras_mut().graph.as_deref_mut().unwrap().label_styles = styles;
Ok(())
})
.unwrap();
s.execute("file.documentColorMode", &json!({"mode": "rgb"})).unwrap();
assert!(spec(&s, id).label_styles.legend_fill_set, "the converted red is still the labels' own");
}
/// The default black legend fill of a graph that keeps its legend beside the marks stays the default through a color
/// mode change, so turning on Legends in Wedges later still draws the labels on dark wedges white.
#[test]
fn a_color_mode_change_keeps_the_default_legend_fill_of_other_graphs() {
// A pie made here keeps its legend beside the pies.
for kind in ["column", "pie"] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = make(&mut s, kind, ",a,b\nP1,1,2");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": 11})).unwrap();
let black = Paint::solid(vectorcraft_color::Color::BLACK);
let before = spec(&s, id).label_styles;
assert_eq!(before.legend.as_ref().map(|st| st.fill.clone()), Some(black.clone()), "{kind}: {before:?}");
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
let after = spec(&s, id).label_styles;
assert_eq!(after.legend.as_ref().map(|st| st.fill.clone()), Some(black), "{kind}: {after:?}");
assert!(!after.legend_fill_set && !after.legend_fill_is_own(), "{kind}: still the default: {after:?}");
}
}
#[test]
fn labels_are_told_apart_by_where_they_come_not_by_their_text() {
let mut s = Session::new();
@@ -6848,3 +7261,42 @@ fn a_graph_opened_from_ai_keeps_its_data_for_editing() {
assert!(notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}");
}
}
/// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own
/// leaves the plot where it is at the first redraw.
#[test]
fn a_graph_opened_from_ai_measures_moves_without_its_labels() {
let graph = "%_Gs\n%_100 200 300 100 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\
%_1 () Ga\n%_0 13 0 0 0 0 0 () GA\n%_2 () Ga\n%_0 14 0 0 0 0 0 () GA\n%_4 () Ga\n%_0 14 0 0 0 0 0 () GA\n\
%_2 2 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 5 Gc GC\n\
u\nu\n0.6 0 1 0 k\n110 100 m\n110 150 L\n130 150 L\n130 100 L\nf\nU\n%_2 1 0 0 Go\n\
u\n0 0 0 1 K\n100 200 m\n100 100 L\n300 100 L\nS\nU\n\
0 To\n1 0 0 1 100 220 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Sales) Tx\nTO\nU\n%_GS\n";
let text = format!(
"%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 400 400\n%AI5_FileFormat 3\n%AI3_Cropmarks: 0 0 400 400\n%%EndComments\n\
%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Graph) Ln\n0 A\n{graph}LB\n\
%AI5_EndLayer--\n%%PageTrailer\n%%Trailer\n%%EOF\n"
);
let dir = vectorcraft_testkit::temp_dir("graph-ai-label");
let path = dir.join("graph.ai");
std::fs::write(&path, text).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"path": path})).unwrap();
let (mut graphs, mut labels) = (vec![], vec![]);
s.doc().unwrap().doc.walk(|n| {
if n.extras().graph.is_some() {
graphs.push(n.id);
}
if matches!(&n.kind, NodeKind::Text(t) if t.plain_text() == "Sales") {
labels.push(n.id);
}
});
assert_eq!((graphs.len(), labels.len()), (1, 1));
let (id, label) = (graphs[0], labels[0]);
let before = spec(&s, id);
assert!(before.placed_art.is_some());
s.execute("select.set", &json!({"ids": [label.0]})).unwrap();
s.execute("object.move", &json!({"dx": 80, "dy": -40})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap();
assert_eq!(spec(&s, id).rect, before.rect);
}
+30 -4
View File
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Links",
[],
None,
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded)|size (the linked file's size in bytes as Link Info shows it, smallest first; rows without one, embedded images and missing files whose size is not kept, last; equal sizes by name); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
has_doc,
list
),
@@ -2316,6 +2316,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)
@@ -2382,8 +2392,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.
@@ -2431,6 +2447,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);
@@ -2451,12 +2472,17 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
rows.push(row);
}
let text = |r: &Value, k: &str| r[k].as_str().unwrap_or_default().to_lowercase();
match str_param(p, "sort") {
None => {}
match sort {
Some("name") => rows.sort_by_cached_key(|r| text(r, "name")),
Some("kind") => rows.sort_by_cached_key(|r| (text(r, "format"), text(r, "name"))),
Some("status") => rows.sort_by_cached_key(|r| (status_rank(r["status"].as_str().unwrap_or_default()), text(r, "name"))),
Some(x) => return Err(bad(C, format!("sort `{x}`: name, kind or status"))),
// Smallest file first; rows without a file size (embedded images, a missing file whose
// size the document does not keep) come last; equal sizes by name.
Some("size") => rows.sort_by_cached_key(|r| {
let size = r["id"].as_u64().and_then(|id| sizes.get(&id).copied());
(size.is_none(), size.unwrap_or(0), text(r, "name"))
}),
_ => {}
}
let count = |k: &str| counts.get(k).copied().unwrap_or(0);
Ok(json!({ "links": rows, "missing": count("missing"), "modified": count("modified"), "embedded": count("embedded") }))
+1 -1
View File
@@ -251,7 +251,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Object Properties",
[],
None,
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
has_doc,
set_props
),
+11 -3
View File
@@ -68,8 +68,14 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
// A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label
// for its kind of label, so a value a mark or label already has still replaces the one another left on the graph.
let transparency = opacity.is_some() || blend.is_some();
let stores =
|| transparency && (crate::cmd::graph::series_object_opacity_differs(d, &ids) || crate::cmd::graph::label_object_opacity_differs(d, &ids));
// A series group's isolation, knockout and knockout shape are kept for the group alone.
let group_only = !transparency && ["isolate", "knockout", "knockoutShape"].iter().any(|k| p.get(*k).is_some());
let kept = if group_only { crate::cmd::graph::series_groups_among(d, &ids) } else { ids.clone() };
let stores = || {
(transparency || group_only)
&& (crate::cmd::graph::series_object_opacity_differs(d, &kept)
|| transparency && crate::cmd::graph::label_object_opacity_differs(d, &ids))
};
if ids.iter().all(|id| d.node(*id).is_some_and(has_values)) && !stores() {
// Hidden or locked objects can't stay selected.
if hides {
@@ -123,8 +129,10 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
});
}
}
if transparency || group_only {
crate::cmd::graph::capture_series_object_opacity(d, &kept);
}
if transparency {
crate::cmd::graph::capture_series_object_opacity(d, &ids);
crate::cmd::graph::capture_label_object_opacity(d, &ids);
}
// Hidden or locked objects can't stay selected.
+1 -1
View File
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transparency",
["Window", "Transparency"],
None,
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
has_doc,
transparency
),
+55 -39
View File
@@ -5,7 +5,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Composer, JustificationOptions, NodeKind, Scaling, SingleWordJustify, TextRun};
use vectorcraft_geom::{Rect, Vec2};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, point_indices, switch_or};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, switch_or};
use crate::{Clipboard, EngineError};
pub fn specs() -> Vec<CommandSpec> {
@@ -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
),
@@ -137,19 +137,16 @@ pub(crate) fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result<Vec
return artboard_indices(d, p, cmd);
}
if let Some(recorded) = p.get("selectedArtboards") {
return artboard_indices(d, &json!({ "indices": recorded }), cmd);
return listed_artboards(d, recorded, "selectedArtboards", cmd);
}
let mut picked: Vec<u64> = t["selected"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_u64)
.filter(|i| usize::try_from(*i).is_ok_and(|i| i < d.artboards.len()))
.collect();
let mut picked: Vec<usize> =
t["selected"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(index).filter(|i| *i < d.artboards.len()).collect();
if picked.is_empty() {
picked.push(t["active"].as_u64().unwrap_or(0));
picked.push(on_board(d, t["active"].as_u64().map_or(0, index))?);
}
artboard_indices(d, &json!({ "indices": picked }), cmd)
picked.sort_unstable();
picked.dedup();
Ok(picked)
}
/// Rename Artboards: one artboard takes the name, and several take it numbered in artboard order, in
@@ -221,23 +218,51 @@ fn artboard_switch_orientation(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "switched": switched }))
}
/// The one artboard `cmd` acts on: `index`, an artboard of `d`, with the errors of
/// [`artboard_indices`] (`missing index`, `no such artboard`).
/// The one artboard `cmd` acts on: `index`, an artboard of `d`. Left out or null, it is
/// `missing index`; a value that is not a whole number is "`index` must be a whole number"; a
/// whole number past the last artboard is `no such artboard`.
pub(crate) fn artboard_index(d: &vectorcraft_doc::Document, p: &Value, cmd: &str) -> Result<usize> {
let i = p.get("index").ok_or_else(|| bad(cmd, "missing index"))?;
artboard_indices(d, &json!({ "index": i }), cmd)?.into_iter().next().ok_or_else(|| EngineError::Other("no such artboard".into()))
artboard_at(d, p, "index", cmd)?.ok_or_else(|| bad(cmd, "missing index"))
}
/// The artboard of `d` that `key` of `p` names, or `None` when `p` leaves it out or gives null. A
/// value that is not a whole number is "`{key}` must be a whole number", and a whole number past the
/// last artboard is `no such artboard`.
pub(crate) fn artboard_at(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: &str) -> Result<Option<usize>> {
super::index_opt(p, key, cmd)?.map(|i| on_board(d, i)).transpose()
}
/// `i` when it is an artboard of `d`, else `no such artboard`.
pub(crate) fn on_board(d: &vectorcraft_doc::Document, i: usize) -> Result<usize> {
match i < d.artboards.len() {
true => Ok(i),
false => Err(EngineError::Other("no such artboard".into())),
}
}
/// The artboards `cmd` acts on: `indices` (several), else `index` (one), each an artboard of `d`,
/// in order and once each.
/// in order and once each. `indices` is read as [`listed_artboards`] reads it, and `index` as
/// [`artboard_index`] reads it.
pub(crate) fn artboard_indices(d: &vectorcraft_doc::Document, p: &Value, cmd: &str) -> Result<Vec<usize>> {
let listed = match (p.get("indices"), p.get("index")) {
(Some(v), _) => point_indices(v),
(None, Some(i)) => point_indices(&json!([i])),
(None, None) => return Err(bad(cmd, "missing index")),
};
let mut indices =
listed.filter(|v| !v.is_empty() && v.iter().all(|i| *i < d.artboards.len())).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
match p.get("indices") {
Some(v) => listed_artboards(d, v, "indices", cmd),
None => Ok(vec![artboard_index(d, p, cmd)?]),
}
}
/// `v`, the value of `key`, as artboards of `d`, in order and once each. A value that is not a list
/// is "`{key}` must be a list of artboard indices", an empty list is "`{key}` must be a non-empty
/// list of artboard indices", and a list with an entry that is not a whole number is "`{key}` must
/// contain whole numbers"; a whole number past the last artboard is `no such artboard`. Every entry
/// is checked for its form before any is checked against the artboards.
fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
let entries = v.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be a list of artboard indices")))?;
if entries.is_empty() {
return Err(bad(cmd, format!("`{key}` must be a non-empty list of artboard indices")));
}
let listed = entries.iter().map(Value::as_u64).collect::<Option<Vec<u64>>>();
let listed = listed.ok_or_else(|| bad(cmd, format!("`{key}` must contain whole numbers")))?;
let mut indices = listed.into_iter().map(|i| on_board(d, index(i))).collect::<Result<Vec<usize>>>()?;
indices.sort_unstable();
indices.dedup();
Ok(indices)
@@ -1310,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)? {
@@ -1356,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();
@@ -1382,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;
}
}
@@ -1472,7 +1488,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
let tab = vectorcraft_doc::TabStop { position: x, align: vectorcraft_doc::TabAlign::Left, leader: String::new(), align_on: '.' };
style.tabs.insert(i, tab);
}
for part in story_para.parts.iter().filter(|q| (std::ptr::eq(*q, para) || q.bytes.is_empty()) && !is_held(q.frame)) {
for part in story_para.parts.iter().filter(|q| std::ptr::eq(*q, para) || q.bytes.is_empty()) {
if let Some((stops, _)) = frame_edits.get_mut(part.frame) {
stops.push((part.index, style.clone()));
}
+1 -1
View File
@@ -183,7 +183,7 @@ pub(crate) fn accepted_keys(doc: &'static str) -> Option<Vec<&'static str>> {
/// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands
/// its `…` entries name)?
pub(crate) fn takes_key(doc: &'static str, key: &str) -> bool {
pub fn takes_key(doc: &'static str, key: &str) -> bool {
doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key))
}
+122 -8
View File
@@ -7,7 +7,8 @@
//! fields; `perspective.grid.preset` applies one, `perspective.presets.*` manage them.
//!
//! View options (Lock Grid, Lock Station Point, Snap to Grid, Show Rulers) are view state on
//! the grid: they toggle without an undo step, as Show Grid does.
//! the grid: they toggle without an undo step, as Show Grid does. So is the point Automatic Plane
//! Positioning holds the active plane through (`perspective.plane.infer`).
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -15,12 +16,15 @@ use vectorcraft_doc::{Document, NodeId};
use vectorcraft_geom::{Point, Rect, Vec2};
use vectorcraft_tools::distort::perspective::Plane;
use vectorcraft_tools::distort::perspective::define::{BUILTINS, LETTER, first_artboard, is_builtin};
use vectorcraft_tools::distort::perspective::infer::{HIT_PX, InferSource};
use vectorcraft_tools::distort::perspective::widget::{WidgetCorner, WidgetPlace};
use vectorcraft_tools::distort::perspective::{GridDefinition, PerspectiveGrid};
use vectorcraft_tools::distort::perspective::{GridDefinition, MAX_DEPTH, PerspectiveGrid};
use vectorcraft_tools::{PointerEvent, PointerKind, ToolKey};
use super::distortcmds::{grid_kept, grid_of, silent, store_grid};
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, switch_or, unique_name};
use super::{
CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, number_or, str_param, switch_or, unique_name,
};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -92,10 +96,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Perspective Grid Options",
[],
None,
"{show?: bool, position?: topLeft|topRight|bottomLeft|bottomRight} the Plane Switching Widget: shown or not, and the corner of the document window it stays in (kept with the preferences; no params reads them) → {show, position}",
"{show?: bool, position?: topLeft|topRight|bottomLeft|bottomRight, anchorPoint?: bool, gridlineIntersection?: bool} the Plane Switching Widget: shown or not, and the corner of the document window it stays in; Automatic Plane Positioning: whether it takes a point from an anchor point of art in perspective and from a gridline intersection (both on by default; see perspective.plane.infer). Kept with the preferences; no params reads them → {show, position, anchorPoint, gridlineIntersection}",
always,
widget_options
),
cmd!(
"perspective.plane.infer",
"Automatic Plane Positioning",
[],
None,
"{at?: [x, y], tolerance?: pt around `at` (default 6), clear?: bool} with `at` on an anchor point of shown art in perspective, or on a gridline intersection of a plane that shows, the active plane moves through that point for now and the other planes hide (the Perspective Selection tool: Shift held over one with no button down). An anchor point within reach wins over an intersection, and perspective.widget.options turns either off. Making another plane active (perspective.plane.set) brings that plane through the same point. The plane goes back to its place when an object is drawn on it or attached to it (perspective.draw, perspective.attach, an object brought into perspective by perspective.move or perspective.transform), when a plane is moved (perspective.plane.move, perspective.plane.matchObject), when the grid hides or no plane is active, when the file is opened again, and with `clear` (Escape with the Perspective Selection tool). View state: not an undo step; no params reads it → {active, plane, offset: where the active plane is, point?: [x, y, z] in the grid's frame, source?: anchor|gridline (what `at` found; absent when nothing was within reach)}",
has_doc,
plane_infer
),
cmd!(
"perspective.grid.lock",
"Lock Grid",
@@ -259,21 +272,32 @@ pub(crate) fn grid_preset(s: &mut Session, p: &Value) -> Result<Value> {
let old = grid_of(&s.doc()?.doc);
let ab = s.doc()?.doc.artboards.first().map(|a| a.rect).ok_or_else(|| EngineError::Other("no artboard".into()))?;
let g = s.perspective_preset_grid(&name, ab).ok_or_else(|| bad(C, format!("no perspective grid preset named `{name}`")))?;
// The objects stay attached and the view options stay as they were.
let g = PerspectiveGrid { attached: old.attached, locked: old.locked, lock_station: old.lock_station, snap: old.snap, rulers: old.rulers, ..g };
// The objects stay attached and the view options stay as they were, and so does a plane held
// by Automatic Plane Positioning while the new grid can hold it.
let mut g = PerspectiveGrid {
attached: old.attached,
locked: old.locked,
lock_station: old.lock_station,
snap: old.snap,
rulers: old.rulers,
inferred: old.inferred,
..g
};
g.keep_positioning_valid();
// When the document holds this grid already, apart from whether it shows and its active plane,
// the preset only sets those two, without an undo step (as perspective.grid.show and
// perspective.plane.set do).
let view = PerspectiveGrid { visible: old.visible, plane: old.plane, ..g.clone() };
let view = PerspectiveGrid { visible: old.visible, plane: old.plane, inferred: old.inferred, ..g.clone() };
if !grid_kept(&s.doc()?.doc, &view) {
s.edit("Perspective Grid Preset", |d, _| {
store_grid(d, &g);
Ok(())
})?;
} else if (old.visible, old.plane) != (g.visible, g.plane) {
} else if (old.visible, old.plane, old.inferred) != (g.visible, g.plane, g.inferred) {
silent(s, |cur| {
cur.visible = g.visible;
cur.plane = g.plane;
cur.inferred = g.inferred;
})?;
}
Ok(g.definition_json())
@@ -460,10 +484,100 @@ fn widget_options(s: &mut Session, p: &Value) -> Result<Value> {
o.position =
v.as_str().and_then(WidgetCorner::parse).ok_or_else(|| bad(C, "position must be topLeft, topRight, bottomLeft or bottomRight"))?;
}
if let Some(v) = p.get("anchorPoint") {
o.anchor_point = v.as_bool().ok_or_else(|| bad(C, "anchorPoint must be true or false"))?;
}
if let Some(v) = p.get("gridlineIntersection") {
o.gridline_intersection = v.as_bool().ok_or_else(|| bad(C, "gridlineIntersection must be true or false"))?;
}
s.prefs.perspective_widget = o;
Ok(json!(o))
}
/// What `perspective.plane.infer` reports for `g`.
fn infer_info(g: &PerspectiveGrid, source: Option<InferSource>) -> Value {
let active = g.inferred.is_some() && g.plane != Plane::None;
let mut v = json!({ "active": active, "plane": g.plane.id(), "offset": g.offset(g.plane) });
if let Some(at) = g.inferred.filter(|_| active) {
v["point"] = json!(at);
}
if let Some(source) = source {
v["source"] = json!(source.id());
}
v
}
fn plane_infer(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "perspective.plane.infer";
let clear = switch_or(p, "clear", false, C)?;
let at = match p.get("at") {
None | Some(Value::Null) => None,
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be [x, y]"))?),
};
let tol = number_or(p, "tolerance", HIT_PX, C)?;
if !(tol.is_finite() && (0.0..=MAX_DEPTH).contains(&tol)) {
return Err(bad(C, "tolerance must be 0 or more"));
}
if clear && at.is_some() {
return Err(bad(C, "give `at` or `clear`, not both"));
}
let doc = &s.doc()?.doc;
let g = PerspectiveGrid::current(doc);
let mut source = None;
let next = match at {
_ if clear => None,
None => g.inferred,
Some(at) => {
if !g.visible {
return Err(EngineError::Other("the perspective grid is hidden".into()));
}
if g.plane == Plane::None {
return Err(EngineError::Other("no active perspective plane".into()));
}
let targets = s.prefs.perspective_widget.targets();
if !targets.any() {
return Err(EngineError::Other(
"Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options)".into(),
));
}
match g.infer_at(doc, at, tol, targets) {
Some((found, point)) => {
source = Some(found);
Some(point)
}
None => g.inferred,
}
}
};
if next == g.inferred {
return Ok(infer_info(&g, source));
}
// A plane through the point stays in front of the viewer.
if next.is_some() {
PerspectiveGrid { inferred: next, ..g }.validate().map_err(|e| bad(C, e))?;
}
let g = silent(s, |g| g.inferred = next)?;
Ok(infer_info(&g, source))
}
/// An object was drawn on, or attached to, `plane`: when Automatic Plane Positioning holds that
/// plane, it goes back to its place as view state, not an undo step (a plane it doesn't hold
/// leaves it as it is). In a drag that happens once the drag is committed
/// ([`Session::commit_interaction`]), so the plane stays put while the object is drawn.
pub(crate) fn plane_positioning_used(s: &mut Session, plane: Plane) -> Result<()> {
let st = s.doc_mut()?;
let g = grid_of(&st.doc);
if g.inferred.is_none() || g.plane != plane {
return Ok(());
}
if let Some(it) = &mut st.interaction {
it.plane_placed = true;
return Ok(());
}
silent(s, |g| g.inferred = None)?;
Ok(())
}
impl Session {
/// The Plane Switching Widget's part of a pointer event: a press on it picks the plane (its
/// drag and release go nowhere); None when the event isn't the widget's.
+40 -4
View File
@@ -20,7 +20,7 @@ use std::sync::Arc;
use vectorcraft_doc::links::hash_bytes;
use vectorcraft_doc::placed_document::{PREVIEW_MAX, PREVIEW_PX_PER_PT, key_for};
use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, NodeKind, PageBox, PlacedDocument, PlacementOptions};
use vectorcraft_doc::{ColorMode, Document, ImageBlob, LinkInfo, Node, NodeKind, PageBox, PlacedDocument, PlacementOptions};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_pdf::CropTo;
@@ -221,22 +221,57 @@ pub(crate) struct Source {
/// What is shown, in the file's coordinates: the artboard, the page's box or the art's bounds.
pub frame: Rect,
pub warnings: Vec<String>,
/// The colour mode the file's art was read in (a PDF page painted mostly in CMYK reads in CMYK).
pub color_mode: ColorMode,
}
/// The VectorCraft document `name` (`bytes`, from `path` when there is one) read for showing
/// artboard `page`, or the PDF or `.ai` file for showing page `page` clipped to its box
/// `page_box` (its art's bounds when `bounding`).
pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bounding: bool, page_box: PageBox, cmd: &str) -> Result<Source> {
read_source(name, bytes, None, path, (page, bounding, page_box), cmd)
}
/// [`source`] of the file whose bytes `bytes` holds, kept by the blob without a copy of its own:
/// several pages of one file read this way share one copy of it.
pub(crate) fn shared_source(
name: &str,
bytes: &Arc<Vec<u8>>,
path: Option<&str>,
page: u32,
bounding: bool,
page_box: PageBox,
cmd: &str,
) -> Result<Source> {
read_source(name, bytes, Some(bytes), path, (page, bounding, page_box), cmd)
}
/// [`source`], the blob keeping `shared` when given (else a copy of `bytes`); `shown` is the page
/// (or artboard), whether the art's bounds are shown, and the page's box.
fn read_source(
name: &str,
bytes: &[u8],
shared: Option<&Arc<Vec<u8>>>,
path: Option<&str>,
shown: (u32, bool, PageBox),
cmd: &str,
) -> Result<Source> {
let (page, bounding, page_box) = shown;
// The same document placed the same way is read once (placing it again is free).
let key = key_for(&hash_bytes(bytes), page, bounding, page_box);
// Resolving its links depends on where the file is and on what the caller may read, so a hit
// needs the same path, and nothing is shared with or from a confined (automation) caller.
let confined = crate::file_access::current().is_some();
if !confined && let Some((_, s)) = lock_memo().iter().find(|(at, s)| s.key == key && at.as_deref() == path).cloned() {
if !confined && let Some((_, mut s)) = lock_memo().iter().find(|(at, s)| s.key == key && at.as_deref() == path).cloned() {
// The same bytes: the copy given is kept instead, so the pages that share it go on sharing.
if let Some(b) = shared {
s.blob.bytes = b.clone();
}
return Ok(s);
}
let a = document_art(name, bytes, path, page, bounding, page_box, cmd)?;
let mut blob = ImageBlob::new(mime(name, bytes), bytes.to_vec());
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
let shown = PlacedDocument {
link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) },
key: key.clone(),
@@ -249,9 +284,10 @@ pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bo
};
let art = group(a.nodes, a.clip);
blob.proxy = preview(&a.doc, &art, a.frame).map(Arc::new);
let color_mode = a.doc.color_mode;
// Drawing it needn't read it again.
vectorcraft_doc::placed_document::prime(&shown, blob.bytes.clone(), (a.doc, art, a.frame));
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings };
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode };
if !confined {
let mut m = lock_memo();
if m.len() >= MEMO_SIZE {
+175 -35
View File
@@ -101,12 +101,30 @@ const FILE_WORDS: &[&str] = &[
"clipboard",
];
/// Param keys that name a file or a folder.
const FILE_KEYS: &[&str] =
&["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url", "diffPath"];
/// Param keys that name a file or a folder, each by its whole name, the folder preferences
/// `prefs.set {values}` takes included: a command that adds a key naming one adds it here. A key
/// that only ends like one (`alignToPath`, `linksFolder`, `sortPaths`) names none, nor do `folders`
/// (how an export groups its files) and `url` (a web link).
const FILE_KEYS: &[&str] = &[
"path",
"paths",
"file",
"files",
"folder",
"dir",
"directory",
"destinationFolder",
"sourceFolder",
"diffPath",
"fontsFolder",
"pluginsFolder",
"recoveryFolder",
"templatesFolder",
];
/// The keys in [`FILE_KEYS`] that name a folder.
const FOLDER_KEYS: &[&str] = &["folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder"];
const FOLDER_KEYS: &[&str] =
&["folder", "dir", "directory", "destinationFolder", "sourceFolder", "fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"];
/// What a param key that names a place on disk names there.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -132,7 +150,83 @@ pub fn key_location(key: &str) -> Option<Location> {
/// What `key` names on disk in command `spec`: [`key_location`], or `None` when [`NOT_FILES`]
/// names it for `spec` (it names part of the document there).
pub fn location_in(spec: &CommandSpec, key: &str) -> Option<Location> {
if NOT_FILES.contains(&(spec.id, key)) { None } else { key_location(key) }
ParamsPlace::top(Some(spec)).member(key, None).1
}
/// A place in the params of a command. What a key names on disk depends on the command and on the
/// keys above it: [`key_location`], less a key [`NOT_FILES`] names for the command at the top of its
/// params and one at the end of a [`NESTED_NOT_FILES`] key list. A walk of params starts at
/// [`ParamsPlace::top`] and goes down with [`ParamsPlace::member`] and [`ParamsPlace::item`].
#[derive(Clone, Copy, Debug)]
pub struct ParamsPlace {
/// The command whose params these are; `None` for a command that isn't known.
command: Option<&'static str>,
/// Whether this is the top of the params.
top: bool,
/// The keys of a [`NESTED_NOT_FILES`] list still to follow below this place.
trail: Option<&'static [&'static str]>,
}
impl ParamsPlace {
/// The top of the params of `spec`, or of a command that isn't known (`None`), where every key in
/// [`FILE_KEYS`] names a file or a folder.
pub fn top(spec: Option<&CommandSpec>) -> ParamsPlace {
ParamsPlace { command: spec.map(|s| s.id), top: true, trail: None }
}
/// The top of the params of the command with id `id` ([`ParamsPlace::top`]).
pub fn of(id: &str) -> ParamsPlace {
ParamsPlace::top(super::find_command(id))
}
/// The top of the params of the command that object `fields` calls, when it is a call
/// (`{command | id: <command id>, params}`, as a `command.batch` step or a control request is):
/// the place of its `params` member ([`ParamsPlace::member`]).
pub fn carried(fields: &serde_json::Map<String, Value>) -> Option<ParamsPlace> {
if !fields.contains_key("params") {
return None;
}
let id = fields.get("command").or_else(|| fields.get("id")).and_then(Value::as_str)?;
super::find_command(id).map(|spec| ParamsPlace::top(Some(spec)))
}
/// The top of the params of the command that array `items` records, when it is a recorded step
/// (`[command id, params]`): the place of its item 1 ([`ParamsPlace::item`]).
pub fn step(items: &[Value]) -> Option<ParamsPlace> {
match items {
[Value::String(id), Value::Object(_)] => super::find_command(id).map(|spec| ParamsPlace::top(Some(spec))),
_ => None,
}
}
/// The place of member `key` of an object here, with what `key` names on disk there. `carried` is
/// [`ParamsPlace::carried`] of that object: its `params` member is then the top of that command's
/// params, and names no file.
pub fn member(self, key: &str, carried: Option<ParamsPlace>) -> (ParamsPlace, Option<Location>) {
if key == "params"
&& let Some(inner) = carried
{
return (inner, None);
}
let rest = if self.top {
let id = self.command;
NESTED_NOT_FILES.iter().find(|(c, keys)| Some(*c) == id && keys.first() == Some(&key)).map(|(_, keys)| keys.get(1..).unwrap_or_default())
} else {
self.trail.filter(|keys| keys.first() == Some(&key)).map(|keys| keys.get(1..).unwrap_or_default())
};
let document = (self.top && self.command.is_some_and(|id| NOT_FILES.contains(&(id, key)))) || rest.is_some_and(<[&str]>::is_empty);
let place = ParamsPlace { command: self.command, top: false, trail: rest.filter(|keys| !keys.is_empty()) };
(place, if document { None } else { key_location(key) })
}
/// The place of item `index` of an array here. `step` is [`ParamsPlace::step`] of that array: its
/// item 1 is then the top of that command's params.
pub fn item(self, index: usize, step: Option<ParamsPlace>) -> ParamsPlace {
match step {
Some(inner) if index == 1 => inner,
_ => ParamsPlace { command: self.command, top: false, trail: None },
}
}
}
/// The param keys of `spec` that name a file or a folder, with what they name: the keys in
@@ -158,9 +252,6 @@ pub(crate) const NOT_FILES: &[(&str, &str)] = &[
("symbol.instance.setAppearance", "path"),
("symbol.instance.selectPart", "path"),
("object.objectsOnPath.attach", "path"),
("attributes.set", "url"),
("object.slice.options", "url"),
("document.exportForScreens", "folders"),
];
/// Commands and the keys from the top of their params down to a key in [`FILE_KEYS`] that, there,
@@ -251,34 +342,24 @@ pub(crate) fn names_key(text: &str, key: &str) -> bool {
})
}
/// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth
/// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`]
/// names for `id`, at the top level, and one at the end of a [`NESTED_NOT_FILES`] key list for
/// `id`, aren't counted. The walk keeps its own stack, so deep arguments can't overflow the
/// thread's.
/// Does `args`, the arguments of a call of command `id`, carry a key that names a file or a folder at
/// any depth (in objects and in arrays, [`ParamsPlace`]), such as an effect's `textureImage.path`?
/// Only a key [`NOT_FILES`] names for `id`, at the top level, and one at the end of a
/// [`NESTED_NOT_FILES`] key list for `id`, aren't counted. A call or a recorded step inside `args`
/// is read as part of `id`'s arguments, not as the command it names. The walk keeps its own stack,
/// so deep arguments can't overflow the thread's.
fn names_file(id: &str, args: &Value) -> bool {
// Each value, whether it is the params themselves, and the keys of a NESTED_NOT_FILES list
// still to follow below it.
let mut stack: Vec<(&Value, bool, Option<&[&str]>)> = vec![(args, true, None)];
while let Some((v, top, trail)) = stack.pop() {
let mut stack: Vec<(&Value, ParamsPlace)> = vec![(args, ParamsPlace::of(id))];
while let Some((v, place)) = stack.pop() {
match v {
Value::Array(a) => stack.extend(a.iter().map(|x| (x, false, None))),
Value::Array(a) => stack.extend(a.iter().enumerate().map(|(i, x)| (x, place.item(i, None)))),
Value::Object(o) => {
for (k, x) in o {
let k = k.as_str();
let rest = if top {
NESTED_NOT_FILES
.iter()
.find(|(c, keys)| *c == id && keys.first() == Some(&k))
.map(|(_, keys)| keys.get(1..).unwrap_or_default())
} else {
trail.filter(|keys| keys.first() == Some(&k)).map(|keys| keys.get(1..).unwrap_or_default())
};
let document = (top && NOT_FILES.contains(&(id, k))) || rest.is_some_and(<[&str]>::is_empty);
if FILE_KEYS.contains(&k) && !document {
let (below, location) = place.member(k, None);
if location.is_some() {
return true;
}
stack.push((x, false, rest.filter(|keys| !keys.is_empty())));
stack.push((x, below));
}
}
_ => {}
@@ -638,7 +719,13 @@ mod tests {
assert!(names_file("effect.apply", &texture));
assert!(names_file("effect.setParams", &texture));
assert!(names_file("effect.apply", &json!({"params": {"layers": [{"name": "a"}, {"folder": "/tmp"}]}})));
assert!(names_file("select.all", &json!([[[{"url": "file:///etc/hosts"}]]])));
assert!(names_file("select.all", &json!([[[{"file": "file:///etc/hosts"}]]])));
// A web link and an export's grouping name no file.
assert!(!names_file("attributes.set", &json!({"url": "https://example.com/a"})));
assert!(!names_file("object.move", &json!({"opts": {"folders": "rows", "alignToPath": "baseline"}})));
// A call nested in the arguments doesn't vouch for its own keys.
assert!(names_file("object.move", &json!({"opts": {"command": "object.setLiveShape", "params": {"path": "/tmp/x"}}})));
assert!(names_file("object.move", &json!({"opts": ["object.setLiveShape", {"path": "/tmp/x"}]})));
assert!(!names_file("effect.apply", &json!({"effect": "distort.glass", "params": {"distortion": 5, "textureImage": "frosted"}})));
assert!(!names_file("object.move", &json!({"dx": 5, "dy": 0, "ids": [1, 2], "opts": {"copy": false}})));
// `path` is the path text is set on in text.createInPath, but only as its own param.
@@ -647,7 +734,13 @@ mod tests {
assert!(names_file("object.move", &json!({"path": [[0, 0]]})));
// object.setLiveShape takes no `path`; its description says "on any path:" in its prose.
assert!(names_file("object.setLiveShape", &json!({"path": "/tmp/x"})));
// Image Trace's path fidelity setting, only inside its tracing settings.
}
/// Image Trace's path fidelity setting `paths` names no file, but only inside its tracing
/// settings.
#[test]
fn image_trace_paths_name_no_file_only_in_its_settings() {
use serde_json::json;
for id in ["imageTrace.make", "imageTrace.makeAndExpand"] {
assert!(!names_file(id, &json!({"preset": "Default", "params": {"mode": "color", "paths": 50}})));
assert!(!names_file(id, &json!({"savedPreset": {"paths": 50, "corners": 75}})));
@@ -658,7 +751,12 @@ mod tests {
assert!(names_file(id, &json!({"options": {"paths": 50}})));
}
assert!(names_file("object.move", &json!({"params": {"paths": 50}})));
// A custom arrowhead's outline in stroke.set, only where stroke.set takes one.
}
/// A custom arrowhead's outline `path` names no file, but only where stroke.set takes one.
#[test]
fn a_custom_arrowhead_outline_names_no_file_only_in_stroke_set() {
use serde_json::json;
let outline = json!({"subpaths": []});
assert!(!names_file("stroke.set", &json!({"endArrow": {"Custom": {"name": "A", "path": outline}}})));
assert!(!names_file("stroke.set", &json!({"startArrow": {"Custom": {"name": "A", "path": outline}}, "endArrow": "Triangle"})));
@@ -668,7 +766,12 @@ mod tests {
assert!(names_file("stroke.set", &json!({"options": {"endArrow": {"Custom": {"path": "/tmp/x"}}}})));
assert!(names_file("stroke.set", &json!({"endArrow": [{"Custom": {"path": "/tmp/x"}}]})));
assert!(names_file("object.move", &json!({"endArrow": {"Custom": {"path": "/tmp/x"}}})));
// Deep nesting is walked without recursion.
}
/// A file key under deep nesting is found, and the walk doesn't recurse.
#[test]
fn a_file_key_is_found_under_deep_nesting() {
use serde_json::json;
let mut deep = json!({"file": "/tmp/x"});
for _ in 0..10_000 {
deep = Value::Array(vec![deep]);
@@ -726,11 +829,48 @@ mod tests {
assert!(found.iter().all(|(k, l)| (*l == Location::Folder) == FOLDER_KEYS.contains(k)), "{}: {found:?}", spec.id);
assert!(denied(spec).is_some() || found.is_empty(), "{} names {found:?} but a plug-in may call it", spec.id);
}
assert_eq!(key_location("url"), Some(Location::File));
assert_eq!(key_location("url"), None);
assert_eq!(key_location("folders"), None);
assert_eq!(key_location("linksFolder"), None);
assert_eq!(key_location("sourceFolder"), Some(Location::Folder));
assert_eq!(key_location("pathData"), None);
}
/// A key keeps the meaning its command gives it at every depth: a call (`{command, params}`) and a
/// recorded step (`[command id, params]`) carry their command's exceptions down, and a custom
/// arrowhead's outline is part of the document only at its own place in `stroke.set`.
#[test]
fn a_params_place_follows_its_command() {
use serde_json::json;
let at = |place: ParamsPlace, keys: &[&str]| {
let mut place = place;
let mut location = None;
for k in keys {
(place, location) = place.member(k, None);
}
location
};
assert_eq!(at(ParamsPlace::of("text.createInPath"), &["path"]), None);
assert_eq!(at(ParamsPlace::of("text.createInPath"), &["options", "path"]), Some(Location::File));
assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "path"]), None);
assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "file"]), Some(Location::File));
assert_eq!(at(ParamsPlace::of("no.such.command"), &["path"]), Some(Location::File));
assert_eq!(at(ParamsPlace::top(None), &["destinationFolder"]), Some(Location::Folder));
let call = json!({"command": "text.createInPath", "params": {"path": [[0, 0]]}});
let carried = call.as_object().and_then(ParamsPlace::carried);
let (inner, location) = ParamsPlace::of("command.batch").member("params", carried);
assert_eq!(location, None);
assert_eq!(inner.member("path", None).1, None);
assert_eq!(ParamsPlace::carried(&serde_json::Map::new()).map(|_| ()), None);
let unknown = json!({"command": "no.such.command", "params": {}});
assert!(unknown.as_object().and_then(ParamsPlace::carried).is_none());
let step = [json!("text.createInPath"), json!({"path": [[0, 0]]})];
let place = ParamsPlace::top(None).item(1, ParamsPlace::step(&step));
assert_eq!(place.member("path", None).1, None);
assert_eq!(ParamsPlace::top(None).item(0, ParamsPlace::step(&step)).member("path", None).1, Some(Location::File));
assert!(ParamsPlace::step(&[json!("text.createInPath")]).is_none());
}
/// A file key counts as a command's param only where its description takes it: not a word in
/// the prose after the params, in a nested object or in the result. A description that doesn't
/// say which keys it takes counts any `key:` in its text.
@@ -34,6 +34,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.contour.set",
"addon.cutting.banner",
"addon.cutting.bridges",
"addon.cutting.nest",
"addon.cutting.weed",
"addon.image.applyColorMask",
"addon.image.colorMask",
@@ -473,6 +474,7 @@ pub(super) const ALLOWED: &[&str] = &[
"perspective.grid.snap",
"perspective.move",
"perspective.nudge",
"perspective.plane.infer",
"perspective.plane.matchObject",
"perspective.plane.move",
"perspective.plane.set",
+1
View File
@@ -217,6 +217,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("recentFontsCount", "Type", "Options", "Number of Recent Fonts", int(1, 15)),
p!("missingGlyphProtection", "Type", "Options", "Enable Missing Glyph Protection", bool),
p!("highlightAlternateGlyphs", "Type", "Options", "Highlight Alternate Glyphs", bool),
p!("showCharacterAlternates", "Type", "Options", "Show Character Alternates", bool),
p!("highlightSubstitutedFonts", "Type", "Options", "Highlight Substituted Fonts", bool),
p!("placeholderText", "Type", "Options", "Fill New Type Objects With Placeholder Text", bool),
p!("typedLists", "Type", "Options", "Start Lists From Typed Markers", bool),
+81 -11
View File
@@ -8,7 +8,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, TextWrap};
use super::typecmd::refresh_bounds;
use super::{CommandSpec, EngineError, Result, Session, bool_or, checked_ids_or_selection, cmd, f64_or, has_selection};
use super::{CommandSpec, EngineError, Result, Session, bad, checked_ids_or_selection, cmd, has_selection, number_or, switch_or};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Text Wrap"],
None,
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a negative offset (to -1000) lets the text that far into them → {ids}",
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids}",
has_selection,
make
),
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Wrap Options…",
["Object", "Text Wrap"],
None,
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); no options → the current {offset, invert}",
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}",
has_selection,
options
),
@@ -37,14 +37,23 @@ pub fn specs() -> Vec<CommandSpec> {
/// The Offset a wrap object takes, in points.
pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive<f64> = -1000.0..=1000.0;
fn wrap_param(p: &Value, base: TextWrap) -> TextWrap {
let (lo, hi) = (*TEXT_WRAP_OFFSET_RANGE.start(), *TEXT_WRAP_OFFSET_RANGE.end());
TextWrap { offset: f64_or(p, "offset", base.offset).clamp(lo, hi), invert: bool_or(p, "invert", base.invert) }
/// The options `p` gives, with `base` for an omitted or null `offset` or `invert`. An `offset` that is
/// not a number or lies outside [`TEXT_WRAP_OFFSET_RANGE`], or an `invert` that is not true or false,
/// is an error. `base`'s offset is kept as it is.
fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result<TextWrap> {
let key = "offset";
let given = p.get(key).is_some_and(|v| !v.is_null());
let offset = number_or(p, key, base.offset, cmd)?;
if given && !TEXT_WRAP_OFFSET_RANGE.contains(&offset) {
let (lo, hi) = (TEXT_WRAP_OFFSET_RANGE.start(), TEXT_WRAP_OFFSET_RANGE.end());
return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}")));
}
Ok(TextWrap { offset, invert: switch_or(p, "invert", base.invert, cmd)? })
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
let ids = checked_ids_or_selection(s, p, "object.textWrap.make")?;
let w = wrap_param(p, TextWrap::default());
let w = wrap_param(p, TextWrap::default(), "object.textWrap.make")?;
s.edit("Make Text Wrap", |d, _| {
for id in &ids {
let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
@@ -86,10 +95,10 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default()
};
if p.get("offset").is_none() && p.get("invert").is_none() {
if ["offset", "invert"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) {
return Ok(json!({ "offset": current.offset, "invert": current.invert }));
}
let w = wrap_param(p, current);
let w = wrap_param(p, current, "object.textWrap.options")?;
s.edit("Text Wrap Options", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id)
@@ -212,11 +221,72 @@ mod tests {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.execute("object.textWrap.options", &json!({})).unwrap()["offset"], json!(6.0));
assert!(beside(&s).iter().all(|x| (x - 206.0).abs() < 1e-6), "{:?}", beside(&s));
// An offset past -1000 is kept at -1000: the whole object lets text through.
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -5000})).unwrap()["offset"], json!(-1000.0));
// An offset of -1000 lets the text through the whole object.
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -1000})).unwrap()["offset"], json!(-1000.0));
assert!(lines(&s, t).iter().all(|l| l.0 < 1.0 && l.1 > 300.0));
}
/// An offset that is not a number or lies outside -1000 to 1000 pt, or an invert that is not
/// true or false, is an error for Make and Options, and leaves the options and the history as
/// they were. Omitted and null values take the default, and the range's ends are accepted.
#[test]
fn text_wrap_commands_refuse_bad_offsets_and_inverts_without_editing() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let wrap = |s: &Session| s.doc().unwrap().doc.node(NodeId(id)).unwrap().extras().wrap;
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let refused = [
(json!({"offset": "12"}), "`offset` must be a number"),
(json!({"offset": true}), "`offset` must be a number"),
(json!({"offset": [12]}), "`offset` must be a number"),
(json!({"offset": {"pt": 12}}), "`offset` must be a number"),
(json!({"offset": 1000.5}), "`offset` must be from -1000 to 1000"),
(json!({"offset": -1000.5}), "`offset` must be from -1000 to 1000"),
(json!({"offset": 5000}), "`offset` must be from -1000 to 1000"),
(json!({"offset": 12, "invert": "true"}), "`invert` must be true or false"),
(json!({"offset": 12, "invert": 1}), "`invert` must be true or false"),
(json!({"invert": "false"}), "`invert` must be true or false"),
];
let start = undo(&s);
for (p, msg) in &refused {
let e = s.execute("object.textWrap.make", p).unwrap_err().to_string();
assert!(e.contains(msg), "make {p}: {e}");
assert!(wrap(&s).is_none(), "make {p} made a wrap");
assert_eq!(undo(&s), start, "make {p} added history");
}
// Omitted and null values: Make's 6 pt default.
s.execute("object.textWrap.make", &json!({"offset": null, "invert": null})).unwrap();
assert_eq!(wrap(&s), Some(vectorcraft_doc::TextWrap { offset: 6.0, invert: false }));
s.execute("object.textWrap.options", &json!({"offset": 40, "invert": true})).unwrap();
let before = undo(&s);
for (p, msg) in &refused {
let e = s.execute("object.textWrap.options", p).unwrap_err().to_string();
assert!(e.contains(msg), "options {p}: {e}");
assert_eq!(wrap(&s), Some(vectorcraft_doc::TextWrap { offset: 40.0, invert: true }), "options {p}");
assert_eq!(undo(&s), before, "options {p} added history");
}
// Null options read the current ones without an undo step; a null one keeps its value.
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": null, "invert": null})).unwrap(), json!({"offset": 40.0, "invert": true}));
assert_eq!(undo(&s), before);
assert_eq!(
s.execute("object.textWrap.options", &json!({"offset": null, "invert": false})).unwrap(),
json!({"offset": 40.0, "invert": false})
);
// The range's ends are accepted by both commands.
for (command, offset) in
[("object.textWrap.options", 1000), ("object.textWrap.options", -1000), ("object.textWrap.make", 1000), ("object.textWrap.make", -1000)]
{
s.execute(command, &json!({ "offset": offset })).unwrap();
assert_eq!(wrap(&s).unwrap().offset, f64::from(offset), "{command} {offset}");
}
// A stored offset outside the range (from a file) is kept when only Invert Wrap changes.
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(NodeId(id)).unwrap().extras_mut().wrap = Some(vectorcraft_doc::TextWrap { offset: 5000.0, invert: false });
assert_eq!(s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(), json!({"offset": 5000.0, "invert": true}));
}
#[test]
fn text_flows_on_both_sides_of_a_centred_object() {
let mut s = Session::new();
+10
View File
@@ -400,6 +400,8 @@ thread_local! {
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's
/// threads on this thread.
static THREAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`story_in`] went through a thread's frames on this thread.
static STORY_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's
@@ -409,6 +411,12 @@ pub(crate) fn thread_scans() -> usize {
THREAD_SCANS.with(std::cell::Cell::get)
}
/// Tests: how many times [`story_in`] has gone through a thread's frames on this thread.
#[cfg(test)]
pub(crate) fn story_builds() -> usize {
STORY_BUILDS.with(std::cell::Cell::get)
}
/// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a
/// path; empty when `id` is in no thread or the thread has fewer than two such frames.
pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec<NodeId> {
@@ -420,6 +428,8 @@ pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec<NodeId> {
/// [`story_of`] for `id` in `thread`, the first of the document's threads that lists it.
pub(crate) fn story_in(d: &Document, thread: &[NodeId], id: NodeId) -> Vec<NodeId> {
#[cfg(test)]
STORY_BUILDS.with(|c| c.set(c.get() + 1));
let frames: Vec<NodeId> = thread.iter().copied().filter(|f| text_of(d, *f).is_some()).collect();
if frames.len() >= 2 && frames.contains(&id) { frames } else { vec![] }
}
+73 -42
View File
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Text",
[],
None,
"{id?|ids?, text} replace the contents of text objects (keeps the first run's style) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits)}",
"{id?|ids?, text} replace the contents of text objects (keeps the first run's style); no undo step when no object changes (each already has the text in one style, every paragraph with the first one's attributes, and no ruby) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits)}",
has_doc,
set_text
),
@@ -104,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reshape Type Area",
[],
None,
"{id, anchors: [[subpath, anchor]…], dx, dy} or {items: [{id, anchors}…], dx, dy} move anchors of area type's frame (the type area) by dx, dy points, with their handles; the text reflows at its size, through its thread too (what Direct Selection does dragging a frame corner or edge, or the frame anchors its marquee selected, and the arrow keys nudging those); with items, every listed frame moves in one step",
"{id, anchors: [[subpath, anchor]…], dx, dy} or {items: [{id, anchors}…], dx, dy} move anchors of area type's frame (the type area) by dx, dy points, with their handles; the text reflows at its size, through its thread too (what Direct Selection does dragging a frame corner or edge, or the frame anchors its marquee selected, and the arrow keys nudging those); with items, every listed frame moves in one step; no undo step when no frame changes (dx and dy both 0)",
has_doc,
reshape_area
),
@@ -113,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reshape Type Path",
[],
None,
"{id, anchors: [[subpath, anchor]…], dx, dy} move anchors of type on a path's path by dx, dy points, with their handles; the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging an anchor of the path)",
"{id, anchors: [[subpath, anchor]…], dx, dy} move anchors of type on a path's path by dx, dy points, with their handles; the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging an anchor of the path); no undo step when the path does not change (dx and dy both 0)",
has_doc,
reshape_path
),
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Type Path Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path)",
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
has_doc,
set_path_handle
),
@@ -131,7 +131,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fit Headline",
["Type"],
None,
"{ids?|id?} track the first line of area type so it fills the frame width → {tracking}",
"{ids?|id?} track the first line of area type so it fills the frame width; no undo step when the first line already has that tracking → {tracking}",
has_selection,
fit_headline
),
@@ -140,7 +140,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
has_doc,
set_style
),
@@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Ruby…",
[],
None,
"{ids?|id?, start?: byte, end?: byte, text?: reading, position?: above|below (vertical type: right|left), align?: start|center|end, size?: 1–100 (percent of the base text's size, default 50), overhang?: bool (default true), remove?: bool} set the ruby (furigana) over the selected text's bytes in `start..end` (without them: all its text): the reading over the base characters, above them in horizontal type and right of them in vertical type; `remove` takes the ruby off the range instead → {ids, ruby: [{start, end, text, position, align, sizePercent, overhang}…] (the first object's ruby)}",
"{ids?|id?, start?: byte, end?: byte, text?: reading, position?: above|below (vertical type: right|left), align?: start|center|end, size?: 1–100 (percent of the base text's size, default 50), overhang?: bool (default true), remove?: bool} set the ruby (furigana) over the selected text's bytes in `start..end` (without them: all its text): the reading over the base characters, above them in horizontal type and right of them in vertical type; `remove` takes the ruby off the range instead; no undo step when the ruby does not change (the same reading and options again, or `remove` where there is none) → {ids, ruby: [{start, end, text, position, align, sizePercent, overhang}…] (the first object's ruby)}",
has_selection,
ruby
),
@@ -265,8 +265,8 @@ fn fractional_widths(s: &mut Session, p: &Value) -> Result<Value> {
}
/// Type › Ruby: set or remove the ruby (furigana) over a byte range of the selected type in one
/// undo step. Without `start`/`end` the range is all the text; a new reading replaces the ruby
/// over the range. The reply lists the first object's ruby (start/end in bytes of its plain text).
/// undo step (none when nothing changes). Without `start`/`end` the range is all the text; a new
/// reading replaces the ruby over the range. The reply lists the first object's ruby (start/end in bytes of its plain text).
fn ruby(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.ruby";
let ids = text_targets(s, p, C)?;
@@ -293,7 +293,8 @@ fn ruby(s: &mut Session, p: &Value) -> Result<Value> {
}
let overhang = switch_or(p, "overhang", true, C)?;
let mut first: Option<Value> = None;
s.edit("Ruby", |d, _| {
// The same reading again, or a removal where there is no ruby, is no undo step.
edit_if_nodes_changed(s, "Ruby", &ids, |d| {
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else {
return Err(EngineError::NoNode(*id));
@@ -320,7 +321,7 @@ fn ruby(s: &mut Session, p: &Value) -> Result<Value> {
first = Some(serde_json::to_value(&t.ruby).unwrap_or(Value::Null));
}
}
Ok(())
Ok(((), false))
})?;
Ok(json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "ruby": first.unwrap_or(Value::Null)}))
}
@@ -615,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| {
@@ -622,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();
@@ -657,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());
}
@@ -673,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)));
@@ -704,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
@@ -749,12 +755,26 @@ 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)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
/// [`Session::edit`] for a type command that may set what the type already has: `f` runs on a
/// copy of the document, and it becomes an undo step only when one of the objects `ids` differs
/// afterwards or `f` returns true for a change of its own elsewhere (a graph's kept label styles).
/// When nothing changed, the document, its undo and redo steps and its saved state stay as they
/// were. Only the objects are compared, not the whole document, whose embedded images can be large.
fn edit_if_nodes_changed<T>(s: &mut Session, label: &str, ids: &[NodeId], f: impl FnOnce(&mut Document) -> Result<(T, bool)>) -> Result<T> {
super::colorcmds::edit_if_changed(s, label, |before, d| {
let (v, other) = f(d)?;
let changed = other || ids.iter().any(|id| before.node(*id) != d.node(*id));
Ok((v, changed))
})
}
pub(crate) fn text_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let ids = targets(s, p)?;
let t = text_ids(&s.doc()?.doc, &ids);
@@ -849,7 +869,8 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option<TextRange>, mut f: i
fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
let ids = text_targets(s, p, "text.setText")?;
s.edit("Typing", |d, _| {
// The text the type already has is no undo step.
edit_if_nodes_changed(s, "Typing", &ids, |d| {
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
let style = t.first_style();
@@ -860,7 +881,7 @@ fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
t.ruby.clear();
refresh_bounds(t);
}
Ok(())
Ok(((), false))
})?;
Ok(with_overflow(s, &ids, json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })))
}
@@ -933,7 +954,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some());
// The fonts the styled characters are set in, for the warning.
let mut set = std::collections::BTreeSet::new();
s.edit("Character", |d, _| {
// Attributes the characters already have are no undo step.
edit_if_nodes_changed(s, "Character", &ids, |d| {
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
let size = size.map(|v| local_type_value(t, v, (0.1, 1296.0), false, C)).transpose()?;
@@ -1008,8 +1030,9 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
}
// Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given,
// not in a scaled label's own units).
let mut labels_changed = false;
if range.is_none() {
super::graph::capture_label_styles(d, &ids, &|st| {
labels_changed = super::graph::capture_label_styles(d, &ids, &|st| {
if let Some(f) = &font {
st.font_family = f.clone();
st.font_version = None;
@@ -1052,7 +1075,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
}
});
}
Ok(())
Ok(((), labels_changed))
})?;
let mut out = with_overflow(s, &ids, json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }));
if let Some(w) = super::fonts::set_font_warning(set) {
@@ -1350,14 +1373,16 @@ fn reshape_area(s: &mut Session, p: &Value) -> Result<Value> {
items.push((id, refs));
}
let d = Vec2::new(f64_req(p, "dx", C)?, f64_req(p, "dy", C)?);
s.edit("Reshape Type Area", |doc, _| {
// Anchors moved by no distance are no undo step.
let ids: Vec<NodeId> = items.iter().map(|(id, _)| *id).collect();
edit_if_nodes_changed(s, "Reshape Type Area", &ids, |doc| {
for (id, refs) in &items {
let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(*id)) };
if !reshape_area_with(t, |t| t.move_area_anchors(refs, d)) {
return Err(bad(C, "no such frame anchor, or the frame would reach past the canvas"));
}
}
Ok(())
Ok(((), false))
})?;
ok()
}
@@ -1377,7 +1402,8 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> {
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
return Err(bad(C, "not type on a path outside perspective"));
}
s.edit("Reshape Type Path", |doc, _| {
// Anchors moved by no distance are no undo step.
edit_if_nodes_changed(s, "Reshape Type Path", &[id], |doc| {
let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
let before = t.kind.clone();
let within = |t: &TextObject| {
@@ -1388,7 +1414,7 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
}
refresh_bounds(t);
Ok(())
Ok(((), false))
})?;
ok()
}
@@ -1406,7 +1432,8 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
return Err(bad(C, "not type on a path outside perspective"));
}
s.edit("Reshape Type Path", |doc, _| {
// A handle moved to where it is is no undo step.
edit_if_nodes_changed(s, "Reshape Type Path", &[id], |doc| {
let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
let before = t.kind.clone();
let within = |t: &TextObject| {
@@ -1417,7 +1444,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
}
refresh_bounds(t);
Ok(())
Ok(((), false))
})?;
ok()
}
@@ -1428,6 +1455,8 @@ mod block;
pub(crate) use block::needed_room;
#[cfg(test)]
mod block_tests;
#[cfg(test)]
mod noop_tests;
/// Width of the first line and of the space it can fill, with `tracking` on the first paragraph.
/// The third value is where the first line ends in the plain text.
@@ -1469,7 +1498,9 @@ fn fit_headline(s: &mut Session, p: &Value) -> Result<Value> {
plans.push((*id, (lo * 10.0).floor() / 10.0));
}
let first = plans.first().map(|p| p.1).ok_or_else(|| bad(C, "select area type whose first line can fit its frame"))?;
s.edit("Fit Headline", |d, _| {
// A headline that already has its fitted tracking is no undo step.
let fitted: Vec<NodeId> = plans.iter().map(|(id, _)| *id).collect();
edit_if_nodes_changed(s, "Fit Headline", &fitted, |d| {
for (id, tr) in &plans {
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
let end = t.plain_text().find('\n').unwrap_or(usize::MAX).min(vectorcraft_text::edit::runs_len(&t.runs));
@@ -1477,7 +1508,7 @@ fn fit_headline(s: &mut Session, p: &Value) -> Result<Value> {
refresh_bounds(t);
}
}
Ok(())
Ok(((), false))
})?;
Ok(json!({ "tracking": first }))
}
+143
View File
@@ -0,0 +1,143 @@
use super::*;
/// The document and the number of undo steps, to compare before and after a command that sets
/// what the type already has.
fn state(s: &Session) -> (std::sync::Arc<Document>, usize) {
let st = s.doc().unwrap();
(st.doc.clone(), st.history.undo.len())
}
/// Assert that `cmd` with `p` leaves the document and its undo history as they were.
fn records_nothing(s: &mut Session, cmd: &str, p: Value) {
let before = state(s);
s.execute(cmd, &p).unwrap();
let after = state(s);
assert!(*after.0 == *before.0, "{cmd} {p} changed the document");
assert_eq!(after.1, before.1, "{cmd} {p} recorded an undo step");
}
/// Assert that `cmd` with `p` changes the document in exactly one undo step.
fn records_one_step(s: &mut Session, cmd: &str, p: Value) {
let before = state(s);
s.execute(cmd, &p).unwrap();
let after = state(s);
assert!(*after.0 != *before.0, "{cmd} {p} left the document as it was");
assert_eq!(after.1, before.1 + 1, "{cmd} {p} did not record one undo step");
}
fn session_with(text: &str, area: Option<Value>) -> (Session, u64) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let mut p = json!({"x": 10, "y": 20, "text": text, "size": 24});
if let Some(a) = area {
p["area"] = a;
}
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
(s, id)
}
/// Ruby set again with the same reading and options, or removed where there is none, records no
/// undo step; a step that does change the ruby still undoes in one.
#[test]
fn ruby_that_changes_nothing_records_no_undo_step() {
let (mut s, id) = session_with("漢字です", None);
records_nothing(&mut s, "type.ruby", json!({"remove": true}));
let p = json!({"text": "かんじ", "start": 0, "end": 6, "position": "below", "size": 60});
records_one_step(&mut s, "type.ruby", p.clone());
records_nothing(&mut s, "type.ruby", p);
s.execute("type.ruby", &json!({"remove": true})).unwrap();
records_nothing(&mut s, "type.ruby", json!({"remove": true, "start": 0, "end": 6}));
s.execute("edit.undo", &json!({})).unwrap();
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") };
assert_eq!(t.ruby.len(), 1, "undo brings the ruby back");
}
/// `text.setStyle` (the Character panel) given the attributes the characters already have
/// records no undo step, with a range too.
#[test]
fn character_attributes_already_set_record_no_undo_step() {
let (mut s, _) = session_with("Headline", None);
records_nothing(&mut s, "text.setStyle", json!({"size": 24}));
s.execute("text.setStyle", &json!({"tracking": 50, "fill": "#ff0000"})).unwrap();
records_nothing(&mut s, "text.setStyle", json!({"tracking": 50, "fill": "#ff0000"}));
records_nothing(&mut s, "text.setStyle", json!({"tracking": 50, "start": 0, "end": 4}));
s.execute("text.setStyle", &json!({"justify": "center"})).unwrap();
records_nothing(&mut s, "text.setStyle", json!({"justify": "center"}));
records_one_step(&mut s, "text.setStyle", json!({"tracking": 80, "start": 0, "end": 4}));
}
/// `text.setStyle` on a graph label that leaves the label's own text as it is but changes the
/// style its kind of label keeps still records one undo step; given again, it records none.
#[test]
fn a_kept_graph_label_style_change_alone_records_one_undo_step() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
let graph = NodeId(
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let doc = s.doc().unwrap().doc.clone();
let legend = doc.node(graph).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap();
let (label, size) = legend
.children()
.unwrap()
.iter()
.find_map(|c| match &c.kind {
NodeKind::Text(t) if t.plain_text() == "2025" => Some((c.id, t.runs[0].style.size)),
_ => None,
})
.unwrap();
let kept = |s: &Session| s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_deref().unwrap().label_styles.legend.clone();
assert!(kept(&s).is_none());
let p = json!({"ids": [label.0], "size": size});
let before = state(&s);
s.execute("text.setStyle", &p).unwrap();
let after = state(&s);
assert!(after.0.node(label) == before.0.node(label), "the label's own text changed");
assert!(kept(&s).is_some(), "the legend keeps the style");
assert_eq!(after.1, before.1 + 1, "the kept style change recorded no undo step");
records_nothing(&mut s, "text.setStyle", p);
}
/// `text.setText` with the text the type already has records no undo step; new text records one.
#[test]
fn the_same_text_records_no_undo_step() {
let (mut s, _) = session_with("Same words", None);
records_nothing(&mut s, "text.setText", json!({"text": "Same words"}));
records_one_step(&mut s, "text.setText", json!({"text": "Other words"}));
}
/// Fit Headline run again on a headline it already fitted records no undo step; the first run
/// records one.
#[test]
fn fit_headline_again_records_no_undo_step() {
let (mut s, _) = session_with("HEADLINE\nbody text", Some(json!({"width": 300, "height": 120})));
let start = state(&s);
let tracking = s.execute("text.fitHeadline", &json!({})).unwrap()["tracking"].clone();
let fitted = state(&s);
assert!(*fitted.0 != *start.0 && fitted.1 == start.1 + 1, "the first Fit Headline did not record one undo step");
let before = state(&s);
assert_eq!(s.execute("text.fitHeadline", &json!({})).unwrap()["tracking"], tracking);
let after = state(&s);
assert!(*after.0 == *before.0 && after.1 == before.1, "a second Fit Headline recorded an undo step");
}
/// Reshaping area type or type on a path by no distance, or moving a path handle to where it is,
/// records no undo step; a reshape that moves something records one.
#[test]
fn reshaping_type_by_nothing_records_no_undo_step() {
let (mut s, id) = session_with("Boxed words", Some(json!({"width": 200, "height": 100})));
records_nothing(&mut s, "text.reshapeArea", json!({"id": id, "anchors": [[0, 2]], "dx": 0, "dy": 0}));
records_one_step(&mut s, "text.reshapeArea", json!({"id": id, "anchors": [[0, 2]], "dx": 20, "dy": 10}));
let path =
s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 300, "in": [50, 300], "out": [150, 300]}, {"x": 400, "y": 300}]})).unwrap();
let on_path = s.execute("text.createInPath", &json!({"path": path["id"], "mode": "onPath", "text": "Along the curve"})).unwrap()["id"].clone();
records_nothing(&mut s, "text.reshapePath", json!({"id": on_path, "anchors": [[0, 1]], "dx": 0, "dy": 0}));
records_one_step(&mut s, "text.reshapePath", json!({"id": on_path, "anchors": [[0, 1]], "dx": 0, "dy": 20}));
let handle = json!({"id": on_path, "anchor": 0, "which": "out", "x": 100, "y": 250});
records_one_step(&mut s, "text.setPathHandle", handle.clone());
records_nothing(&mut s, "text.setPathHandle", handle);
}
+314 -18
View File
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Smart Punctuation…",
["Type"],
None,
"{quotes?: true (straight quotes become the Document Setup quotes), dashes?: true (-- → en dash, --- → em dash), ellipsis?: true (... → …), scope?: \"selection\"|\"document\"} → {changed}",
"{fiLigatures?: false (ff, fi, ffi → the ligatures U+FB00, U+FB01, U+FB03), flLigatures?: false (ff, fl, ffl → U+FB00, U+FB02, U+FB04), quotes?: true (straight quotes become the Document Setup quotes), spaces?: false (two or more spaces after a period → one), dashes?: true (-- → en dash, --- → em dash), ellipsis?: true (... → …), fractions?: false (1/2, 1/4, 3/4 and the other fractions Unicode encodes as one character, with no digit, slash or decimal point next to them, → ½, ¼, ¾ …), scope?: \"selection\"|\"document\"} the selected type, or every text object with scope document or nothing selected; a ligature or a fraction is written only where the run's font has a glyph for it. Nothing to replace records no undo step → {changed: text objects changed, replaced: {fiLigatures, flLigatures, quotes, spaces, dashes, ellipses, fractions}: how many of each were replaced}",
has_doc,
smart_punctuation
),
@@ -268,24 +268,227 @@ fn change_case(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- Smart Punctuation ----------
#[derive(Default)]
struct PunctState {
prev: Option<char>,
/// What Smart Punctuation replaces: each option of its dialog.
struct Punct {
/// ff, fi and ffi become the ligatures U+FB00, U+FB01 and U+FB03.
fi_ligatures: bool,
/// ff, fl and ffl become the ligatures U+FB00, U+FB02 and U+FB04.
fl_ligatures: bool,
/// Straight quotes become these quotes (the Document Setup quotes).
quotes: Option<Quotes>,
/// Two or more spaces after a period become one.
spaces: bool,
/// `--` becomes an en dash and `---` an em dash.
dashes: bool,
/// `...` becomes an ellipsis.
ellipses: bool,
/// `1/2` and the other fractions [`FRACTIONS`] lists become their one-character forms.
fractions: bool,
}
/// Dashes (`--` en, `---` em), ellipses and, with `quotes`, typographer's quotes.
pub(crate) fn smarten(text: &str, prev: &mut Option<char>, quotes: Option<&Quotes>, dashes: bool, ellipsis: bool) -> String {
let mut s = text.to_string();
if dashes {
s = s.replace("---", "—").replace("--", "–");
/// How many of each replacement Smart Punctuation made.
#[derive(Default)]
struct PunctCounts {
fi_ligatures: usize,
fl_ligatures: usize,
quotes: usize,
spaces: usize,
dashes: usize,
ellipses: usize,
fractions: usize,
}
/// The text before the run being rewritten, across the runs of one text object.
#[derive(Default)]
struct PunctState {
/// The character before the run.
prev: Option<char>,
/// The number of spaces since the last period, while only spaces follow it.
after_period: Option<usize>,
/// An inline graphic comes right before the run.
after_graphic: bool,
}
/// The fractions Expert Fractions writes as one character: every fraction Unicode encodes as a
/// vulgar fraction with a numerator of 1 to 7 and a denominator of 2 to 10.
const FRACTIONS: [(&str, char); 18] = [
("1/2", '½'),
("1/3", '⅓'),
("2/3", '⅔'),
("1/4", '¼'),
("3/4", '¾'),
("1/5", '⅕'),
("2/5", '⅖'),
("3/5", '⅗'),
("4/5", '⅘'),
("1/6", '⅙'),
("5/6", '⅚'),
("1/7", '⅐'),
("1/8", '⅛'),
("3/8", '⅜'),
("5/8", '⅝'),
("7/8", '⅞'),
("1/9", '⅑'),
("1/10", '⅒'),
];
/// `s` with every `from` replaced by `to`, adding the number replaced to `n`.
fn replace_counted(s: String, from: &str, to: &str, n: &mut usize) -> String {
let found = s.matches(from).count();
if found == 0 {
return s;
}
if ellipsis {
s = s.replace("...", "…");
*n += found;
s.replace(from, to)
}
/// Smart Spaces: `text` without the second and later spaces after a period, adding the number of
/// periods whose spaces it shortened to `n`. `after` carries the spaces after a period from one run
/// to the next.
fn smart_spaces(text: &str, after: &mut Option<usize>, n: &mut usize) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match (c, *after) {
(' ', Some(k)) => {
*after = Some(k + 1);
if k >= 1 {
if k == 1 {
*n += 1;
}
continue;
}
}
('.', _) => *after = Some(0),
_ => *after = None,
}
out.push(c);
}
match quotes {
Some(q) => q.apply(&s, prev),
out
}
/// The fraction `cs` starts with, and its length in characters: one of [`FRACTIONS`] that no digit,
/// slash or decimal part follows, so `1/25`, `1/2/2026` and `1/2.5` are left as they are. A digit
/// counts in any script.
fn fraction_at(cs: &[char]) -> Option<(usize, char)> {
FRACTIONS.iter().find_map(|(text, f)| {
let len = text.chars().count();
if cs.len() < len || !cs[..len].iter().copied().eq(text.chars()) {
return None;
}
let ends = match &cs[len..] {
[c, ..] if c.is_numeric() || *c == '/' => false,
['.' | ',', d, ..] if d.is_numeric() => false,
_ => true,
};
ends.then_some((len, *f))
})
}
/// Expert Fractions: `text` with each fraction [`fraction_at`] finds, and no digit, slash or
/// decimal point before, written as one character when `covers` it. `prev` is the character before
/// `text`, and `next` the two characters after it (in the next runs), so a fraction at the end of
/// a run is checked against what follows it.
fn expert_fractions(text: &str, prev: Option<char>, next: [Option<char>; 2], covers: &mut impl FnMut(char) -> bool, n: &mut usize) -> String {
let mut cs: Vec<char> = text.chars().collect();
let len_text = cs.len();
cs.extend(next.into_iter().flatten());
let mut out = String::with_capacity(text.len());
let mut i = 0;
while i < len_text {
let before = if i == 0 { prev } else { Some(cs[i - 1]) };
let free = !before.is_some_and(|c| c.is_numeric() || matches!(c, '/' | '.' | ','));
let found = fraction_at(&cs[i..]).filter(|(len, f)| i + len <= len_text && covers(*f));
if free && let Some((len, f)) = found {
out.push(f);
*n += 1;
i += len;
continue;
}
out.push(cs[i]);
i += 1;
}
out
}
/// The ligatures and their letters, longest first, with whether each comes with the ff, fi, ffi
/// option (else with the ff, fl, ffl option). ff comes with both.
const LIGATURES: [(&str, char, bool); 5] =
[("ffi", '\u{FB03}', true), ("ffl", '\u{FB04}', false), ("ff", '\u{FB00}', true), ("fi", '\u{FB01}', true), ("fl", '\u{FB02}', false)];
/// The ligature options: `text` with the letters of each ligature an option `o` asks for written
/// as the ligature, the longest first, when `covers` it.
fn ligatures(text: &str, o: &Punct, covers: &mut impl FnMut(char) -> bool, n: &mut PunctCounts) -> String {
let cs: Vec<char> = text.chars().collect();
let mut out = String::with_capacity(text.len());
let mut i = 0;
while i < cs.len() {
let found = (cs[i] == 'f').then(|| {
LIGATURES.iter().find(|(letters, lig, fi)| {
let on = if *letters == "ff" {
o.fi_ligatures || o.fl_ligatures
} else if *fi {
o.fi_ligatures
} else {
o.fl_ligatures
};
let len = letters.chars().count();
on && cs.len() - i >= len && cs[i..i + len].iter().copied().eq(letters.chars()) && covers(*lig)
})
});
if let Some(&(letters, lig, fi)) = found.flatten() {
out.push(lig);
// ff counts with the ff, fi, ffi option when that option is on.
if fi && (letters != "ff" || o.fi_ligatures) {
n.fi_ligatures += 1;
} else {
n.fl_ligatures += 1;
}
i += letters.chars().count();
continue;
}
out.push(cs[i]);
i += 1;
}
out
}
/// One run's text with the replacements `o` asks for, counted in `n`. Ligatures and fractions are
/// written only where the run's font has a glyph for them. `next` holds the two characters after
/// the run.
fn smarten(text: &str, style: &CharStyle, next: [Option<char>; 2], o: &Punct, st: &mut PunctState, n: &mut PunctCounts) -> String {
let mut s = if o.spaces { smart_spaces(text, &mut st.after_period, &mut n.spaces) } else { text.to_string() };
if o.dashes {
s = replace_counted(s, "---", "—", &mut n.dashes);
s = replace_counted(s, "--", "–", &mut n.dashes);
}
if o.ellipses {
s = replace_counted(s, "...", "…", &mut n.ellipses);
}
// The run's font, looked up once and only for a ligature or a fraction.
let mut face = None;
let mut covers = |c: char| {
face.get_or_insert_with(|| {
vectorcraft_text::FontDb::global().face_version(&style.font_family, &style.font_style, style.font_version.as_deref())
})
.as_ref()
.is_some_and(|f| f.covers(c))
};
if o.fractions && s.contains('/') {
let before = if st.after_graphic { None } else { st.prev };
s = expert_fractions(&s, before, next, &mut covers, &mut n.fractions);
}
st.after_graphic = false;
if (o.fi_ligatures || o.fl_ligatures) && s.contains('f') {
s = ligatures(&s, o, &mut covers, n);
}
match &o.quotes {
Some(q) => {
let out = q.apply(&s, &mut st.prev);
n.quotes += s.chars().zip(out.chars()).filter(|(a, b)| a != b).count();
out
}
None => {
*prev = s.chars().last().or(*prev);
st.prev = s.chars().last().or(st.prev);
s
}
}
@@ -293,12 +496,20 @@ pub(crate) fn smarten(text: &str, prev: &mut Option<char>, quotes: Option<&Quote
fn smart_punctuation(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.smartPunctuation";
let (d, e) = (switch_or(p, "dashes", true, C)?, switch_or(p, "ellipsis", true, C)?);
let quotes = switch_or(p, "quotes", true, C)?;
let mut o = Punct {
fi_ligatures: switch_or(p, "fiLigatures", false, C)?,
fl_ligatures: switch_or(p, "flLigatures", false, C)?,
quotes: None,
spaces: switch_or(p, "spaces", false, C)?,
dashes: switch_or(p, "dashes", true, C)?,
ellipses: switch_or(p, "ellipsis", true, C)?,
fractions: switch_or(p, "fractions", false, C)?,
};
let document = choice(p, C, "scope", &["selection", "document"])? == Some("document");
let st = s.doc()?;
// Quotes in the document's style (Document Setup → Type).
let q = quotes.then_some(st.doc.setup.quotes);
o.quotes = quotes.then_some(st.doc.setup.quotes);
let ids = if document || st.selection.is_empty() {
let mut v = vec![];
st.doc.walk(|n| {
@@ -310,8 +521,93 @@ fn smart_punctuation(s: &mut Session, p: &Value) -> Result<Value> {
} else {
text_ids(&st.doc, &st.selection.objects)
};
let n = edit_runs::<PunctState>(s, "Smart Punctuation", &ids, |text, st| smarten(text, &mut st.prev, q.as_ref(), d, e))?;
Ok(json!({ "changed": n }))
let mut n = PunctCounts::default();
let changed = super::overprint::edit_counted(s, "Smart Punctuation", |d| {
let mut changed = 0;
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
let mut st = PunctState::default();
let mut any = false;
// The ruby spans' ends, in the plain text as it was. Each run is rewritten in pieces
// between them, so no replacement crosses one, and `moved` records where each end and
// each run's start lands in the new text.
let mut edges: Vec<usize> = t.ruby.iter().flat_map(|r| [r.start, r.end]).collect();
edges.sort_unstable();
edges.dedup();
let mut moved = vec![];
let (mut old_at, mut new_at) = (0, 0);
// Inline graphics are art, not characters to rewrite. Each run sees the first two
// characters of the runs after it, up to the next inline graphic, as they were.
for i in 0..t.runs.len() {
let len = t.runs[i].text.len();
moved.push((old_at, new_at));
if t.runs[i].inline.is_some() {
// A graphic separates the characters on either side of it for Smart Spaces and
// Expert Fractions; quotes still read the character before it.
st.after_period = None;
st.after_graphic = true;
(old_at, new_at) = (old_at + len, new_at + len);
continue;
}
let mut after = t.runs[i + 1..].iter().take_while(|r| r.inline.is_none()).flat_map(|r| r.text.chars());
let following = [after.next(), after.next()];
// Smart Spaces counts no space across a ruby span's end, so it removes no space on
// the other side of one.
if edges.binary_search(&old_at).is_ok() {
st.after_period = None;
}
let r = &mut t.runs[i];
let mut cuts: Vec<usize> =
edges.iter().filter(|&&e| e > old_at && e < old_at + len && r.text.is_char_boundary(e - old_at)).map(|e| e - old_at).collect();
cuts.push(len);
let mut new = String::with_capacity(len);
let mut from = 0;
for cut in cuts {
if from > 0 {
moved.push((old_at + from, new_at + new.len()));
st.after_period = None;
}
let mut after = r.text[cut..].chars().chain(following.into_iter().flatten());
let next = [after.next(), after.next()];
new.push_str(&smarten(&r.text[from..cut], &r.style, next, &o, &mut st, &mut n));
from = cut;
}
(old_at, new_at) = (old_at + len, new_at + new.len());
if new != r.text {
r.text = new;
any = true;
}
}
moved.push((old_at, new_at));
if any {
changed += 1;
// Each ruby end moves with the text before it; an end inside a character keeps its
// distance from the last place recorded before it.
let to_new = |v: usize| {
let k = moved.partition_point(|&(old, _)| old <= v).saturating_sub(1);
moved.get(k).map_or(v, |&(old, new)| new + (v - old.min(v)))
};
for span in &mut t.ruby {
(span.start, span.end) = (to_new(span.start), to_new(span.end));
}
t.normalize_ruby();
refresh_bounds(t);
}
}
Ok(changed)
})?;
Ok(json!({
"changed": changed,
"replaced": {
"fiLigatures": n.fi_ligatures,
"flLigatures": n.fl_ligatures,
"quotes": n.quotes,
"spaces": n.spaces,
"dashes": n.dashes,
"ellipses": n.ellipses,
"fractions": n.fractions,
},
}))
}
// ---------- Area / Point conversion ----------
+4 -4
View File
@@ -222,11 +222,11 @@ pub fn written_elsewhere(path: &str) -> bool {
!cfg!(windows) && foreign && current().is_some()
}
/// Does a command param named `key` hold a file or folder path: `path`, `paths`, `file`, `files`,
/// `folder`, or a name ending in `Path`, `Paths`, `File`, `Files` or `Folder` (`diffPath`,
/// `destinationFolder`)?
/// Does a command param named `key` hold a file or folder path in a command that gives it no other
/// meaning ([`crate::cmd::key_location`]: `path`, `file`, `diffPath`, `destinationFolder` and the
/// like)? [`crate::cmd::ParamsPlace`] tells what it holds in a given command.
pub fn is_path_key(key: &str) -> bool {
matches!(key, "path" | "paths" | "file" | "files" | "folder") || ["Path", "Paths", "File", "Files", "Folder"].iter().any(|end| key.ends_with(end))
crate::cmd::key_location(key).is_some()
}
/// May `path` be written here? Always, without roots in force.
+3
View File
@@ -24,6 +24,9 @@ pub struct Interaction {
/// The perspective transform the previews make (`perspective.transform` params): Transform
/// Again repeats it once the drag is committed.
pub perspective_again: Option<Value>,
/// A preview drew an object on, or attached one to, a plane held by Automatic Plane
/// Positioning: the plane goes back to its place once the drag is committed.
pub(crate) plane_placed: bool,
/// A transform or a perspective edit with `copy` keeps the copies it made of the snapshot here
/// ([`PreviewCopies`]).
pub(crate) copies: Option<Arc<PreviewCopies>>,
+4
View File
@@ -111,6 +111,9 @@ pub struct Prefs {
pub recent_fonts_count: u32,
pub missing_glyph_protection: bool,
pub highlight_alternate_glyphs: bool,
/// Type › Show Character Alternates: with a Type tool and one character selected, the canvas
/// shows that character's alternate glyphs beside it (on by default).
pub show_character_alternates: bool,
/// Type › Highlight Substituted Fonts: on screen, text drawn in a substitute for a missing
/// font is highlighted, in every document (on by default).
pub highlight_substituted_fonts: bool,
@@ -442,6 +445,7 @@ impl Default for Prefs {
recent_fonts_count: 10,
missing_glyph_protection: true,
highlight_alternate_glyphs: false,
show_character_alternates: true,
highlight_substituted_fonts: true,
placeholder_text: true,
typed_lists: true,
+9 -4
View File
@@ -329,6 +329,8 @@ impl Session {
// Ruler guides a reader left in the saved list become nodes on their layers.
doc.guides_into_nodes();
cmd::dimension::conform(&mut doc);
// A plane held by Automatic Plane Positioning when the file was saved is back in its place.
vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(&mut doc);
self.reset_tool_for_doc_switch();
let mut st = DocState::new(doc, path);
st.history.limit = self.prefs.history_states as usize;
@@ -357,6 +359,7 @@ impl Session {
doc.resolve_inline_art();
doc.guides_into_nodes();
cmd::dimension::conform(&mut doc);
vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(&mut doc);
// In the back, type set in a font named like a composite font is measured again below, in
// the document's own composite fonts, not in the front document's.
let back = self.active != Some(index);
@@ -415,14 +418,16 @@ impl Session {
/// Measure the type not measured yet in open document `index`, which is in the back, in its own
/// composite fonts, lent for the measuring, so its type has the bounds it will have when the
/// document comes to the front. The front document stays the one whose composite fonts are
/// registered. The names of the document's composite fonts its type was measured in are kept,
/// so its coming to the front does not measure that type again.
/// document comes to the front: type naming a composite font the document does not define is
/// measured as in a missing font, also when the front document defines one of that name, and
/// also when the document defines none. The front document stays the one whose composite fonts
/// are registered. The names of the document's composite fonts its type was measured in are
/// kept, so its coming to the front does not measure that type again.
fn measure_back_document(&mut self, index: usize) {
let Some(st) = self.docs.get(index) else { return };
let fonts = st.doc.composite_fonts.clone();
let db = vectorcraft_text::FontDb::global();
let lent = db.lend_composite_fonts(&fonts);
let lent = db.lend_document_composite_fonts(&fonts);
// A name another loan holds with a different definition is not lent: type set in it is
// measured again when the document comes to the front.
let own: HashSet<String> =
+9
View File
@@ -289,6 +289,7 @@ impl Session {
variables_highlight: st.variables_highlight.clone(),
isolation: st.isolation,
perspective_again: None,
plane_placed: false,
copies: None,
move_box: std::sync::OnceLock::new(),
});
@@ -319,6 +320,7 @@ impl Session {
it.preview_paint = None;
it.color_mode_paints = None;
it.deferred_color_mode = None;
it.plane_placed = false;
if selection_changed {
st.selection.clone_from(&it.selection);
}
@@ -378,6 +380,7 @@ impl Session {
after.clone_from(&paint);
}
let perspective_again = it.perspective_again.take();
let plane_placed = it.plane_placed;
let copy = preview.0 == "object.transform" && preview.1.get("copy").and_then(Value::as_bool).unwrap_or(false);
// Alt pressed or released during a move drag turns it into a copy or back: name it for
// what it did in the end.
@@ -395,6 +398,12 @@ impl Session {
preview.1.get("dy").and_then(Value::as_f64).unwrap_or(0.0),
);
st.keep_interaction(it);
// The drag drew an object on, or attached one to, the plane Automatic Plane Positioning
// held: the plane is back in its place now, as view state (undoing the drag holds it again).
if plane_placed && changed && vectorcraft_tools::distort::perspective::PerspectiveGrid::positioning(&st.doc) {
vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(Arc::make_mut(&mut st.doc));
st.revision += 1;
}
if preview.0 == "object.transform" && changed {
let m = cmd::matrix_param(&preview.1, "matrix");
if let Some(m) = m {
+1
View File
@@ -128,6 +128,7 @@ mod pdffidelity;
mod pdfmarks;
mod pdfpresets;
mod pdfraster;
mod persp_infer;
mod persp_planes;
pub(super) mod persp_select;
mod persp_text;
+36
View File
@@ -301,6 +301,42 @@ fn an_export_preset_sets_the_shared_settings() {
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["prefix"], "p_");
}
/// `openLocation` (Open Location after Export) is remembered in the document's export settings,
/// outside presets; null removes it, and only true or false is taken.
#[test]
fn open_location_is_remembered_in_the_export_settings() {
let mut s = session();
let open = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["openLocation"].clone();
let r = run(&mut s, "assets.settings.set", json!({"openLocation": false}));
assert_eq!(open(&mut s), false);
assert!(r["settings"].get("openLocation").is_none(), "{r}");
// Create Sub-folders, on for a document without settings, stays on.
assert_eq!(r["settings"]["subfolders"], true, "{r}");
run(&mut s, "document.exportPresets.save", json!({"name": "Kept", "settings": {"formats": [{"format": "svg"}]}}));
run(&mut s, "assets.settings.set", json!({"exportPreset": "Kept"}));
assert_eq!(open(&mut s), false, "a preset leaves it as it is");
run(&mut s, "assets.settings.set", json!({"openLocation": null}));
assert_eq!(open(&mut s), Value::Null);
for bad in [json!({"openLocation": "yes"}), json!({"openLocation": 1}), json!({"subfolders": "no"})] {
assert!(s.execute("assets.settings.set", &bad).is_err(), "{bad}");
}
}
/// Create Sub-folders turned off on its own ends a remembered folder per format or item, so Export
/// for Screens opens with it off too; given with an export preset, the preset's folders stay.
#[test]
fn create_sub_folders_off_alone_ends_a_folder_per_format_or_item() {
let mut s = session();
let folders = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["folders"].clone();
run(&mut s, "document.exportPresets.save", json!({"name": "Items", "settings": {"formats": [{"format": "svg"}], "folders": "item"}}));
for preset in ["Logo Package", "Items"] {
run(&mut s, "assets.settings.set", json!({"exportPreset": preset, "subfolders": false}));
assert_ne!(folders(&mut s), "none", "{preset}");
run(&mut s, "assets.settings.set", json!({"subfolders": false}));
assert_eq!(folders(&mut s), "none", "{preset}");
}
}
/// An export preset applied to the shared settings keeps its folders, with Create Sub-folders on
/// for a folder per row; with Create Sub-folders off every file goes into the folder itself,
/// mobile and density rows too.
+209
View File
@@ -1490,6 +1490,93 @@ fn shape_builder_open_filled_paths_cut_without_open_filled_as_closed() {
assert!((area(&s, NodeId(r["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6);
}
/// The fill rows of an open path's appearance (bottom first) for the open-path tests below, with
/// a 1 pt black stroke on top: a painted fill under an unpainted top fill, a painted fill that is
/// hidden, one with an opacity of 0, and a painted fill under a hidden painted top fill.
fn open_path_fill_stacks() -> [(&'static str, Vec<AppearanceItem>, bool); 4] {
use vectorcraft_doc::{FillLayer, StrokeLayer};
let fill = |p: Paint, visible: bool, opacity: f32| {
let mut f = FillLayer::new(p);
f.visible = visible;
f.opacity = opacity;
AppearanceItem::Fill(f)
};
let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let blue = || Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let stroke = || AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0));
[
("a painted fill under an unpainted top fill", vec![fill(red(), true, 1.0), fill(Paint::None, true, 1.0), stroke()], true),
("a hidden painted fill", vec![fill(red(), false, 1.0), stroke()], false),
("a painted fill with an opacity of 0", vec![fill(red(), true, 0.0), stroke()], false),
("a painted fill under a hidden painted top fill", vec![fill(red(), true, 1.0), fill(blue(), false, 1.0), stroke()], true),
]
}
/// Consider Open Filled Paths as Closed: an open path counts as filled when any of its fill rows
/// draws (shown, painted and above 0% opacity), whichever row is on top. The map, a merge inside
/// the area and what a merge keeps of the path follow the rows that draw; with the option off, none
/// of the paths closes.
#[test]
fn shape_builder_closes_open_paths_by_the_fill_rows_that_draw() {
for (what, items, closes) in open_path_fill_stacks() {
let mut s = session();
let r = s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap();
let p = NodeId(r["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(p).unwrap().appearance.items = items;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
let r = s.execute("shapeBuilder.regions", &json!({})).unwrap();
assert_eq!(
(r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()),
if closes { (1, 0) } else { (0, 1) },
"{what}: {r}"
);
let r = s.execute("shapeBuilder.regions", &json!({"openFilledAsClosed": false})).unwrap();
assert_eq!((r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()), (0, 1), "{what}, option off: {r}");
let n = node(&s, p);
for on in [true, false] {
let inputs = vectorcraft_tools::builder::merge_inputs(&[&n], on);
assert_eq!(inputs.iter().map(|i| i.fill_closes).collect::<Vec<_>>(), vec![closes && on], "{what}, option {on}");
}
let merged = s.execute("shapeBuilder.merge", &json!({"points": [[75, 25]]}));
if closes {
assert!((area(&s, NodeId(merged.unwrap()["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6, "{what}");
} else {
assert!(merged.is_err(), "{what}: the open path encloses no region");
}
}
}
/// Clicking Stroke Splits the Path on the middle side of an open U cuts it along the outline its
/// drawn fill closes: with a fill row that draws, what is left runs on from the cut round the
/// implied closing edge (the top side, then the bottom side); without one, what is left is the
/// open path's two ends in path order (the bottom side, then the top side).
#[test]
fn shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw() {
for (what, items, closes) in open_path_fill_stacks() {
let mut s = session();
let r =
s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 0, "y": 100}]})).unwrap();
let p = NodeId(r["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(p).unwrap().appearance.items = items;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
let r = s.execute("shapeBuilder.merge", &json!({"points": [[101, 50]], "splitStroke": true})).unwrap();
let out = ids(&r);
assert_eq!(shapes_of(&s, &out), vec![(false, 4, 200.0), (false, 2, 100.0)], "{what}");
let (rest, _) = outline(&node(&s, out[0]));
let starts: Vec<(f64, f64)> = rest.subpaths.iter().map(|sp| (sp.anchors[0].p.x.round(), sp.anchors[0].p.y.round())).collect();
let order = if closes { vec![(100.0, 100.0), (0.0, 0.0)] } else { vec![(0.0, 0.0), (100.0, 100.0)] };
assert_eq!(starts, order, "{what}");
}
}
/// Pick Color From Color Swatches: the merged shape takes the current fill, not the fill of the
/// object under the first point; setting the current fill without `ids` leaves the selection's.
#[test]
@@ -3018,6 +3105,76 @@ fn live_paint_expand_keeps_the_faces_and_edges_that_draw() {
assert_eq!(rows(&n, lower_stroke), rows(&before, lower_stroke));
}
/// `livePaint.info` lists every fill and stroke row of each face and edge, bottom first, and says
/// which rows draw by Expand's rule, while `fill`, `stroke` and `width` stay the top rows.
#[test]
fn live_paint_info_lists_every_appearance_row() {
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 blue = || Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let green = || Paint::solid(Color::rgb(0.0, 1.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 faded = |mut i: AppearanceItem, o: f32| {
match &mut i {
AppearanceItem::Fill(f) => f.opacity = o,
AppearanceItem::Stroke(st) => st.opacity = o,
}
i
};
let mut s = session();
let g = live(&mut s);
// A drawn lower fill and a half-opaque stroke under an unpainted top fill.
let lower = set_live_part(&mut s, g, Some((25.0, 50.0)), None, vec![fill(red()), faded(stroke(blue(), 2.0), 0.5), fill(Paint::None)], 1.0);
let quiet = set_live_part(&mut s, g, Some((125.0, 50.0)), None, vec![hidden(fill(red())), faded(fill(red()), 0.0)], 1.0);
let bare = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![], 1.0);
// Two strokes with a fill between them.
let two = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![stroke(red(), 4.0), fill(green()), stroke(blue(), 2.0)], 1.0);
let thin = set_live_part(&mut s, g, None, Some((100.0, 50.0)), vec![stroke(red(), 0.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 hidden_edge = set_live_part(&mut s, g, None, Some((150.0, 50.0)), vec![stroke(red(), 2.0)], 1.0);
s.edit("t", |d, _| {
d.node_mut(hidden_edge).unwrap().visible = false;
Ok(())
})
.unwrap();
let parts = [lower, quiet, bare, two, thin, clear_edge, hidden_edge];
assert_eq!(parts.iter().collect::<std::collections::HashSet<_>>().len(), parts.len());
let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap();
let part = |key: &str, id: NodeId| info[key].as_array().unwrap().iter().find(|p| p["id"] == id.0).unwrap().clone();
let fill_row = |i: usize, p: Paint, o: f64, v: bool, drawn: bool| json!({"index": i, "kind": "fill", "paint": p.label(), "opacity": o, "visible": v, "drawn": drawn});
let stroke_row = |i: usize, p: Paint, o: f64, v: bool, w: f64, drawn: bool| json!({"index": i, "kind": "stroke", "paint": p.label(), "opacity": o, "visible": v, "width": w, "drawn": drawn});
let f = part("faces", lower);
assert_eq!(f["fill"], json!(Paint::None.label()), "fill stays the top fill");
assert!(f["bounds"].is_array());
assert_eq!(
f["appearance"],
json!([fill_row(0, red(), 1.0, true, true), stroke_row(1, blue(), 0.5, true, 2.0, true), fill_row(2, Paint::None, 1.0, true, false)])
);
assert_eq!(part("faces", quiet)["appearance"], json!([fill_row(0, red(), 1.0, false, false), fill_row(1, red(), 0.0, true, false)]));
assert_eq!(part("faces", bare)["appearance"], json!([]));
let e = part("edges", two);
assert_eq!((e["stroke"].clone(), e["width"].clone()), (json!(blue().label()), json!(2.0)), "stroke and width stay the top stroke's");
assert_eq!(
e["appearance"],
json!([stroke_row(0, red(), 1.0, true, 4.0, true), fill_row(1, green(), 1.0, true, true), stroke_row(2, blue(), 1.0, true, 2.0, true)])
);
assert_eq!(part("edges", thin)["appearance"], json!([stroke_row(0, red(), 1.0, true, 0.0, false)]));
for id in [clear_edge, hidden_edge] {
assert_eq!(part("edges", id)["appearance"], json!([stroke_row(0, red(), 1.0, true, 2.0, false)]), "a part that is not shown draws no row");
}
}
/// Merge carries a face's whole appearance when one of its rows draws, and carries nothing from a
/// face that draws nothing.
#[test]
@@ -4035,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() {
+32 -7
View File
@@ -1034,14 +1034,39 @@ fn in_place_pastes_put_a_copy_on_each_artboard_named() {
// `artboard` wins over `artboards`.
let ids = ids_of(&s.execute(cmd, &json!({"artboard": 2, "artboards": [0, 3]})).unwrap());
assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[2].x0 + 10.0, boards[2].y0 + 5.0), "{cmd}");
// A list that is empty, names an artboard the document lacks or names one twice, or isn't a
// list: an error, and nothing pasted.
let before = doc(&s).clone();
for bad in [json!([]), json!([0, 4]), json!([1, 1]), json!([0, -1]), json!(2), json!("0,1")] {
assert!(s.execute(cmd, &json!({"artboards": bad})).is_err(), "{cmd} with artboards {bad}");
// A list that is empty, names an artboard the document lacks or names one twice, holds a
// value that is not a whole number, or isn't a list, and an `artboard` that is not a whole
// number or not an artboard: an error naming the fault, and nothing pasted. Both keys are
// checked when both are given.
let (before, undo) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
let (not_list, missing, not_whole) = (
"`artboards` must be a list of artboard indices",
"`artboards` names an artboard the document does not have",
"`artboards` must contain whole numbers",
);
let cases = [
(json!({"artboards": []}), not_list),
(json!({"artboards": 2}), not_list),
(json!({"artboards": "0,1"}), not_list),
(json!({"artboards": [0, 4]}), missing),
(json!({"artboards": [1, 1]}), "`artboards` names an artboard twice"),
(json!({"artboards": [0, -1]}), not_whole),
(json!({"artboards": [0, 1.5]}), not_whole),
(json!({"artboards": [4, "1"]}), not_whole),
(json!({"artboard": 1, "artboards": [7]}), missing),
(json!({"artboard": 1, "artboards": ["1"]}), not_whole),
(json!({"artboard": 4}), "`artboard` must be the index of an artboard of the document"),
(json!({"artboard": -1}), "`artboard` must be a whole number"),
(json!({"artboard": 1.5}), "`artboard` must be a whole number"),
(json!({"artboard": "1"}), "`artboard` must be a whole number"),
(json!({"artboard": null}), "`artboard` must be a whole number"),
(json!({"artboard": "1", "artboards": [9]}), "`artboard` must be a whole number"),
];
for (p, want) in cases {
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert_eq!(e, format!("invalid parameters for `{cmd}`: {want}"), "{cmd} {p}");
}
assert!(s.execute(cmd, &json!({"artboard": 1, "artboards": [7]})).is_err(), "{cmd}: a bad list with `artboard`");
assert_eq!(doc(&s), &before, "{cmd}");
assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, undo), "{cmd}");
}
}
+254
View File
@@ -2023,6 +2023,260 @@ fn smoothing_leaves_paths_out_of_reach_and_straight_segments_alone() {
assert_eq!(path(&s, line), before);
}
/// The turn, in degrees, of `sp` at each of its anchors: round a closed path, and 0 at an open
/// path's first and last anchors.
fn smooth_anchor_turns(sp: &vectorcraft_geom::SubPath) -> Vec<f64> {
let (n, segs) = (sp.anchors.len(), sp.segment_count());
(0..n)
.map(|i| {
if segs == 0 || !sp.closed && (i == 0 || i == n - 1) {
return 0.0;
}
let (a, b) = (sp.segment((i + segs - 1) % segs), sp.segment(i % segs));
let tin = [a.p3 - a.p2, a.p3 - a.p1, a.p3 - a.p0].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or_default();
let tout = [b.p1 - b.p0, b.p2 - b.p0, b.p3 - b.p0].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or_default();
tin.cross(tout).atan2(tin.dot(tout)).abs().to_degrees()
})
.collect()
}
/// The turn of `sp` at its anchor on `at`, `None` when no anchor is there.
fn smooth_turn_at(sp: &vectorcraft_geom::SubPath, at: Point) -> Option<f64> {
let i = sp.anchors.iter().position(|a| a.p.distance(at) < 1e-9)?;
smooth_anchor_turns(sp).get(i).copied()
}
/// An open polyline with a corner at (300, 300) whose angle inside is `inside` degrees: a 100 pt
/// leg along y = 300 from the left, then a 100 pt leg turning by 180 - `inside` degrees, each leg cut
/// into `per_leg` segments. Returns the path, the corner, and a drag along the path from 40 pt
/// before the corner to 40 pt after it.
fn smooth_corner_path(s: &mut Session, inside: f64, per_leg: usize) -> (NodeId, Point, Vec<Point>) {
let v = Point::new(300.0, 300.0);
let d = kurbo::Vec2::from_angle(-(180.0 - inside).to_radians());
let back = kurbo::Vec2::new(-100.0, 0.0);
let legs = per_leg as f64;
let mut pts: Vec<Point> = (0..per_leg).map(|k| v + back * (1.0 - k as f64 / legs)).collect();
pts.extend((0..=per_leg).map(|k| v + d * (100.0 * k as f64 / legs)));
let anchors: Vec<_> = pts.iter().map(|p| json!({"x": p.x, "y": p.y})).collect();
let id = smooth_test_path(s, &anchors, false);
let mut drag: Vec<Point> = (0..8).map(|k| v - kurbo::Vec2::new(40.0 - 5.0 * f64::from(k), 0.0)).collect();
drag.extend((0..=8).map(|k| v + d * (5.0 * f64::from(k))));
(id, v, drag)
}
/// A Smooth drag over a corner keeps it where the path turns there by more than 57.5° (an angle
/// inside the corner under 122.5°), whether each leg is one segment or ten and at any Fidelity. A
/// wider corner is not kept: when the drag changes the path, no anchor is left turning as sharply
/// there, and a leg of ten segments at the default Fidelity always rounds it.
#[test]
fn the_smooth_tool_keeps_corners_sharper_than_its_threshold() {
let mut wrong = vec![];
for inside in [30.0f64, 60.0, 90.0, 120.0, 122.4, 122.6, 125.0, 135.0, 150.0, 170.0] {
let kept = inside < 122.5;
for per_leg in [1, 10] {
for fidelity in [0.5, 2.5, 10.0] {
let mut s = session();
let (id, v, drag) = smooth_corner_path(&mut s, inside, per_leg);
let before = path(&s, id);
let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect();
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": fidelity})).unwrap();
let p = path(&s, id);
let turn = 180.0 - inside;
let at = smooth_turn_at(&p.subpaths[0], v);
let changed = p != before;
let rounded = changed && at.is_none_or(|t| t < turn - 1.0);
let right = if kept { at.is_some_and(|t| (t - turn).abs() < 0.01) } else { rounded || !changed && per_leg == 1 };
let most = smooth_anchor_turns(&p.subpaths[0]).into_iter().fold(0.0, f64::max);
if !right || !kept && most > 57.5 || !kept && per_leg == 10 && fidelity == 2.5 && !rounded {
wrong.push(format!(
"{inside}° inside, {per_leg} segments a leg, Fidelity {fidelity}: turn {at:?}, changed {changed}, sharpest {most}°"
));
}
}
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// Three Smooth drags over a 90° and a 120° corner leave the corner where it was and as sharp, while
/// the first one smooths a wobble on the same leg.
#[test]
fn smooth_drags_again_and_again_keep_a_corner_in_place() {
for inside in [90.0f64, 120.0] {
let mut s = session();
let v = Point::new(300.0, 300.0);
let d = kurbo::Vec2::from_angle(-(180.0 - inside).to_radians());
let mut anchors: Vec<_> = (0..=18).map(|k| json!({"x": 180.0 + 5.0 * f64::from(k), "y": if k % 2 == 1 { 301.5 } else { 300.0 }})).collect();
anchors.push(json!({"x": v.x, "y": v.y}));
let c = v + d * 100.0;
anchors.push(json!({"x": c.x, "y": c.y}));
let id = smooth_test_path(&mut s, &anchors, false);
let mut drag = smooth_drag_along(300.0, 175.0, 300.0);
drag.extend((1..=8).map(|k| v + d * (5.0 * f64::from(k))));
let mut before = path(&s, id);
for pass in 1..=3 {
smooth_pass(&mut s, &drag);
let p = path(&s, id);
let at = smooth_turn_at(&p.subpaths[0], v);
assert!(at.is_some_and(|t| (t - (180.0 - inside)).abs() < 0.01), "{inside}°, pass {pass}: {at:?}");
if pass == 1 {
assert!(p.anchor_count() < before.anchor_count(), "{inside}°: the wobble is smoothed: {} anchors", p.anchor_count());
assert!(total_turning(&p) < total_turning(&before), "{inside}°: the path turns less");
}
before = p;
}
}
}
/// A Smooth drag along a line with 1 pt jags, each turning by 90°, smooths them all: none is kept
/// as a corner, since the line hardly turns over the tool's reach.
#[test]
fn smoothing_keeps_no_small_jag_as_a_corner() {
let mut s = session();
let anchors: Vec<_> = (0..=200).map(|i| json!({"x": 100.0 + f64::from(i), "y": if i % 2 == 1 { 201.0 } else { 200.0 }})).collect();
let id = smooth_test_path(&mut s, &anchors, false);
assert!(smooth_anchor_turns(&path(&s, id).subpaths[0]).iter().skip(1).take(199).all(|t| (t - 90.0).abs() < 1e-6));
smooth_pass(&mut s, &smooth_drag_along(200.5, 90.0, 310.0));
let p = path(&s, id);
let sp = &p.subpaths[0];
assert!(sp.anchors.len() < 50, "the jags are smoothed: {} anchors", sp.anchors.len());
let most = smooth_anchor_turns(sp).into_iter().fold(0.0, f64::max);
assert!(most <= 57.5, "a jag is kept, turning {most}°");
}
/// A closed path with 90° corners at (200, 200), where it starts, and at (400, 200), 75° ones at
/// (400, 400) and (200, 400), a 30° bend at (300, 426.79), and a top side jagged by 1 pt. With
/// `from_bend` the path starts at the bend instead.
fn smooth_house(s: &mut Session, from_bend: bool) -> (NodeId, [Point; 4], Point) {
let corners = [Point::new(200.0, 200.0), Point::new(400.0, 200.0), Point::new(400.0, 400.0), Point::new(200.0, 400.0)];
let bend = Point::new(300.0, 400.0 + 100.0 / 75f64.to_radians().tan());
let mut anchors = vec![json!({"x": 200.0, "y": 200.0})];
anchors.extend((1..40).map(|k| json!({"x": 200.0 + 5.0 * f64::from(k), "y": if k % 2 == 1 { 201.0 } else { 200.0 }})));
for p in [corners[1], corners[2], bend, corners[3]] {
anchors.push(json!({"x": p.x, "y": p.y}));
}
if from_bend {
let at_bend = anchors.len() - 2;
anchors.rotate_left(at_bend);
}
(smooth_test_path(s, &anchors, true), corners, bend)
}
/// A Smooth drag round the whole of a closed path, and one along its top side only, keep its corners,
/// the one where the path starts included, and smooth the jags; the path still starts where it did,
/// at a corner or at the bend, which the refit keeps, and the bend out of the second drag's reach
/// stays as it was.
#[test]
fn smoothing_a_closed_path_keeps_its_corners() {
let turns: Vec<f64> = {
let mut s = session();
let (id, corners, _) = smooth_house(&mut s, false);
corners.iter().map(|c| smooth_turn_at(&path(&s, id).subpaths[0], *c).unwrap()).collect()
};
for from_bend in [false, true] {
let mut s = session();
let (id, corners, bend) = smooth_house(&mut s, from_bend);
let before = path(&s, id);
let mut ring: Vec<Point> = vec![];
for (a, b) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], bend), (bend, corners[3]), (corners[3], corners[0])] {
let n = (a.distance(b) / 5.0).ceil();
ring.extend((0..n as usize).map(|k| a.lerp(b, k as f64 / n)));
}
ring.push(corners[0]);
smooth_pass(&mut s, &ring);
let p = path(&s, id);
let sp = &p.subpaths[0];
assert!(sp.closed && sp.anchors.len() < before.subpaths[0].anchors.len(), "{} anchors", sp.anchors.len());
assert_eq!(sp.anchors[0].p, before.subpaths[0].anchors[0].p, "the path still starts where it did");
for (c, t) in corners.iter().zip(&turns) {
let at = smooth_turn_at(sp, *c);
assert!(at.is_some_and(|a| (a - t).abs() < 0.01), "the corner at {c:?} turning {t}° is kept: {at:?}");
}
}
let mut s = session();
let (id, corners, bend) = smooth_house(&mut s, false);
let before = path(&s, id);
smooth_pass(&mut s, &smooth_drag_along(200.0, 190.0, 410.0));
let p = path(&s, id);
let sp = &p.subpaths[0];
assert!(sp.closed && sp.anchors.len() < before.subpaths[0].anchors.len(), "the top is smoothed: {} anchors", sp.anchors.len());
for (c, t) in corners.iter().zip(&turns) {
let at = smooth_turn_at(sp, *c);
assert!(at.is_some_and(|a| (a - t).abs() < 0.01), "part of the path: the corner at {c:?} turning {t}° is kept: {at:?}");
}
assert!(smooth_turn_at(sp, bend).is_some_and(|t| (t - 30.0).abs() < 0.01), "the bend out of reach stays");
}
/// A Smooth drag over an anchor whose curved legs meet at a corner keeps the corner, taking the turn
/// from the directions the curves arrive and leave along, a handle of no length included.
#[test]
fn smoothing_keeps_a_corner_between_curves() {
use kurbo::ParamCurve;
let v = Point::new(200.0, 300.0);
let with_in = json!({"x": 200.0, "y": 300.0, "in": [170.0, 270.0], "out": [230.0, 270.0]});
let no_in = json!({"x": 200.0, "y": 300.0, "out": [230.0, 270.0]});
for (corner, first_out) in [(with_in, [130.0, 260.0]), (no_in, [170.0, 230.0])] {
let mut s = session();
let anchors = [json!({"x": 100.0, "y": 300.0, "out": first_out}), corner, json!({"x": 300.0, "y": 300.0, "in": [270.0, 260.0]})];
let id = smooth_test_path(&mut s, &anchors, false);
let before = path(&s, id);
let turn = smooth_turn_at(&before.subpaths[0], v).unwrap();
assert!(turn > 80.0, "{turn}");
let (a, b) = (before.subpaths[0].segment(0), before.subpaths[0].segment(1));
let mut drag: Vec<Point> = (0..=10).map(|k| a.eval(0.6 + 0.04 * f64::from(k))).collect();
drag.extend((1..=10).map(|k| b.eval(0.04 * f64::from(k))));
smooth_pass(&mut s, &drag);
let at = smooth_turn_at(&path(&s, id).subpaths[0], v);
assert!(at.is_some_and(|t| (t - turn).abs() < 0.01), "the corner turning {turn}° is kept: {at:?}");
}
}
/// A corner at the first anchor of the stretch a drag smooths, just out of its reach, keeps its
/// place and its turn.
#[test]
fn a_corner_at_the_end_of_the_smoothed_stretch_stays() {
let mut s = session();
let mut anchors = vec![json!({"x": 100.0, "y": 300.0}), json!({"x": 200.0, "y": 300.0})];
anchors.extend((1..=20).map(|k| json!({"x": if k % 2 == 1 { 201.0 } else { 200.0 }, "y": 300.0 - 5.0 * f64::from(k)})));
let id = smooth_test_path(&mut s, &anchors, false);
let before = path(&s, id);
let turn = smooth_turn_at(&before.subpaths[0], Point::new(200.0, 300.0)).unwrap();
let drag: Vec<Point> = (0..=19).map(|k| Point::new(200.0, 287.0 - 5.0 * f64::from(k))).collect();
smooth_pass(&mut s, &drag);
let p = path(&s, id);
let sp = &p.subpaths[0];
assert_ne!(p, before, "the jagged leg is smoothed");
assert_eq!(sp.anchors[0], before.subpaths[0].anchors[0]);
let at = smooth_turn_at(sp, Point::new(200.0, 300.0));
assert!(at.is_some_and(|t| (t - turn).abs() < 0.01), "the corner turning {turn}° stays: {at:?}");
}
/// A Smooth drag over corners it keeps, with nothing else to smooth, changes nothing and adds no
/// undo step: an open path's corner and a square's four corners.
#[test]
fn a_smooth_drag_that_only_meets_corners_adds_no_undo_step() {
let mut s = session();
let (id, v, drag) = smooth_corner_path(&mut s, 90.0, 1);
let before = path(&s, id);
let undo = s.doc().unwrap().history.undo.len();
assert_eq!(smooth_pass_ids(&mut s, &drag), json!([]), "a corner at {v:?}");
assert_eq!(path(&s, id), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
let square = [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)].map(|(x, y)| json!({"x": x, "y": y}));
let id = smooth_test_path(&mut s, &square, true);
let before = path(&s, id);
let undo = s.doc().unwrap().history.undo.len();
let mut ring = smooth_drag_along(100.0, 100.0, 200.0);
ring.extend((1..=20).map(|k| Point::new(200.0, 100.0 + 5.0 * f64::from(k))));
ring.extend(smooth_drag_along(200.0, 100.0, 200.0).into_iter().rev().skip(1));
ring.extend((1..=20).map(|k| Point::new(100.0, 200.0 - 5.0 * f64::from(k))));
assert_eq!(smooth_pass_ids(&mut s, &ring), json!([]), "a square");
assert_eq!(path(&s, id), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn join_tool_joins_two_lines() {
let mut s = session();
+164 -8
View File
@@ -4,7 +4,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_geom::{Affine, PathData, Rect};
use vectorcraft_geom::{Affine, PathData, Point, Rect};
use crate::*;
@@ -320,16 +320,16 @@ fn global_edit_needs_one_supported_object() {
let t = NodeId(s.execute("text.create", &json!({"x": 50, "y": 500, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
sel(&mut s, &[t]);
assert!(matches!(s.execute("select.globalEdit", &json!({})), Err(EngineError::Disabled(..))), "type");
let lone = rect(&mut s, 0.0, 500.0, 30.0, 70.0);
// A copy turned a quarter turn (70 × 30) is not taken: rotated copies are not matched, and the
// message says so.
let turned = rect(&mut s, 200.0, 500.0, 30.0, 70.0);
sel(&mut s, &[turned]);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
// A reflected copy is not taken, and the message says so.
let lone = kite(&mut s, 0.0, 500.0, 1.0);
let mirrored = kite(&mut s, 200.0, 500.0, 1.0);
sel(&mut s, &[mirrored]);
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
sel(&mut s, &[lone]);
let e = s.execute("select.globalEdit", &json!({})).unwrap_err().to_string();
assert!(e.contains("no similar objects") && e.contains("rotated"), "{e}");
assert!(e.contains("no similar objects") && e.contains("reflected copies are not matched") && !e.contains("rotated"), "{e}");
assert!(s.doc().unwrap().global_edit.is_none());
assert!(crate::cmd::globaledit::highlights(&s).is_empty(), "and it is not highlighted");
// A group holding type is not offered, though another such group exists.
let group = |s: &mut Session, x: f64| {
let p = rect(s, x, 100.0, 10.0, 10.0);
@@ -851,3 +851,159 @@ fn groups_nested_as_deep_as_a_document_allows_are_edited_together() {
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
assert_eq!(fill(&s, other_inner), "#12ab34");
}
/// A four-sided path with no symmetry, `k` times the size, its box's top left near (`x`, `y`): a
/// 30 × 70 rectangle whose first anchor is moved.
fn kite(s: &mut Session, x: f64, y: f64, k: f64) -> NodeId {
let id = rect(s, x, y, 30.0 * k, 70.0 * k);
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]]})).unwrap();
s.execute("path.moveAnchors", &json!({"dx": 10.0 * k, "dy": -20.0 * k})).unwrap();
id
}
/// Rotate `id` by `deg` (counter-clockwise) about the centre of its box → that rotation.
fn rotate(s: &mut Session, id: NodeId, deg: f64) -> Affine {
let c = bounds(s, id).center();
sel(s, &[id]);
s.execute("object.rotate", &json!({"angle": deg})).unwrap();
Affine::rotate_about(-deg.to_radians(), c)
}
/// A kite at the origin side of the page, a copy of it turned a quarter turn, and a copy at half
/// the size turned by 30° → the three and the transforms that lay the first on the other two.
fn turned_kites(s: &mut Session) -> ([NodeId; 3], [Affine; 2]) {
let a = kite(s, 0.0, 100.0, 1.0);
let (b, c) = (kite(s, 200.0, 100.0, 1.0), kite(s, 400.0, 100.0, 0.5));
let quarter = rotate(s, b, 90.0) * Affine::translate((200.0, 0.0));
let small = rotate(s, c, 30.0) * Affine::translate((400.0, 100.0)) * Affine::scale(0.5) * Affine::translate((0.0, -100.0));
assert!(placed(s, a, b, quarter) && placed(s, a, c, small), "the copies as made");
([a, b, c], [quarter, small])
}
#[test]
fn start_global_edit_takes_rotated_copies_and_an_edit_reaches_each_turned_by_its_angle() {
let mut s = session();
let ([a, b, c], [quarter, small]) = turned_kites(&mut s);
sel(&mut s, &[a]);
assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2, "both are highlighted before the start");
assert_eq!(s.execute("select.globalEditOptions", &json!({})).unwrap()["count"], 3);
assert_eq!(start(&mut s, a, json!({})), [a, b, c]);
let before = (*s.doc().unwrap().doc).clone();
let steps = s.doc().unwrap().history.undo.len();
// An anchor moved on the selected kite moves on each copy along the copy's own directions.
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]]})).unwrap();
s.execute("path.moveAnchors", &json!({"dx": 12, "dy": 5})).unwrap();
assert!(placed(&s, a, b, quarter), "the quarter-turned copy");
assert!(placed(&s, a, c, small), "the smaller copy turned by 30°");
assert!(!placed(&s, a, b, Affine::translate((200.0, 0.0))), "the copy is still turned");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
crate::tests_large_edits::undo_gives_back(&mut s, &before);
// A move of the whole kite to the right moves the quarter-turned copy up (counter-clockwise).
sel(&mut s, &[a]);
let was = bounds(&s, b);
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
let now = bounds(&s, b);
assert!((now.x0 - was.x0).abs() < 1e-6 && (now.y0 - (was.y0 - 10.0)).abs() < 1e-6, "{was:?} → {now:?}");
assert!(placed(&s, a, b, quarter) && placed(&s, a, c, small), "each copy lies on the kite as before");
}
#[test]
fn a_rotated_copy_leads_an_edit_as_any_other_member_does() {
let mut s = session();
let ([a, b, c], [quarter, small]) = turned_kites(&mut s);
// Started on the turned copy, and edited from the smaller one.
assert_eq!(start(&mut s, b, json!({})), [b, a, c]);
s.execute("select.anchors", &json!({"id": c.0, "anchors": [[0, 2]]})).unwrap();
s.execute("path.moveAnchors", &json!({"dx": 3, "dy": -4})).unwrap();
assert!(placed(&s, a, b, quarter) && placed(&s, a, c, small));
// A fill reaches the turned copies as it is.
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
assert_eq!((fill(&s, a), fill(&s, b)), ("#12ab34".to_string(), "#12ab34".to_string()));
}
#[test]
fn size_takes_a_rotated_copy_of_the_same_size_and_other_shapes_stay_out() {
let mut s = session();
let ([a, b, c], _) = turned_kites(&mut s);
// A quarter-turned copy is 70 × 30 by its box: it has the size of the 30 × 70 kite all the same.
assert_eq!(start(&mut s, a, json!({"size": true})), [a, b], "not the half-size copy {c}");
s.execute("select.globalEdit", &json!({})).unwrap();
// A copy turned and then stretched, and one whose anchor was moved, are other shapes.
let stretched = kite(&mut s, 0.0, 300.0, 1.0);
rotate(&mut s, stretched, 30.0);
s.execute("object.scale", &json!({"sx": 150, "sy": 100})).unwrap();
let bent = kite(&mut s, 200.0, 300.0, 1.0);
rotate(&mut s, bent, 45.0);
s.execute("select.anchors", &json!({"id": bent.0, "anchors": [[0, 2]]})).unwrap();
s.execute("path.moveAnchors", &json!({"dx": 1, "dy": 0})).unwrap();
// A copy turned by half a turn and by a full turn in two steps.
let half = kite(&mut s, 400.0, 300.0, 1.0);
rotate(&mut s, half, 180.0);
let full = kite(&mut s, 600.0, 300.0, 1.0);
rotate(&mut s, full, 135.0);
rotate(&mut s, full, 225.0);
assert_eq!(start(&mut s, a, json!({})), [a, b, c, half, full], "not the stretched {stretched} nor the bent {bent}");
}
#[test]
fn a_square_whose_anchors_were_turned_is_a_rotated_copy() {
let mut s = session();
let [a, b, ..] = squares(&mut s);
let turn = rotate(&mut s, b, 90.0) * Affine::translate((300.0, 0.0));
assert_eq!(start(&mut s, a, json!({})).len(), 3, "the turned square is still taken, with the small one");
// The first anchor of the turned square lies at another corner, and that is the one that moves.
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]]})).unwrap();
s.execute("path.moveAnchors", &json!({"dx": 10, "dy": 30})).unwrap();
assert!(placed(&s, a, b, turn));
assert!(!placed(&s, a, b, Affine::translate((300.0, 0.0))));
}
#[test]
fn rotated_groups_are_like_the_group_and_an_edit_inside_one_reaches_the_others_turned() {
let mut s = session();
let (g, [sq, dot, _]) = card(&mut s, 0.0, 1.0);
let (copy, [csq, cdot, cbar]) = card(&mut s, 300.0, 1.0);
let turn = rotate(&mut s, copy, 90.0) * Affine::translate((300.0, 0.0));
// The same three objects, each turned in place: not the group turned as a whole.
let (apart, objects) = card(&mut s, 500.0, 1.0);
for id in objects {
rotate(&mut s, id, 90.0);
}
assert_eq!(start(&mut s, g, json!({})), [g, copy], "not the group {apart} whose objects were turned one by one");
sel(&mut s, &[dot]);
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
assert_eq!(fill(&s, cdot), "#12ab34");
sel(&mut s, &[sq]);
s.execute("object.setBounds", &json!({"height": 20, "reference": 0})).unwrap();
assert!(placed(&s, sq, csq, turn), "the square in the turned group is halved along the group's own direction");
assert_eq!(kids(&s, copy), [csq, cdot, cbar], "each object keeps its id");
s.execute("select.globalEdit", &json!({})).unwrap();
// An object inside one group takes the object at its place in the turned group, as the
// objects of rotated copies of a group are edited together.
assert_eq!(start(&mut s, sq, json!({})), [sq, csq]);
}
#[test]
fn a_rotated_symbol_instance_is_taken_and_a_reflected_one_is_not() {
let mut s = session();
let r = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let first = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
let place =
|s: &mut Session, x: f64| NodeId(s.execute("symbol.place", &json!({"name": "Tile", "x": x, "y": 300})).unwrap()["id"].as_u64().unwrap());
let (turned, mirrored) = (place(&mut s, 200.0), place(&mut s, 400.0));
sel(&mut s, &[turned]);
s.execute("object.rotate", &json!({"angle": 30, "origin": [220, 320]})).unwrap();
sel(&mut s, &[mirrored]);
s.execute("object.reflect", &json!({"axis": "vertical", "origin": [420, 320]})).unwrap();
assert_eq!(start(&mut s, first, json!({})), [first, turned], "not the reflected instance {mirrored}");
let xf = |s: &Session, id: NodeId| match node(s, id).kind {
NodeKind::SymbolInstance { xf, .. } => xf,
_ => panic!("not an instance"),
};
let was = xf(&s, turned);
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
// The instance turned by 30° counter-clockwise moves along its own direction.
let moved = Affine::rotate((-30f64).to_radians()) * Point::new(10.0, 0.0);
let (now, want) = (xf(&s, turned).as_coeffs(), (Affine::translate(moved.to_vec2()) * was).as_coeffs());
assert!(now.iter().zip(want).all(|(p, q)| (p - q).abs() < 1e-6), "{now:?} vs {want:?}");
}
+16 -5
View File
@@ -79,18 +79,29 @@ fn the_source_stays_as_it_is() {
assert!(s.doc().unwrap().is_dirty(), "the new document is unsaved");
}
/// An index that names no state, or is not a whole number, is an error and changes nothing: no
/// document, no step and no Untitled number is used up.
/// An index that names no state (`no history state N`), or is not a whole number ("`index` must be
/// a whole number"), is an error and changes nothing: no document, no step and no Untitled number
/// is used up.
#[test]
fn a_bad_index_is_an_error_and_changes_nothing() {
let mut s = three_rectangles_one_undone();
let source = s.doc().unwrap().doc.clone();
let untitled = s.peek_untitled();
let bad: [Value; 8] = [json!(4), json!(99), json!(-1), json!(1.5), json!("1"), json!(true), json!([1]), json!(u64::MAX)];
for index in bad {
let bad: [(Value, bool); 8] = [
(json!(4), true),
(json!(99), true),
(json!(u64::MAX), true),
(json!(-1), false),
(json!(1.5), false),
(json!("1"), false),
(json!(true), false),
(json!([1]), false),
];
for (index, whole) in bad {
let e = s.execute(CMD, &json!({ "index": index })).unwrap_err();
assert!(matches!(e, EngineError::BadParams { .. }), "{index}: {e}");
assert!(e.to_string().contains(&format!("no history state {index}")), "{e}");
let want = if whole { format!("no history state {index}") } else { "`index` must be a whole number".to_string() };
assert_eq!(e.to_string(), format!("invalid parameters for `{CMD}`: {want}"), "{index}");
assert_eq!(s.documents().len(), 1, "{index}");
assert_eq!(steps(&s), (2, 1), "{index}");
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &source), "{index}");
+10 -7
View File
@@ -611,15 +611,18 @@ fn edit_copy_and_cut_read_the_recorded_artboards() {
s.execute("select.none", &json!({})).unwrap();
assert!(matches!(s.execute(id, &json!({})), Err(crate::EngineError::Disabled(..))), "{id}");
let before = documents(&s);
for bad in [
json!({"selectedArtboards": [9]}),
json!({"selectedArtboards": []}),
json!({"selectedArtboards": "1"}),
json!({"selectedArtboards": null}),
json!({"selectedArtboards": [1], "art": "yes"}),
for (bad, want) in [
(json!({"selectedArtboards": [9]}), "no such artboard"),
(json!({"selectedArtboards": []}), "`selectedArtboards` must be a non-empty list of artboard indices"),
(json!({"selectedArtboards": "1"}), "`selectedArtboards` must be a list of artboard indices"),
(json!({"selectedArtboards": null}), "`selectedArtboards` must be a list of artboard indices"),
(json!({"selectedArtboards": [1, "0"]}), "`selectedArtboards` must contain whole numbers"),
(json!({"selectedArtboards": [1, -1]}), "`selectedArtboards` must contain whole numbers"),
(json!({"selectedArtboards": [1], "art": "yes"}), "`art` must be true or false"),
] {
let err = s.execute(id, &bad).unwrap_err().to_string();
assert!(err.contains(id) || err.contains("no such artboard"), "{id} {bad}: {err}");
assert!(err.ends_with(want), "{id} {bad}: {err}");
assert!(err.contains(id) || want == "no such artboard", "{id} {bad}: {err}");
assert_eq!(documents(&s), before, "{id} {bad}");
assert!(s.clipboard.artboards.is_empty(), "{id} {bad}");
}
+36 -1
View File
@@ -248,7 +248,42 @@ fn the_list_shows_each_image_with_its_status() {
assert_eq!(run(&mut s, "links.list", json!({"show": "missing"}))["links"][0]["id"], linked.0);
assert_eq!(run(&mut s, "links.list", json!({"sort": "name"}))["links"][0]["name"], "a.png");
assert!(s.execute("links.list", &json!({"show": "broken"})).is_err());
assert!(s.execute("links.list", &json!({"sort": "size"})).is_err());
assert!(s.execute("links.list", &json!({"sort": "date"})).is_err());
}
#[test]
fn sort_by_size_lists_the_smallest_file_first() {
let dir = Folder::new("list-size");
let files = [("a.png", png(600, 300, RED)), ("b.png", png(10, 10, BLUE)), ("c.png", png(100, 100, RED)), ("d.png", png(10, 10, BLUE))];
let mut s = session();
for (name, bytes) in &files {
let path = dir.file(name);
write(&path, bytes);
place(&mut s, &path);
}
let e = dir.file("e.png");
write(&e, &png(1, 1, RED));
place_embedded(&mut s, &e);
let names = |s: &mut Session| -> Vec<String> {
let l = run(s, "links.list", json!({"sort": "size"}));
l["links"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap_or_default().to_string()).collect()
};
// Smallest first, equal sizes by name, the embedded image (no file) last.
let mut want: Vec<(usize, &str)> = files.iter().map(|(n, b)| (b.len(), *n)).collect();
want.sort();
assert!(want[0].0 < want[2].0 && want[2].0 < want[3].0, "{want:?}");
let mut want: Vec<String> = want.iter().map(|(_, n)| n.to_string()).collect();
want.push("e.png".into());
assert_eq!(names(&mut s), want);
// A missing file sorts by the size the document keeps of it.
std::fs::remove_file(dir.file("a.png")).unwrap();
assert_eq!(names(&mut s), want);
// A modified file sorts by its size now.
let bigger = png(900, 900, BLUE);
assert!(bigger.len() > files[0].1.len());
write(&dir.file("c.png"), &bigger);
let got = names(&mut s);
assert_eq!(got[got.len() - 2..], ["c.png".to_string(), "e.png".to_string()]);
}
#[test]
+160 -6
View File
@@ -1979,9 +1979,10 @@ fn fit_to_artwork_bounds_fits_each_artboard_to_its_own_art() {
assert_eq!(boards(&s), [Rect::new(100.0, 100.0, 1050.0, 280.0), was[1], was[2]], "the first artboard by default");
}
/// Artboard Options and Fit to Selected Art fail with `no such artboard` on an `index` that names
/// no artboard (past the last, negative, fractional, a string or null), and the artboards stay as
/// they were. Artboard Options needs an `index`; Fit to Selected Art without one fits the first
/// Artboard Options and Fit to Selected Art fail with `no such artboard` on a whole-number `index`
/// past the last artboard, with "`index` must be a whole number" on one that is negative,
/// fractional or a string, and with `missing index` on a null one, and the artboards stay as they
/// were. Artboard Options needs an `index`; Fit to Selected Art without one fits the first
/// artboard.
#[test]
fn artboard_options_and_fit_to_selected_art_refuse_an_index_that_names_no_artboard() {
@@ -1992,9 +1993,16 @@ fn artboard_options_and_fit_to_selected_art_refuse_an_index_that_names_no_artboa
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let (was, n) = (boards(&s), undo_len(&s));
for index in [json!(99), json!(-1), json!(1.5), json!("1"), Value::Null] {
for (index, error) in [
(json!(99), None),
(json!(-1), Some("`index` must be a whole number")),
(json!(1.5), Some("`index` must be a whole number")),
(json!("1"), Some("`index` must be a whole number")),
(Value::Null, Some("missing index")),
] {
for (cmd, p) in [("artboard.setProps", json!({"index": index, "width": 300})), ("artboard.fitToSelection", json!({"index": index}))] {
assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), "no such artboard", "{cmd} {p}");
let want = error.map_or_else(|| "no such artboard".to_string(), |e| format!("invalid parameters for `{cmd}`: {e}"));
assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), want, "{cmd} {p}");
}
}
let e = s.execute("artboard.setProps", &json!({"width": 300})).unwrap_err().to_string();
@@ -2226,6 +2234,10 @@ fn type_menu_and_find_commands_refuse_a_param_of_the_wrong_type() {
("type.smartPunctuation", json!({"dashes": "false"}), switch("dashes")),
("type.smartPunctuation", json!({"ellipsis": 0}), switch("ellipsis")),
("type.smartPunctuation", json!({"quotes": "no"}), switch("quotes")),
("type.smartPunctuation", json!({"fiLigatures": 1}), switch("fiLigatures")),
("type.smartPunctuation", json!({"flLigatures": "true"}), switch("flLigatures")),
("type.smartPunctuation", json!({"spaces": "on"}), switch("spaces")),
("type.smartPunctuation", json!({"fractions": [true]}), switch("fractions")),
("type.smartPunctuation", json!({"scope": 5}), scope.clone()),
("type.smartPunctuation", json!({"scope": "page"}), scope),
("type.changeCase", json!({"case": 5}), string("case")),
@@ -3555,12 +3567,154 @@ fn smart_punctuation_with_nothing_to_change_records_no_undo_step() {
for id in [t, r] {
select_with_a_step_to_redo(&mut s, &[id]);
let before = history(&s);
assert_eq!(s.execute("type.smartPunctuation", &json!({})).unwrap(), json!({"changed": 0}), "{id:?}");
let r = s.execute("type.smartPunctuation", &json!({})).unwrap();
assert_eq!(r["changed"], 0, "{id:?}");
assert!(r["replaced"].as_object().unwrap().values().all(|n| n == 0), "{id:?}: {r}");
assert_eq!(history(&s), before, "{id:?}");
}
assert_eq!(plain(&s, t), "“Hi” it’s 1–2 and 3—4…");
}
/// Does the face text `font` draws with have a glyph for every character of `chars`?
fn font_covers(font: &str, chars: &str) -> bool {
let face = vectorcraft_text::FontDb::global().face(font, "Regular");
face.is_some_and(|f| chars.chars().all(|c| f.covers(c)))
}
/// Every option on: the ligatures, Smart Spaces and Expert Fractions, each counted on its own, in
/// one undo step. Fractions next to a digit, a slash or a decimal part are left as they are.
#[test]
fn smart_punctuation_ligatures_spaces_and_fractions_are_counted() {
let mut s = session();
assert!(font_covers("Source Sans 3", "\u{FB00}\u{FB01}\u{FB02}\u{FB03}\u{FB04}½¾"), "Source Sans 3 draws the ligatures and fractions");
let words = "An office's fluffy flow. Then 1/2 and 3/4, not 1/25, 1/2/26 or 1/2.5.";
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
let undo = history(&s).0;
let all = json!({"fiLigatures": true, "flLigatures": true, "quotes": true, "spaces": true, "dashes": true, "ellipsis": true, "fractions": true});
let r = s.execute("type.smartPunctuation", &all).unwrap();
assert_eq!(plain(&s, t), "An o\u{FB03}ce’s \u{FB02}u\u{FB00}y \u{FB02}ow. Then ½ and ¾, not 1/25, 1/2/26 or 1/2.5.");
let replaced = json!({"fiLigatures": 2, "flLigatures": 2, "quotes": 1, "spaces": 1, "dashes": 0, "ellipses": 0, "fractions": 2});
assert_eq!(r, json!({"changed": 1, "replaced": replaced}));
assert_eq!(history(&s).0, undo + 1);
}
/// The ff, fl, ffl option alone leaves fi and ffi as letters (ffi keeps its ff ligature, counted
/// with this option), and the other options are off unless asked for.
#[test]
fn smart_punctuation_fl_ligatures_alone() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "office fit baffle. 1/2", "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"flLigatures": true})).unwrap();
assert_eq!(plain(&s, t), "o\u{FB00}ice fit ba\u{FB04}e. 1/2");
assert_eq!(r["replaced"], json!({"fiLigatures": 0, "flLigatures": 2, "quotes": 0, "spaces": 0, "dashes": 0, "ellipses": 0, "fractions": 0}));
}
/// A ligature or a fraction the run's font has no glyph for stays as its letters, while the run's
/// other replacements still happen.
#[test]
fn smart_punctuation_skips_ligatures_and_fractions_the_font_lacks() {
let mut s = session();
let mono = "JetBrains Mono";
assert!(!font_covers(mono, "\u{FB01}") && !font_covers(mono, "⅐"), "{mono} has no fi ligature or one-seventh");
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "fit 1/7 a--b", "font": mono})).unwrap());
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"fiLigatures": true, "fractions": true})).unwrap();
assert_eq!(plain(&s, t), "fit 1/7 a–b");
let counts = (&r["replaced"]["fiLigatures"], &r["replaced"]["fractions"], &r["replaced"]["dashes"]);
assert_eq!(counts, (&json!(0), &json!(0), &json!(1)));
}
/// A fraction at the end of a run is checked against the start of the next run: 1/25 and 1/2.5
/// split after their 1/2 stay as they are, and a 1/2 the next run's space ends is replaced.
#[test]
fn expert_fractions_look_past_the_end_of_a_run() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "1/25 1/2.5 1/2 x", "font": "Source Sans 3"})).unwrap());
for (start, end) in [(0, 3), (5, 8), (11, 14)] {
s.execute("text.setRangeStyle", &json!({"id": t.0, "start": start, "end": end, "size": 30})).unwrap();
}
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap();
assert_eq!(plain(&s, t), "1/25 1/2.5 ½ x");
assert_eq!(r["replaced"]["fractions"], 1);
}
/// An inline graphic separates the text on either side of it: the space after it is not a second
/// space after the period before it, and the digit before it does not stop a fraction after it.
#[test]
fn an_inline_graphic_separates_smart_spaces_and_fractions() {
let mut s = session();
let r = rect(&mut s, 600.0, 500.0, 10.0, 10.0);
sel(&mut s, &[r]);
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "A. B 71/2", "font": "Source Sans 3"})).unwrap());
s.execute("text.insertInline", &json!({"id": t.0, "at": 7, "symbol": "Mark"})).unwrap();
s.execute("text.insertInline", &json!({"id": t.0, "at": 3, "symbol": "Mark"})).unwrap();
let texts = |s: &Session| match node(s, t).kind {
NodeKind::Text(o) => o.runs.iter().map(|r| if r.inline.is_some() { "[g]".to_string() } else { r.text.clone() }).collect::<String>(),
_ => String::new(),
};
assert_eq!(texts(&s), "A. [g] B 7[g]1/2");
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fractions": true})).unwrap();
assert_eq!(texts(&s), "A. [g] B 7[g]½");
assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fractions"]), (&json!(0), &json!(1)));
}
/// Smart Spaces keeps one space after each period, also when the spaces start in the next run,
/// and leaves single spaces and spaces after other characters alone.
#[test]
fn smart_spaces_keeps_one_space_after_a_period() {
let mut s = session();
let t = text(&mut s, "A. B. C. D E");
// "C." is in a run of its own, and the spaces after it start the next one.
s.execute("text.setRangeStyle", &json!({"id": t.0, "start": 8, "end": 10, "size": 30})).unwrap();
assert!(matches!(node(&s, t).kind, NodeKind::Text(ref o) if o.runs.len() > 1));
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "quotes": false, "dashes": false, "ellipsis": false})).unwrap();
assert_eq!(plain(&s, t), "A. B. C. D E");
assert_eq!(r["replaced"]["spaces"], 2);
}
/// Ruby stays on the characters it was set on when Smart Punctuation makes the text before them
/// longer (curly quotes) or shorter (Smart Spaces), and no replacement takes in characters on both
/// sides of a ruby span's end: the fi with ruby on its i stays as letters, and a second space after
/// a period with ruby of its own stays.
#[test]
fn smart_punctuation_keeps_ruby_on_its_characters() {
let mut s = session();
let spans = |s: &Session, t| match node(s, t).kind {
NodeKind::Text(o) => o.ruby.iter().map(|r| (r.start, r.end)).collect::<Vec<_>>(),
_ => vec![],
};
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "'A'. base fit X. Y", "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
for (start, end) in [(1, 2), (6, 10), (12, 13), (18, 19)] {
s.execute("type.ruby", &json!({"text": "r", "start": start, "end": end})).unwrap();
}
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fiLigatures": true})).unwrap();
assert_eq!(plain(&s, t), "‘A’. base fit X. Y");
assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fiLigatures"]), (&json!(1), &json!(0)));
let text = plain(&s, t);
let on: Vec<&str> = spans(&s, t).into_iter().map(|(a, b)| &text[a..b]).collect();
assert_eq!(on, ["A", "base", "i", " "]);
}
/// Expert Fractions leaves a fraction next to a digit of another script as it is.
#[test]
fn expert_fractions_skip_fractions_next_to_digits_of_any_script() {
let mut s = session();
let words = "\u{662}1/2 1/2\u{662} 1/2.\u{662} 1/2";
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap();
assert_eq!(plain(&s, t), "\u{662}1/2 1/2\u{662} 1/2.\u{662} ½");
assert_eq!(r["replaced"]["fractions"], 1);
}
#[test]
fn convert_point_area_roundtrip() {
let mut s = session();

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