Merge main into fix/issue-7849

This commit is contained in:
dotCooCoo
2026-11-18 06:21:28 -08:00
94 changed files with 4691 additions and 250 deletions
+2
View File
@@ -74,6 +74,7 @@ pub mod perspgrid;
pub mod place;
pub mod plugin;
pub(crate) mod plugin_call;
mod preflight;
pub mod prefscmds;
pub mod print;
pub(crate) mod printadvanced;
@@ -382,6 +383,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(package::specs());
v.extend(slices::specs());
v.extend(print::specs());
v.extend(preflight::specs());
v.extend(recovery::specs());
v.extend(fileio::dxfimport::specs());
v.extend(webexport::specs());
@@ -1,7 +1,8 @@
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
//! crossing into either, added as separate open paths, with the line joining their centers if
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it
//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
#[cfg(test)]
mod tests;
@@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Common Tangents",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
has_selection,
common_tangents
)]
}
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
/// else the path's one closed convex subpath.
/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact
/// ellipse for a whole live ellipse, else the path's one closed convex subpath.
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
const C: &str = COMMON_TANGENTS;
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
if sp.anchors.len() == 1
&& let Some(only) = sp.anchors.first()
{
return pt::Outline::point(only.p).map_err(refusal);
}
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
let span = (pie.1 - pie.0).rem_euclid(360.0);
if span < 1e-9 || 360.0 - span < 1e-9 {
@@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
let ordered = d.paint_order(roots.iter().copied());
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
if a.is_point() && b.is_point() {
return Err(bad(C, "select two closed paths"));
}
// A point goes first, so that each line runs from it to where it touches the path.
let point = a.is_point() || b.is_point();
let (a, b) = if b.is_point() { (b, a) } else { (a, b) };
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
let keep = |t: &&pt::Tangent| match kinds {
"external" => t.kind == pt::TangentKind::External,
"internal" => t.kind == pt::TangentKind::Internal,
_ => true,
// A point's external and internal tangents are the same lines: every kind keeps them.
let keep = |t: &&pt::Tangent| {
point
|| match kinds {
"external" => t.kind == pt::TangentKind::External,
"internal" => t.kind == pt::TangentKind::Internal,
_ => true,
}
};
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
let (external_kept, internal_kept) = match (point, kinds) {
(true, "internal") => (0, kept.len()),
(true, _) => (kept.len(), 0),
_ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)),
};
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
if lines.is_empty() && point {
// Written as `EngineError::Other` so that the i18n message scan finds it.
let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into());
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
}
if lines.is_empty() {
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
// external tangent means one path lies inside the other and touches it there; paths that
@@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() {
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
}
fn point(s: &mut Session, x: f64, y: f64) -> NodeId {
id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap())
}
#[test]
fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() {
let mut s = session();
// The point is drawn after the oval, so it is the upper object; the lines still start at it.
let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap());
let dot = point(&mut s, 100.0, 200.0);
select(&mut s, &[oval, dot]);
let before = steps(&s);
let r = s.execute(C, &json!({"centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
assert_eq!(steps(&s), before + 1);
let found = lines(&s, &r);
assert_eq!(found.len(), 3, "two tangents and the centerline");
let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
// From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points
// are x = -a²/200 = -8, y = ±b √(1 - x²/a²).
let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt();
for sy in [1.0, -1.0] {
let touch = c + Vec2::new(-8.0, sy * y);
assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}");
}
assert_eq!(r["centerline"], r["ids"][2]);
assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]);
// Every `tangents` value gives the same two lines.
for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] {
let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}");
assert_eq!(lines(&s, &r).len(), 2, "{kind}");
}
}
#[test]
fn a_point_below_the_path_still_starts_the_lines() {
let mut s = session();
// The point is drawn first, so it is the lower object and needs no swap.
let dot = point(&mut s, 100.0, 200.0);
let round = circle(&mut s, 300.0, 200.0, 50.0);
let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
let found = lines(&s, &r);
assert_eq!(found.len(), 3, "two tangents and the centerline");
let p = Point::new(100.0, 200.0);
assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}");
// From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long.
let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt();
assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}");
assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]);
}
#[test]
fn a_point_on_or_inside_a_path_and_two_points() {
let mut s = session();
let round = circle(&mut s, 200.0, 200.0, 50.0);
// On the circle: one line, centered on the point and as long as the circle is wide.
let on = point(&mut s, 250.0, 200.0);
let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap();
assert_eq!(r["external"].as_u64(), Some(1), "{r}");
let (p, q) = lines(&s, &r)[0];
assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}");
// Inside: nothing changes, and the warning says why.
let inside = point(&mut s, 210.0, 190.0);
let before = (steps(&s), s.doc().unwrap().doc.node_count());
let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap();
assert_eq!(r["ids"], json!([]));
assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}");
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
// Two points, or a point and an open path, are refused.
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths"));
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open"));
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added");
}
#[test]
fn bad_selections_and_params_are_refused() {
let mut s = session();
+42
View File
@@ -172,6 +172,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash },
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
@@ -374,6 +375,47 @@ fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, o
Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) }
}
/// Pressure Sensitive: four original marks whose art width or nib size responds to recorded pen
/// pressure. Mouse paths keep the engine's neutral middle-pressure rendering.
fn pressure_sensitive() -> BrushLibrary {
let flex = black(band(100.0, 5.0, 48, |x| 0.5 * (x / 100.0 * std::f64::consts::TAU).sin()));
let pulse = group(vec![
black(band(100.0, 2.8, 64, |x| 1.4 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
black(shapes::ellipse(Rect::new(46.0, -2.2, 54.0, 2.2))),
]);
let art_pressure = |name: &str, art: Node, light: f64, heavy: f64| Brush {
name: name.into(),
kind: BrushKind::Art(ArtBrush {
art,
width: light,
width_mode: Some(Variation::Pressure),
width_max: Some(heavy),
colorization: Colorization::Tints,
..Default::default()
}),
};
let nib_pressure = |name: &str, angle: f64, roundness: f64, size: f64, variation: f64| Brush {
name: name.into(),
kind: BrushKind::Calligraphic(Calligraphic {
angle,
roundness,
size,
variation: [0.0, 0.0, variation],
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]),
}),
};
built(
"Pressure Sensitive",
Document::new(100.0, 100.0),
vec![
art_pressure("Flex Ribbon", flex, 35.0, 250.0),
art_pressure("Pulse Stroke", pulse, 45.0, 280.0),
nib_pressure("Round Flow", 0.0, 100.0, 7.0, 5.0),
nib_pressure("Chisel Flow", 35.0, 25.0, 9.0, 7.0),
],
)
}
/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for
/// blending and texture.
fn bristle_brushes() -> BrushLibrary {
+66 -2
View File
@@ -532,6 +532,24 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas:
super::typecmd::export_overflow_warning(&overflow)
}
/// The objects behind production findings. Resource art points to its first visible owner on
/// the canvas, so a finding can be located without selecting an id outside the layer tree.
#[derive(Default)]
pub(super) struct PreflightType {
pub fonts: BTreeMap<UsedFont, BTreeSet<NodeId>>,
pub overflow: BTreeSet<NodeId>,
pub images: BTreeMap<NodeId, NodeId>,
}
pub(super) fn preflight_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> PreflightType {
let mut walk = Printed::new(d);
walk.preflight = Some(PreflightType::default());
for l in layers {
walk.node(l, Some(areas));
}
walk.preflight.unwrap_or_default()
}
/// The walk of [`printed_type`].
struct Printed<'a> {
d: &'a Document,
@@ -546,13 +564,25 @@ struct Printed<'a> {
/// The symbols and patterns whose art was walked.
symbols: BTreeSet<String>,
patterns: BTreeSet<String>,
preflight: Option<PreflightType>,
owner: Option<NodeId>,
}
impl<'a> Printed<'a> {
/// A walk of `d` among its own objects, nothing found yet.
fn new(d: &'a Document) -> Self {
let boxes = d.symbol_boxes();
Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }
Self {
d,
boxes,
own: true,
fonts: BTreeSet::new(),
overflow: BTreeSet::new(),
symbols: BTreeSet::new(),
patterns: BTreeSet::new(),
preflight: None,
owner: None,
}
}
/// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit
@@ -560,6 +590,15 @@ impl<'a> Printed<'a> {
/// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live
/// object) all of them but those outside the clipping path of a clip group.
fn node(&mut self, n: &Node, areas: Option<&[Rect]>) {
let previous = self.owner;
if self.own {
self.owner = Some(n.id);
}
self.node_contents(n, areas);
self.owner = previous;
}
fn node_contents(&mut self, n: &Node, areas: Option<&[Rect]>) {
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
return;
}
@@ -571,6 +610,14 @@ impl<'a> Printed<'a> {
&& !open
&& !self.meets(n, a)
{
// An entirely overset frame paints nothing, but is still a delivery problem. Keep
// the export walk unchanged; only preflight checks the frame itself in this case.
if let (Some(p), Some(owner), NodeKind::Text(t)) = (&mut self.preflight, self.owner, &n.kind)
&& n.geometric_bounds().is_some_and(|b| a.iter().any(|r| r.intersect(b).area() > 0.0 || r.contains_rect(b)))
&& vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).overflow
{
p.overflow.insert(owner);
}
return;
}
// The art that its opacity mask, pattern paints and brushed strokes draw.
@@ -616,16 +663,33 @@ impl<'a> Printed<'a> {
if overflows && self.own {
self.overflow.insert(n.id);
}
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.overflow.insert(owner);
}
for r in runs {
self.fonts.extend(run_fonts(r));
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
}
}
self.fonts.extend(fonts);
// Inline graphics draw their symbols' art.
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
self.symbol(&art.symbol);
}
}
}
NodeKind::Image(_) => {
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.images.entry(n.id).or_insert(owner);
}
}
NodeKind::SymbolInstance { symbol, .. } => self.symbol(symbol),
NodeKind::PlacedDocument(p) => {
if let (Some(report), Some(owner)) = (&mut self.preflight, self.owner) {
report.images.entry(n.id).or_insert(owner);
}
for art in p.art(n) {
self.art(&art);
}
+8 -4
View File
@@ -1152,6 +1152,13 @@ pub fn read_info(p: &Value) -> Result<Value> {
Ok(out)
}
/// Resolution at a placed image's transform: 72 points per inch over each pixel axis.
pub(super) fn effective_ppi(xf: Affine) -> [f64; 2] {
let [a, b, c, d, ..] = xf.as_coeffs();
let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l);
[ppi(a, b), ppi(c, d)]
}
pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "image.info";
let st = s.doc()?;
@@ -1165,9 +1172,6 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
let doc = super::links::with_brush_art(&st.doc);
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
let [a, b, c, d, ..] = im.xf.as_coeffs();
let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l);
let size = n.geometric_bounds().unwrap_or_default();
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
let doc_path = super::links::LinkBase::of(st).doc;
@@ -1179,7 +1183,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
"pixelWidth": im.width,
"pixelHeight": im.height,
"ppi": [ppi(a, b), ppi(c, d)],
"ppi": effective_ppi(im.xf),
"width": size.width(),
"height": size.height(),
}))
+133
View File
@@ -0,0 +1,133 @@
//! Production preflight: the existing output-aware type walk, linked-file probes and image
//! resolution calculation, returned as findings that the interface can locate and recheck.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_text::{FontDb, FontMatch};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, number_or, text_param};
const COMMAND: &str = "document.preflight";
const KINDS: [&str; 4] = ["fonts", "text", "links", "resolution"];
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
query "document.preflight",
"Production Preflight",
[],
None,
"{output?: pdf|print|screen (pdf), minPpi?: 1..9600 (300, or 96 for screen), artboards?: [index, …] (0-based whole numbers; default all)} check the selected output without writing files or editing the document; print reuses the saved print settings with these artboards, pdf and screen check visible artwork on these artboards. Reuses output-aware font and overflow checks, Links file status and image.info effective resolution. Resource findings locate their first visible canvas owner; resolution inside resource art is reported as not checked because its placed scale can differ. → {output, minPpi, artboards, checks: [{kind: fonts|text|links|resolution, status: passed|failed|notChecked, count, notChecked}], findings: [{kind, code, ids (canvas objects), name, detail?, sourceId?, effectivePpi?, threshold?}], outputWarnings, limitations}; a pass covers only these checks, not certification of a produced file",
has_doc,
check
)]
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let output = text_param(p, "output", COMMAND)?.unwrap_or("pdf");
if !matches!(output, "pdf" | "print" | "screen") {
return Err(bad(COMMAND, "output must be pdf, print or screen"));
}
let min_ppi = number_or(p, "minPpi", if output == "screen" { 96.0 } else { 300.0 }, COMMAND)?;
if !min_ppi.is_finite() || !(1.0..=9600.0).contains(&min_ppi) {
return Err(bad(COMMAND, "minPpi must be from 1 to 9600"));
}
let indices = match p.get("artboards").filter(|v| !v.is_null()) {
Some(v) => super::panelcmds::listed_artboards(&s.doc()?.doc, v, "artboards", COMMAND)?,
None => (0..s.doc()?.doc.artboards.len()).collect(),
};
let context = if output == "print" {
super::print::preflight_context(s, &indices)?
} else {
let doc = &s.doc()?.doc;
let pages = indices.iter().filter_map(|i| doc.artboards.get(*i).map(|a| (a.rect, vectorcraft_geom::Affine::IDENTITY))).collect();
super::print::PreflightContext { layers: vectorcraft_pdf::PrintLayers::Visible, pages, warnings: vec![] }
};
let areas = context.pages.iter().map(|(r, _)| *r).collect::<Vec<_>>();
let st = s.doc()?;
let doc = st.doc.with_placed_art();
let mut layers = doc.layers.clone();
vectorcraft_pdf::keep_layers(&mut layers, context.layers);
let typed = super::fonts::preflight_type(&doc, &layers, &areas);
let statuses = super::links::statuses(st);
let mut findings = vec![];
let db = FontDb::global();
for (font, ids) in typed.fonts {
let code = match db.resolve(&font.0, &font.1).map(|(_, m)| m) {
None | Some(FontMatch::Missing) => "missingFont",
Some(FontMatch::Style) => "substitutedFont",
_ => continue,
};
findings.push(
json!({ "kind": "fonts", "code": code, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "name": super::fonts::font_label(&font) }),
);
}
for id in typed.overflow {
findings.push(finding("text", "overflow", id, &doc));
}
let mut resolution_unchecked = 0usize;
for (source, owner) in typed.images {
if let Some((status, _, _)) = statuses.get(&source) {
let code = match status.as_str() {
"missing" => Some("missingLink"),
"modified" => Some("modifiedLink"),
_ => None,
};
if let Some(code) = code {
let mut f = finding("links", code, owner, &doc);
f["sourceId"] = json!(source.0);
findings.push(f);
}
}
// A vector placed document has no single bitmap resolution. Its embedded artwork, and
// resources with their own coordinate systems, must never be certified at a local scale.
if doc.node(source).is_none() || source != owner {
resolution_unchecked += 1;
continue;
}
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node(source).map(|n| &n.kind) else {
resolution_unchecked += 1;
continue;
};
let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n));
let ppi = context
.pages
.iter()
.filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0))
.map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf))
.reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]);
let Some(ppi) = ppi else {
resolution_unchecked += 1;
continue;
};
// Inverting the placed-size transform can round an exact threshold slightly down.
if ppi.iter().any(|n| !n.is_finite() || *n <= 0.0) {
resolution_unchecked += 1;
} else if ppi.iter().any(|n| *n < min_ppi * (1.0 - 1e-9)) {
let mut f = finding("resolution", "lowResolution", owner, &doc);
f["effectivePpi"] = json!(ppi);
f["threshold"] = json!(min_ppi);
findings.push(f);
}
}
let checks = KINDS.map(|kind| {
let count = findings.iter().filter(|f| f["kind"] == kind).count();
let not_checked = if kind == "resolution" { resolution_unchecked } else { 0 };
let status = if count > 0 {
"failed"
} else if not_checked > 0 {
"notChecked"
} else {
"passed"
};
json!({ "kind": kind, "status": status, "count": count, "notChecked": not_checked })
});
Ok(json!({
"output": output, "minPpi": min_ppi, "artboards": indices, "checks": checks,
"findings": findings, "outputWarnings": context.warnings,
"limitations": ["These checks do not certify an exported file.", "Resolution inside symbols, patterns, brushes, opacity masks and placed documents is not checked."]
}))
}
fn finding(kind: &str, code: &str, id: NodeId, doc: &vectorcraft_doc::Document) -> Value {
json!({ "kind": kind, "code": code, "ids": [id.0], "name": doc.node(id).map(|n| n.display_name()).unwrap_or_else(|| id.0.to_string()) })
}
+26
View File
@@ -147,6 +147,32 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
Ok(v)
}
/// Reuse the Print dialog's saved settings and page geometry for production preflight, without
/// printing, writing a file or duplicating its type warnings.
pub(super) struct PreflightContext {
pub layers: PrintLayers,
pub pages: Vec<(Rect, Affine)>,
pub warnings: Vec<String>,
}
pub(super) fn preflight_context(s: &Session, indices: &[usize]) -> Result<PreflightContext> {
let settings =
json!({ "settings": { "artboards": "range", "range": indices.iter().map(|i| (i + 1).to_string()).collect::<Vec<_>>().join(",") } });
let set = preset_or_saved("document.preflight", s, &s.doc()?.doc, &settings)?;
super::printadvanced::flattener("document.preflight", &set, &s.prefs.flattener_presets)?;
let mut pv = vectorcraft_pdf::preview(&s.doc()?.doc, &set).map_err(|e| pdf_error("document.preflight", e))?;
let pages = pv
.sheets
.iter()
.filter_map(|p| {
let to_page = Affine::new(p.transform);
on_page(Rect::new(p.area[0], p.area[1], p.area[2], p.area[3]), to_page, (p.width, p.height)).map(|area| (area, to_page))
})
.collect();
pv.warnings.extend(pv.setting_notes);
Ok(PreflightContext { layers: set.print_layers, pages, warnings: pv.warnings })
}
/// The parts of the document (document space) that the pages of `pv` print.
fn areas(pv: &PrintPreview) -> Vec<Rect> {
pv.sheets
+126 -17
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web",
[],
None,
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
has_doc,
export
),
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web Preview",
[],
None,
"{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}",
"{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, shifted (by colorTable.shifted; also locked), webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}",
has_doc,
preview
),
@@ -331,8 +331,14 @@ pub struct ColorTable {
/// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the
/// table when the first color was deleted. Empty: the reduction makes the palette.
pub custom_palette: Vec<String>,
/// Colors shifted by hand: each source color (`#rrggbb`) and the color it is written as. A
/// shifted color is locked, and a source the table does not hold shifts nothing.
pub shifted: std::collections::BTreeMap<String, String>,
}
/// A color shifted by hand: (source, color written).
type Shift = ([u8; 3], [u8; 3]);
/// The most colours a colour table list holds.
const MAX_TABLE: usize = 256;
@@ -352,6 +358,21 @@ impl ColorTable {
list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect()
}
/// The colors shifted by hand as (source, color written). An error names a value that is not a
/// color such as `#ff8800`, two keys that name one color, or more than 256 entries.
fn shifts(&self) -> std::result::Result<Vec<Shift>, String> {
// One entry past the limit is enough for `colors` to refuse a longer map.
let (keys, values): (Vec<String>, Vec<String>) = self.shifted.iter().take(MAX_TABLE + 1).map(|(k, v)| (k.clone(), v.clone())).unzip();
let sources = Self::colors(&keys, "shifted")?;
let to = Self::colors(&values, "shifted")?;
for (i, (s, k)) in sources.iter().zip(&keys).enumerate() {
if sources[..i].contains(s) {
return Err(format!("colorTable.shifted: `{k}` names a color another key names"));
}
}
Ok(sources.into_iter().zip(to).collect())
}
/// `h` as RGB; `None` when it is not a color such as `#ff8800`.
fn rgb(h: &str) -> Option<[u8; 3]> {
vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| {
@@ -487,13 +508,18 @@ impl WebSettings {
{
ColorTable::colors(list, what)?;
}
// A deleted color is no longer locked, transparent or web-shifted.
// A deleted color is no longer locked, transparent, web-shifted or shifted.
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
if !deleted.is_empty() {
for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] {
list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c)));
}
}
// Shifts are kept as `#rrggbb` in lowercase; a color shifted to itself is not shifted, and
// a color shifted by hand is not web-shifted.
let shifts: Vec<Shift> = table.shifts()?.into_iter().filter(|(s, to)| s != to && !deleted.contains(s)).collect();
table.web_shift.retain(|h| ColorTable::rgb(h).is_none_or(|c| !shifts.iter().any(|(s, _)| *s == c)));
table.shifted = shifts.into_iter().map(|(s, to)| (hex(s), hex(to))).collect();
Ok(self)
}
@@ -640,6 +666,8 @@ pub struct TableColor {
pub transparent: bool,
pub locked: bool,
pub web_shifted: bool,
/// Shifted by hand (`colorTable.shifted`): written as `color` instead of `source`.
pub shifted: bool,
}
/// An optimised image file.
@@ -759,6 +787,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
let locked = ColorTable::colors(&table.locked, "locked")?;
let to_clear = ColorTable::colors(&table.transparent, "transparent")?;
let shift = ColorTable::colors(&table.web_shift, "webShift")?;
let by_hand = table.shifts()?;
let shifted_to = |src: &[u8; 3]| by_hand.iter().find(|(s, _)| s == src).map(|(_, to)| *to);
// A color shifted by hand is kept when the colors are reduced, as a locked one is, and takes
// one of the slots kept for them before the locked colors do.
let kept: Vec<[u8; 3]> = by_hand.iter().map(|(s, _)| *s).chain(locked.iter().copied()).collect();
let o = PaletteOptions {
colors: s.colors,
reduction: s.reduction,
@@ -767,7 +800,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
transparency: s.transparency,
matte,
};
let mut ix = reduced(rgba, w, h, s, &o, &locked)?;
let mut ix = reduced(rgba, w, h, s, &o, &kept)?;
// Map to transparent works on the colours the reduction made.
let before = ix.palette.clone();
let clear = ix.transparent.map(usize::from);
@@ -781,11 +814,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
*slot = *c;
}
}
// Web snap, then the colours shifted by hand (locked colours stay as they are).
// Web shift and web snap (locked colors and colors shifted by hand stay as they are).
let clear = ix.transparent.map(usize::from);
for (i, c) in ix.palette.iter_mut().enumerate() {
let src = sources.get(i).copied().unwrap_or(*c);
if Some(i) == clear || locked.contains(&src) {
if Some(i) == clear || shifted_to(&src).is_some() || locked.contains(&src) {
continue;
}
if shift.contains(&src) {
@@ -794,8 +827,19 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
*c = snapped;
}
}
// Lossy compares the pixels with the colors written for them, and moves no pixel into or out of
// a color shifted by hand.
if s.format == WebFormat::Gif {
web::lossy(&mut ix, rgba, s.lossy);
let fixed: Vec<u8> = sources.iter().enumerate().filter(|(_, c)| shifted_to(c).is_some()).filter_map(|(i, _)| u8::try_from(i).ok()).collect();
web::lossy(&mut ix, rgba, s.lossy, &fixed);
}
// The colors shifted by hand.
for (i, c) in ix.palette.iter_mut().enumerate() {
if Some(i) != clear
&& let Some(to) = sources.get(i).and_then(shifted_to)
{
*c = to;
}
}
let order = web::sort(&mut ix, table.sort);
let sources: Vec<[u8; 3]> = order.iter().map(|&i| sources.get(i).copied().unwrap_or_default()).collect();
@@ -804,12 +848,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
.iter()
.zip(&sources)
.enumerate()
.map(|(i, (c, src))| TableColor {
color: *c,
source: *src,
transparent: ix.transparent == u8::try_from(i).ok(),
locked: locked.contains(src),
web_shifted: shift.contains(src),
.map(|(i, (c, src))| {
let transparent = ix.transparent == u8::try_from(i).ok();
let shifted = !transparent && shifted_to(src).is_some();
TableColor {
color: *c,
source: *src,
transparent,
locked: locked.contains(src) || shifted,
web_shifted: shift.contains(src) && !shifted,
shifted,
}
})
.collect();
Ok(PaletteImage { ix, colors, mapped })
@@ -818,7 +867,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the
/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the
/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to
/// transparent.
/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of
/// `colors` together, and its first opaque colors that fit in the rest.
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
let table = &s.color_table;
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
@@ -847,11 +897,70 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
left.push(c);
}
}
left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear));
if left.is_empty() || (removed && !opaque_left(&left)) {
return Err(KEEP_ONE.into());
}
Ok(quantize::quantize_to(rgba, w, h, o, &left))
// The colors mapped to transparent all become the one transparent entry, so together they take
// one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of
// them and no pixel is transparent, that slot goes to the next opaque color instead.
let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true);
let mut ix = quantize::quantize_to(rgba, w, h, o, &kept);
clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear);
if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) {
return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false)));
}
Ok(ix)
}
/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in
/// `to_clear` are kept and take one slot together; without it they are left out. The list holds
/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry).
fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> {
let any_clear = clear && left.iter().any(|c| to_clear.contains(c));
let total = 256 - usize::from(has_clear);
let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear));
let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room);
let mut clear_room = if clear { total - opaque } else { 0 };
left.iter()
.copied()
.filter(|c| {
let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room };
let keep = *slots > 0;
*slots = slots.saturating_sub(1);
keep
})
.collect()
}
/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to
/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the
/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later.
fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) {
let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect();
if dropped.is_empty() {
return;
}
let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect();
let near = quantize::nearest_entries(rgba, o, &all);
if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) {
return;
}
let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) {
Some(i) => i,
None => {
// A kept color mapped to transparent that no pixel took; at most 255 entries are used then.
let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else {
return;
};
ix.palette.push(*c);
i
}
};
for (v, n) in ix.indices.iter_mut().zip(&near) {
if n.is_some_and(|n| n >= kept.len()) {
*v = entry;
}
}
}
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
@@ -1116,7 +1225,7 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
.map(|c| {
json!({
"color": hex(c.color), "source": hex(c.source), "transparent": c.transparent, "locked": c.locked,
"webShifted": c.web_shifted, "webSafe": quantize::web_safe(c.color) == c.color,
"webShifted": c.web_shifted, "shifted": c.shifted, "webSafe": quantize::web_safe(c.color) == c.color,
})
})
.collect();
+52 -4
View File
@@ -110,6 +110,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"art-ribbons",
"ink-and-wash",
"calligraphic-nibs",
"pressure-sensitive",
"bristle-brushes",
"pattern-borders",
"scatter-shapes",
@@ -131,19 +132,19 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"]
);
assert_eq!(libs[6]["count"].as_u64(), Some(4));
assert_eq!(libs[7]["count"].as_u64(), Some(4));
let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"}));
assert_eq!(
beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"]
);
assert_eq!(libs[7]["count"].as_u64(), Some(4));
assert_eq!(libs[8]["count"].as_u64(), Some(4));
let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"}));
assert_eq!(
dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
);
assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4)));
assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4)));
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
@@ -154,6 +155,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("art-ribbons", "art"),
("ink-and-wash", "art"),
("calligraphic-nibs", "calligraphic"),
("pressure-sensitive", "art"),
("bristle-brushes", "bristle"),
("pattern-borders", "pattern"),
("scatter-shapes", "scatter"),
@@ -164,7 +166,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.len() >= 4, "{id}");
for b in &lib.brushes {
let kind = if b.name == "Brush Pen" { "calligraphic" } else { kind };
let kind = if ["Brush Pen", "Round Flow", "Chisel Flow"].contains(&b.name.as_str()) { "calligraphic" } else { kind };
assert_eq!(b.kind.type_id(), kind, "{}", b.name);
let mut line = vectorcraft_geom::BezPath::new();
line.move_to((0.0, 0.0));
@@ -299,6 +301,52 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Pressure Sensitive").unwrap();
let names = ["Flex Ribbon", "Pulse Stroke", "Round Flow", "Chisel Flow"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
let mut curve = line_to(20.0);
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
for b in &lib.brushes {
let width_at = |pressure| {
let stroke = vectorcraft_doc::StrokeLayer {
pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }),
..black_stroke()
};
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke);
let points = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at pressure {pressure}", b.name);
let min = points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min);
let max = points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max);
max - min
};
let light = width_at(0.0);
let heavy = width_at(1.0);
for width in [light, heavy] {
assert!(width.is_finite() && width > 0.0, "{}: light={light}, heavy={heavy}", b.name);
}
assert!(heavy > light * 1.3, "{}: light={light}, heavy={heavy}", b.name);
for line in [line_to(2.0), curve.clone()] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
let points = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
}
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "pressure-sensitive", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([path]));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two
/// translucent washes, with names of their own and a few paths of art each.
#[test]
+1 -1
View File
@@ -407,7 +407,7 @@ fn image_with_shaped_fill(s: &mut Session) -> NodeId {
/// outline with `outline`.
fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec<NodeId> {
let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0);
vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline)
vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline, false)
}
/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its
+190
View File
@@ -539,6 +539,196 @@ fn colour_table_delete_maps_pixels_to_the_nearest_color_left() {
assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]);
}
/// The colors of a fixed palette mapped to transparent take one slot of Colors together with the
/// transparent pixels, so the opaque colors after them still fit: their pixels stay opaque, and the
/// pixels of the colors mapped to transparent become transparent.
#[test]
fn colour_table_fixed_palette_keeps_an_opaque_color() {
// 40×10: red, a near red and blue, and 10 px with nothing (transparent).
let mut s = session(40.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100");
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff");
for table in [
json!({"customPalette": ["#ff0000", "#ee1100", "#0000ff"], "deleted": ["#ee1100"], "transparent": ["#ff0000"]}),
json!({"customPalette": ["#ff0000", "#0000ff"], "transparent": ["#ff0000"]}),
] {
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table});
let v = run(&mut s, "document.exportForWeb.preview", p.clone());
let opaque: Vec<&Value> = v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| &c["source"]).collect();
assert_eq!((opaque, v["colors"].as_array().unwrap().len()), (vec![&json!("#0000ff")], 2), "{p}");
let img = pixels(&one(&mut s, p.clone()));
let alpha = |x: u32| img.get_pixel(x, 5).0[3];
assert_eq!((alpha(5), alpha(15), img.get_pixel(25, 5).0, alpha(35)), (0, 0, [0, 0, 255, 255], 0), "{p}");
}
// A color mapped to transparent that no pixel takes leaves its slot to an opaque color.
let mut u = session(20.0, 10.0);
rect(&mut u, [0.0, 0.0, 10.0, 10.0], "#0000ff");
rect(&mut u, [10.0, 0.0, 10.0, 10.0], "#00ff00");
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#00ff00", "#ff0000"], "transparent": ["#ff0000"]}});
let img = pixels(&one(&mut u, p));
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0), ([0, 0, 255, 255], [0, 255, 0, 255]));
// At 256 colors a color mapped to transparent after 255 opaque ones still keeps an entry.
let full: Vec<String> =
std::iter::once("#0000ff".to_string()).chain((1..255).map(|i| format!("#00{i:02x}00"))).chain(["#ff0000".to_string()]).collect();
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": full, "transparent": ["#ff0000"]}});
let img = pixels(&one(&mut s, p));
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), (0, [0, 0, 255, 255], 0));
// With one opaque color and 255 mapped to transparent, the last of those does not fit, and its
// pixels still become transparent rather than taking the opaque color nearest them.
let mut d = session(30.0, 10.0);
rect(&mut d, [0.0, 0.0, 10.0, 10.0], "#0000ff");
rect(&mut d, [10.0, 0.0, 10.0, 10.0], "#0000ee");
let clear: Vec<String> = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect();
let palette: Vec<String> = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect();
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}});
let img = pixels(&one(&mut d, p));
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0));
// Without transparent pixels the colors mapped to transparent still take one slot together.
let mut t = session(30.0, 10.0);
rect(&mut t, [0.0, 0.0, 10.0, 10.0], "#ff0000");
rect(&mut t, [10.0, 0.0, 10.0, 10.0], "#ee1100");
rect(&mut t, [20.0, 0.0, 10.0, 10.0], "#0000ff");
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {
"customPalette": ["#ff0000", "#ee1100", "#0000ff", "#00ff00"], "transparent": ["#ff0000", "#ee1100"],
}});
let v = run(&mut t, "document.exportForWeb.preview", p.clone());
assert_eq!(v["colors"].as_array().unwrap().len(), 2, "{v}");
let img = pixels(&one(&mut t, p));
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255]));
}
/// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in
/// the image, the other colors stay, the table shows it as shifted and locked, and the preview is
/// the file.
#[test]
fn colour_table_shift_writes_the_picked_color_wherever_the_source_is() {
let mut s = session(30.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#0000ff");
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#00ff00");
let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p);
let entry = |v: &Value, source: &str| v["colors"].as_array().unwrap().iter().find(|c| c["source"] == source).cloned().unwrap_or(Value::Null);
for format in ["gif", "png8"] {
let p = json!({"format": format, "dither": "none", "colorTable": {"shifted": {"#0000FF": "#FF8800"}}});
let v = preview(&mut s, p.clone());
let c = entry(&v, "#0000ff");
assert_eq!(
(c["color"].as_str(), c["shifted"].as_bool(), c["locked"].as_bool(), c["webShifted"].as_bool()),
(Some("#ff8800"), Some(true), Some(true), Some(false)),
"{format}: {v}"
);
assert_eq!((entry(&v, "#ff0000")["shifted"].as_bool(), entry(&v, "#ff0000")["color"].as_str()), (Some(false), Some("#ff0000")));
let file = one(&mut s, p);
assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file");
let img = pixels(&file);
assert_eq!(
(img.get_pixel(5, 5).0, img.get_pixel(12, 2).0, img.get_pixel(18, 8).0, img.get_pixel(25, 5).0),
([255, 0, 0, 255], [255, 136, 0, 255], [255, 136, 0, 255], [0, 255, 0, 255]),
"{format}"
);
assert_eq!(distinct(&img), 3, "{format}");
}
// A shifted color is kept when the colors are reduced, as a locked one is.
let two = preview(&mut s, json!({"colors": 2, "dither": "none", "colorTable": {"shifted": {"#00ff00": "#123456"}}}));
assert_eq!(entry(&two, "#00ff00")["color"], "#123456", "{two}");
// With one slot to keep, the shifted color takes it before a locked one.
let p = json!({"colors": 2, "dither": "none", "colorTable": {"locked": ["#ff0000"], "shifted": {"#0000ff": "#123456"}}});
let first = preview(&mut s, p);
assert_eq!(entry(&first, "#0000ff")["color"], "#123456", "{first}");
// A source the table does not hold shifts nothing, and the shift stays with the settings.
let base = preview(&mut s, json!({"dither": "none"}));
let absent = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#123456": "#000000"}}}));
assert_eq!(absent["colors"], base["colors"]);
// Two colors may be shifted to one color and keep their own sources.
let same = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#ff0000": "#123456", "#0000ff": "#123456"}}}));
assert_eq!((entry(&same, "#ff0000")["color"].as_str(), entry(&same, "#0000ff")["color"].as_str()), (Some("#123456"), Some("#123456")));
assert_eq!(entry(&same, "#00ff00")["shifted"], false);
// A shift by hand wins over web shift, web snap and a lock; transparency wins over it.
let p =
json!({"dither": "none", "webSnap": 100, "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "webShift": ["#0000ff"], "locked": ["#0000ff"]}});
let c = entry(&preview(&mut s, p), "#0000ff");
assert_eq!((c["color"].as_str(), c["webShifted"].as_bool(), c["locked"].as_bool()), (Some("#fe0101"), Some(false), Some(true)));
let clear = json!({"dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "transparent": ["#0000ff"]}});
let v = preview(&mut s, clear.clone());
assert!(v["colors"].as_array().unwrap().iter().all(|c| c["shifted"] == false), "{v}");
assert_eq!(pixels(&one(&mut s, clear)).get_pixel(15, 5).0[3], 0);
// The settings keep the shifts in lowercase, drop a color shifted to itself, a deleted one and
// the web shift of a color shifted by hand.
let table = json!({"shifted": {"#0000FF": "#FE0101", "#FF0000": "#ff0000", "#00ff00": "#000000"}, "webShift": ["#0000ff", "#00ff00"], "deleted": ["#00ff00"]});
let r = run(&mut s, "webExport.settings", json!({ "colorTable": table }));
let t = &r["settings"]["colorTable"];
assert_eq!((&t["shifted"], &t["webShift"]), (&json!({"#0000ff": "#fe0101"}), &json!([])));
// Another reduction keeps the shifts; a saved preset keeps them.
let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"}));
assert_eq!(r["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"}));
run(&mut s, "webExport.presets.save", json!({"name": "Blue to red", "dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}}}));
assert_eq!(entry(&preview(&mut s, json!({"preset": "Blue to red"})), "#0000ff")["color"], "#fe0101");
// Bad shifts are refused and change nothing.
let many: serde_json::Map<String, Value> = (0..257).map(|i| (format!("#{i:06x}"), json!("#000000"))).collect();
for bad in [
json!({"nope": "#000000"}),
json!({"#ff0000": "nope"}),
json!({"#ff0000": "#ff000080"}),
json!({"#ff000080": "#000000"}),
json!({"#ff0000": "#000000", "#FF0000": "#ffffff"}),
json!({"#f00": "#000000", "#ff0000": "#ffffff"}),
Value::Object(many),
] {
let p = json!({"colorTable": {"shifted": bad}});
assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}");
assert!(s.execute("document.exportForWeb.preview", &p).is_err(), "{p}");
assert!(s.execute("webExport.settings", &p).is_err(), "{p}");
}
assert_eq!(run(&mut s, "webExport.settings", json!({}))["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"}));
// Settings saved before shifts existed still read.
let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"colorTable": {"locked": ["#ff0000"]}})).unwrap();
assert!(old.color_table.shifted.is_empty());
}
/// Lossy GIF compression leaves the pixels of a color shifted by hand alone, so a color shifted near
/// another one does not take in that color's pixels.
#[test]
fn lossy_does_not_spread_a_shifted_color_into_another() {
let mut s = session(30.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#0000ff");
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#c80000");
let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#be0000"}}});
let img = pixels(&one(&mut s, p));
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(20, 5).0, img.get_pixel(29, 5).0), ([190, 0, 0, 255], [200, 0, 0, 255], [200, 0, 0, 255]));
}
/// Lossy GIF compression moves no pixel into or out of a color shifted by hand: the colors next to
/// a shifted one keep their own pixels, and the shifted color keeps all of its pixels.
#[test]
fn lossy_moves_no_pixel_into_or_out_of_a_shifted_color() {
let mut s = session(30.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1414e6");
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#0000ff");
rect(&mut s, [20.0, 0.0, 30.0, 10.0], "#1414e6");
let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#ff0000"}}});
let img = pixels(&one(&mut s, p));
let near_blue = [20, 20, 230, 255];
for x in 0..30 {
let want = if (10..20).contains(&x) { [255, 0, 0, 255] } else { near_blue };
assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}");
}
}
/// Lossy GIF compression compares the pixels with the colors web snap writes, so a pixel does not
/// take a color that snaps far from it.
#[test]
fn lossy_compares_pixels_with_the_snapped_colors() {
let mut s = session(20.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1a1a1a");
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#000000");
let img = pixels(&one(&mut s, json!({"format": "gif", "dither": "none", "webSnap": 100, "lossy": 50})));
for x in 0..20 {
let want = if x < 10 { [51, 51, 51, 255] } else { [0, 0, 0, 255] };
assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}");
}
}
#[test]
fn presets_and_remembered_settings() {
let mut s = two_colours();