Merge upstream main and reconcile progress documentation

This commit is contained in:
yoriswind committed 2026-11-11 04:45:33 -08:00
commit 104979dd33
237 files changed
+14548 -816

No files matched your search

Generated
+2 -1
View File
@@ -1096,7 +1096,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"flate2",
"serde",
@@ -6687,6 +6687,7 @@ dependencies = [
"vectorcraft-geom",
"wasmi",
"wat",
"web-time",
]
[[package]]
+1 -1
View File
@@ -21,7 +21,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
# internal
+3 -2
View File
@@ -237,9 +237,10 @@ fn main() -> ExitCode {
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply
/// as they do there.
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&mut h.session);
prefs_dir::attach_plugin_store(&mut h.session);
+2
View File
@@ -463,6 +463,8 @@ fn main() -> std::process::ExitCode {
let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch")));
let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag);
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
app.set_startup_update_check(true);
load_prefs(&mut app, saved);
+8
View File
@@ -57,6 +57,14 @@ pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
}
}
/// Have File › Scripts and `script.listInstalled` list the scripts of the `Scripts` folder. The
/// folder is only read: the user makes it.
pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Scripts") {
session.attach_scripts_dir(dir);
}
}
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
/// now on there. After the preferences were restored: the folder is the one place the presets live.
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
+13 -1
View File
@@ -1,4 +1,4 @@
use super::{Arc, Deserialize, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip};
use super::{Arc, Deserialize, LayerColor, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Artboard {
@@ -39,6 +39,18 @@ pub struct Artboard {
/// it behind the art ([`super::Document::with_artboard_fills`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<vectorcraft_color::Color>,
/// Guide label (Artboard Options): the color the canvas draws the artboard's own ruler guides
/// in (a guide whose [`super::Guide::artboard`] is this artboard's id), a [`LayerColor`] preset
/// or a custom RGB. None (No label) draws them in the guide color preference, as canvas guides
/// are. Only the canvas uses it: the paper, exports and print don't. Written only when set; a
/// file's preset outside [`super::LAYER_COLORS`] reads as no label.
#[serde(default, deserialize_with = "label_within_palette", skip_serializing_if = "Option::is_none")]
pub guide_label: Option<LayerColor>,
}
/// A file's guide label: a preset index outside [`super::LAYER_COLORS`] reads as no label.
fn label_within_palette<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<LayerColor>, D::Error> {
Ok(Option::<LayerColor>::deserialize(d)?.filter(|c| !matches!(c, LayerColor::Preset(i) if usize::from(*i) >= super::LAYER_COLORS.len())))
}
/// The Video Ruler Pixel Aspect Ratios an artboard takes (Artboard Options): from a pixel ten times
+308 -6
View File
@@ -1,7 +1,7 @@
//! Persistent dimension recipes. Children are ordinary paths and type for all renderers/exporters.
use crate::{Document, NodeId, Unit};
use serde::{Deserialize, Serialize};
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Vec2};
/// What a dimension measures.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -306,6 +306,12 @@ pub enum DimensionSource {
a: Option<PointRef>,
b: Option<PointRef>,
vertex: Option<PointRef>,
/// The first point when it is not an anchor, held against a path's anchors.
#[serde(default, rename = "freeA", skip_serializing_if = "Option::is_none")]
free_a: Option<FreePoint>,
/// The second point when it is not an anchor.
#[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")]
free_b: Option<FreePoint>,
},
}
@@ -315,7 +321,11 @@ impl DimensionSource {
Self::Segment { edge } | Self::Arc { edge } => vec![edge.node],
Self::Angle { first, second } => vec![first.node, second.node],
Self::Circle { node } => vec![*node],
Self::Points { a, b, vertex } => [a, b, vertex].into_iter().filter_map(|p| p.as_ref().map(|r| r.node)).collect(),
Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex]
.into_iter()
.filter_map(|p| p.as_ref().map(|r| r.node))
.chain([free_a, free_b].into_iter().filter_map(|p| p.as_ref().map(FreePoint::node)))
.collect(),
}
}
/// Anchor indexes cannot safely follow a topology replacement. Ordinary moves and handle
@@ -332,6 +342,34 @@ impl DimensionSource {
old.is_some() && old != counts(after)
})
}
/// The map that took the measured art from `before` to `after`, when every path it measures
/// went through one [`art_transform`] that reflects it (a negative determinant). None when a
/// measured path is unchanged, or when two of them went through different maps.
pub fn reflection(&self, before: &Document, after: &Document) -> Option<Affine> {
let mut first: Option<Affine> = None;
for id in self.nodes() {
let (old, new) = (before.node(id)?, after.node(id)?);
if std::ptr::eq(old, new) || old.path_data() == new.path_data() {
return None;
}
let xf = fitted(before, after, id, |xf| xf.determinant() < 0.0)?;
match first {
None => first = Some(xf),
Some(f) => {
// The linear parts and the translations, each against its own size.
let (a, b) = (f.as_coeffs(), xf.as_coeffs());
let differ = |range: std::ops::Range<usize>, tolerance: f64| {
let size = a[range.clone()].iter().map(|c| c.abs()).fold(1.0, f64::max);
a[range.clone()].iter().zip(&b[range]).any(|(p, q)| (p - q).abs() > tolerance * size)
};
if differ(0..4, 1e-9) || differ(4..6, 1e-9) {
return None;
}
}
}
}
first
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -348,6 +386,235 @@ impl PointRef {
}
}
/// The point of an anchor that an [`AnchorWeight`] names: the anchor, or one of its handles.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AnchorPart {
#[default]
Point,
In,
Out,
}
impl AnchorPart {
fn of(self, a: &Anchor) -> Point {
match self {
Self::Point => a.p,
Self::In => a.h_in,
Self::Out => a.h_out,
}
}
}
/// One anchor's share of a [`FreePoint`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnchorWeight {
pub subpath: usize,
pub anchor: usize,
/// The anchor itself, or its in or out handle.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub part: AnchorPart,
pub weight: f64,
}
/// A measured point that is not an anchor (a point on a segment, or a point a Smart Guide gave),
/// linked to one path so that it moves with it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum FreePoint {
/// A point on a segment at curve parameter `t`, 0 at the segment's first anchor and 1 at its
/// last. It stays on the segment when the segment's anchors or handles are edited.
OnSegment { edge: SegmentRef, t: f64 },
/// A weighted sum of two or three anchors or handles of one path, the weights adding up to 1,
/// plus `across` times the vector from the first anchor to the second turned a quarter turn,
/// from (x, y) to (-y, x), so that a vector pointing right in the y-down document space
/// turns to point down (two anchors only). When the
/// path is moved, scaled, rotated, reflected or sheared, a point held by three moves with
/// it. A point held by two and `across`, beside a straight path, moves, turns and scales
/// uniformly with it, and a reflection or a non-uniform scale moves it as a half turn or a
/// uniform scale would.
Anchors {
node: NodeId,
anchors: Vec<AnchorWeight>,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
across: f64,
},
}
/// A point of a path: (subpath, anchor, part, place).
type PathPoint = (usize, usize, AnchorPart, Point);
/// Every anchor of `path` in order, each followed by its in and out handles when `handles` is set.
fn path_points(path: &PathData, handles: bool) -> impl Iterator<Item = PathPoint> + Clone + '_ {
let parts: &'static [AnchorPart] = if handles { &[AnchorPart::Point, AnchorPart::In, AnchorPart::Out] } else { &[AnchorPart::Point] };
path.subpaths
.iter()
.enumerate()
.flat_map(move |(si, sp)| sp.anchors.iter().enumerate().flat_map(move |(ai, a)| parts.iter().map(move |&part| (si, ai, part, part.of(a)))))
}
/// Three points that span `points`: the first, the one farthest from it, and the one farthest
/// from the line through those two. None when every point is in one place.
fn spanning(points: impl Iterator<Item = PathPoint> + Clone) -> Option<[PathPoint; 3]> {
let first = points.clone().next()?;
let o = first.3;
let second = points.clone().max_by(|x, y| x.3.distance(o).total_cmp(&y.3.distance(o)))?;
let u = second.3 - o;
let span = u.hypot();
if !span.is_finite() || span <= 1e-6 {
return None;
}
let third = points.max_by(|x, y| u.cross(x.3 - o).abs().total_cmp(&u.cross(y.3 - o).abs()))?;
Some([first, second, third])
}
/// The map that takes the anchors and handles of path `node` in `before` to where they are in
/// `after`, when one affine map does that for every one of them: the path was moved, scaled,
/// rotated, reflected or sheared as a whole. None when its anchors changed in number, moved in
/// another way, or lie on one line with all their handles, as on a straight line: a reflection
/// across a line through such a path puts its points where a turn can put them too.
pub fn art_transform(before: &Document, after: &Document, node: NodeId) -> Option<Affine> {
fitted(before, after, node, |_| true)
}
/// [`art_transform`] when the map passes `wanted`. The map is found from three points, and
/// `wanted` is asked before every other point is checked against it.
fn fitted(before: &Document, after: &Document, node: NodeId, wanted: impl Fn(&Affine) -> bool) -> Option<Affine> {
let (old, new) = (before.node(node)?.path_data()?, after.node(node)?.path_data()?);
if old.subpaths.len() != new.subpaths.len() || old.subpaths.iter().zip(&new.subpaths).any(|(o, n)| o.anchors.len() != n.anchors.len()) {
return None;
}
let [o, f, g] = spanning(path_points(old, true))?;
let place = |q: PathPoint| new.subpaths.get(q.0).and_then(|sp| sp.anchors.get(q.1)).map(|a| q.2.of(a));
let (o2, f2, g2) = (place(o)?, place(f)?, place(g)?);
let (u, v) = (f.3 - o.3, g.3 - o.3);
let span = u.hypot();
if u.cross(v).abs() <= 1e-9 * span * span {
return None;
}
let basis = |u: Vec2, v: Vec2| Affine::new([u.x, u.y, v.x, v.y, 0.0, 0.0]);
let linear = basis(f2 - o2, g2 - o2) * basis(u, v).inverse();
let xf = Affine::translate(o2.to_vec2()) * linear * Affine::translate(-o.3.to_vec2());
if !xf.as_coeffs().iter().all(|c| c.is_finite()) || !wanted(&xf) {
return None;
}
let tolerance = 1e-6 * span.max(1.0);
path_points(old, true).zip(path_points(new, true)).all(|(o, n)| (xf * o.3).distance(n.3) <= tolerance).then_some(xf)
}
impl FreePoint {
/// Largest weight: a point far outside the anchors that hold it is not held.
const MAX_WEIGHT: f64 = 1e4;
/// The path it is linked to.
pub fn node(&self) -> NodeId {
match self {
Self::OnSegment { edge, .. } => edge.node,
Self::Anchors { node, .. } => *node,
}
}
/// `p` held against path `node`: three anchors that span the path; when all its anchors lie
/// on one line or in one place, as on an arch, three of its anchors and handles; when its
/// handles lie on that line too, or so nearly that the weights would be too large, two anchors
/// and `p`'s distance across that line. None when none of these holds `p`.
pub fn on(doc: &Document, node: NodeId, p: Point) -> Option<Self> {
let path = doc.node(node)?.path_data()?;
let weight = |(subpath, anchor, part, _): PathPoint, weight| AnchorWeight { subpath, anchor, part, weight };
for handles in [false, true] {
let Some([o, f, g]) = spanning(path_points(path, handles)) else { continue };
let (u, v) = (f.3 - o.3, g.3 - o.3);
let span = u.hypot();
let det = u.cross(v);
if det.abs() > 1e-9 * span * span {
let s = (p - o.3).cross(v) / det;
let t = u.cross(p - o.3) / det;
let anchors = vec![weight(o, 1.0 - s - t), weight(f, s), weight(g, t)];
// A nearly flat set of points gives weights too large to keep: the next fit is tried.
if let Some(held) = (Self::Anchors { node, anchors, across: 0.0 }).holding(doc, p, span) {
return Some(held);
}
}
}
// Every anchor and handle on one line, or nearly: along it from the first anchor, and across it.
let [o, f, _] = spanning(path_points(path, false))?;
let u = f.3 - o.3;
let span = u.hypot();
let (t, across) = ((p - o.3).dot(u) / (span * span), u.cross(p - o.3) / (span * span));
Self::Anchors { node, anchors: vec![weight(o, 1.0 - t), weight(f, t)], across }.holding(doc, p, span)
}
/// `p` on the segment `edge`, at the curve parameter of the segment's point nearest to it.
/// None when the segment is gone or `p` is not on it.
pub fn on_segment(doc: &Document, edge: &SegmentRef, p: Point) -> Option<Self> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
let sp = doc.node(edge.node)?.path_data()?.subpaths.get(edge.subpath)?;
if edge.segment >= sp.segment_count() {
return None;
}
let (a, b) = edge.endpoints(doc)?;
let t = sp.segment(edge.segment).nearest(p, 1e-12).t;
Self::OnSegment { edge: edge.clone(), t }.holding(doc, p, a.distance(b))
}
/// Itself when it is [`Self::valid`] and puts the point at `p`, within a tolerance that grows
/// with `span`, the size of the art that holds it.
fn holding(self, doc: &Document, p: Point, span: f64) -> Option<Self> {
let at = self.position(doc)?;
(at.distance(p) <= 1e-6 * span.max(1.0)).then_some(self)
}
/// Whether its numbers can be used: a finite `t` from 0 to 1 on a segment; or two or three
/// weights that add up to 1, with `across` set only for two, each finite and at most
/// [`Self::MAX_WEIGHT`] across.
pub fn valid(&self) -> bool {
match self {
Self::OnSegment { t, .. } => (0.0..=1.0).contains(t),
Self::Anchors { anchors, across, .. } => {
(2..=3).contains(&anchors.len())
&& anchors.iter().all(|w| w.weight.is_finite() && w.weight.abs() <= Self::MAX_WEIGHT)
&& (anchors.iter().map(|w| w.weight).sum::<f64>() - 1.0).abs() <= 1e-9
&& across.is_finite()
&& across.abs() <= Self::MAX_WEIGHT
&& (*across == 0.0 || anchors.len() == 2)
}
}
}
/// Where the point is now. None when its segment or an anchor is gone or the point is not
/// [`Self::valid`].
pub fn position(&self, doc: &Document) -> Option<Point> {
use vectorcraft_geom::kurbo::ParamCurve;
if !self.valid() {
return None;
}
let at = match self {
Self::OnSegment { edge, t } => {
let sp = doc.node(edge.node)?.path_data()?.subpaths.get(edge.subpath)?;
if edge.segment >= sp.segment_count() {
return None;
}
sp.segment(edge.segment).eval(*t)
}
Self::Anchors { node, anchors, across } => {
let path = doc.node(*node)?.path_data()?;
let place = |w: &AnchorWeight| path.subpaths.get(w.subpath).and_then(|sp| sp.anchors.get(w.anchor)).map(|a| w.part.of(a).to_vec2());
let mut at = Vec2::ZERO;
for w in anchors {
at += place(w)? * w.weight;
}
if *across != 0.0 {
let u = place(anchors.get(1)?)? - place(anchors.first()?)?;
at += Vec2::new(-u.y, u.x) * *across;
}
at.to_point()
}
};
(at.x.is_finite() && at.y.is_finite()).then_some(at)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Dimension {
@@ -441,6 +708,36 @@ impl Dimension {
self.offset = offset;
}
}
/// A linear dimension whose art was reflected, its points now moved from `old`'s: its line goes
/// to the side of the points that `image` (where the reflection put `old`'s line) is on, as far
/// past the outermost point on that side as `old`'s line was. A line that lay between the two
/// points is left as it is.
pub fn mirror_line(&mut self, old: &Dimension, image: Point) {
if self.mode != DimensionMode::Linear || old.mode != DimensionMode::Linear {
return;
}
let gap = {
let n = old.normal();
let across = |p: Point| p.to_vec2().dot(n);
let line = across(old.a) + old.offset;
let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b)));
if line >= high {
line - high
} else if line <= low {
low - line
} else {
return;
}
};
let n = self.normal();
let across = |p: Point| p.to_vec2().dot(n);
let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
let at = if 2.0 * across(image) >= low + high { high + gap } else { low - gap };
let offset = at - across(self.a);
if offset.is_finite() && offset.abs() <= 1e6 {
self.offset = offset;
}
}
/// Whether a linear dimension's line lies strictly between its two points along the normal.
fn line_between_points(&self) -> bool {
let n = self.normal();
@@ -525,10 +822,15 @@ impl Dimension {
}
pub fn resolve(&mut self, doc: &Document) -> Result<(), String> {
match &self.source {
Some(DimensionSource::Points { a, b, vertex }) => {
for (reference, point) in [(a, &mut self.a), (b, &mut self.b), (vertex, &mut self.vertex)] {
if let Some(r) = reference {
*point = r.position(doc).ok_or("Measured anchor no longer exists")?;
Some(DimensionSource::Points { a, b, vertex, free_a, free_b }) => {
for (reference, free, point) in [(a, free_a, &mut self.a), (b, free_b, &mut self.b), (vertex, &None, &mut self.vertex)] {
match (reference, free) {
// An end is an anchor or a free point, never both.
(Some(_), Some(_)) => return Err("Invalid measured point".into()),
(Some(r), None) => *point = r.position(doc).ok_or("Measured anchor no longer exists")?,
(None, Some(f)) if !f.valid() => return Err("Invalid measured point".into()),
(None, Some(f)) => *point = f.position(doc).ok_or("Measured anchor no longer exists")?,
(None, None) => {}
}
}
self.length = if self.mode == DimensionMode::Linear { self.measured() } else { self.a.distance(self.b) };
+3
View File
@@ -75,6 +75,7 @@ impl Document {
dimensions,
retired_artboard_id: _,
opened_artboard: _,
units_from_file: _,
index: _,
} = self;
*version == other.version
@@ -208,6 +209,7 @@ impl Document {
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
}],
layers: vec![],
swatches: swatches.into(),
@@ -256,6 +258,7 @@ impl Document {
dimensions: false,
retired_artboard_id: Default::default(),
opened_artboard: None,
units_from_file: false,
index: Default::default(),
};
let id = d.alloc_id();
+24 -4
View File
@@ -136,9 +136,11 @@ impl crate::Document {
}
}
/// The character style a graph's labels keep through regeneration once formatted (Format the text in graphs): the
/// value axis numbers, the category labels (category axis, radar spokes, pie names) and the legend labels (beside or
/// across the top, or in pie wedges). `None` draws the default 9 pt black.
/// The character style and anti-aliasing method a graph's labels keep through regeneration once formatted (Format
/// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the
/// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para`
/// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each
/// label's alignment.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct LabelStyles {
@@ -148,6 +150,22 @@ pub struct LabelStyles {
pub categories: Option<crate::CharStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub legend: Option<crate::CharStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub values_para: Option<crate::ParaStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub categories_para: Option<crate::ParaStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub legend_para: Option<crate::ParaStyle>,
/// The anti-aliasing method the value axis numbers keep once set (Character panel › Anti-aliasing Method).
/// `None` draws them Sharp.
#[serde(skip_serializing_if = "Option::is_none")]
pub values_anti_alias: Option<crate::text::TypeAntiAlias>,
/// The anti-aliasing method the category labels keep once set. `None` draws them Sharp.
#[serde(skip_serializing_if = "Option::is_none")]
pub categories_anti_alias: Option<crate::text::TypeAntiAlias>,
/// The anti-aliasing method the legend labels keep once set. `None` draws them Sharp.
#[serde(skip_serializing_if = "Option::is_none")]
pub legend_anti_alias: Option<crate::text::TypeAntiAlias>,
}
impl LabelStyles {
@@ -525,7 +543,9 @@ impl GraphSpec {
out.push_str(&field(self.categories.get(i).map(String::as_str).unwrap_or_default(), true));
out.push(',');
}
out.push_str(&r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::<Vec<_>>().join(","));
let line = r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::<Vec<_>>().join(",");
// A lone blank value would be an empty line, which readers skip; a quoted empty field keeps the row.
out.push_str(if line.is_empty() && !labelled { "\"\"" } else { &line });
out.push('\n');
}
out
+5
View File
@@ -339,6 +339,11 @@ pub struct Document {
/// names it as the file's active artboard. `None`: the first. Native files do not keep it.
#[serde(skip)]
pub opened_artboard: Option<u32>,
/// The file this document was read from recorded its units (a `.ai` file's
/// `%AI5_RulerUnits`): it opens in them. A file that records none opens in Preferences ›
/// Units › General (#5820). Native files do not keep it: they always keep their units.
#[serde(skip)]
pub units_from_file: bool,
/// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this
/// is set, so documents without any pay nothing for them.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
+26
View File
@@ -56,4 +56,30 @@ impl LayerColor {
LayerColor::Custom(c) => c,
}
}
/// The color as text: a preset's name from [`LAYER_COLORS`], else `#rrggbb` (lowercase).
pub fn label_text(self) -> String {
let preset = match self {
LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(i)),
LayerColor::Custom(_) => None,
};
preset.map_or_else(
|| {
let [r, g, b] = self.rgb();
format!("#{r:02x}{g:02x}{b:02x}")
},
|(name, _)| (*name).to_string(),
)
}
/// The color [`LayerColor::label_text`] names: a preset's name exactly as [`LAYER_COLORS`]
/// spells it, or `#rrggbb` with six hex digits. None for anything else.
pub fn from_label_text(s: &str) -> Option<Self> {
if let Some(i) = LAYER_COLORS.iter().position(|(name, _)| *name == s) {
return u8::try_from(i).ok().map(LayerColor::Preset);
}
let hex = s.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))?;
let byte = |k: usize| u8::from_str_radix(&hex[k..k + 2], 16).ok();
Some(LayerColor::Custom([byte(0)?, byte(2)?, byte(4)?]))
}
}
+4 -1
View File
@@ -373,7 +373,10 @@ impl Node {
NodeKind::SymbolInstance { symbol, xf } => {
let b = match symbols.and_then(|s| Some((s, s.art(symbol)?))) {
Some((s, art)) if !s.art_strokes() => xf.transform_rect_bbox(art.geometric),
Some((_, art)) if moves_only(*xf) => xf.transform_rect_bbox(art.visual),
// A symbol drawn at other than its natural size goes through its 9-slice guides.
Some((s, art)) if moves_only(*xf) && s.document().symbol_slice_map_of(symbol, art.geometric, *xf).is_none() => {
xf.transform_rect_bbox(art.visual)
}
Some((s, art)) => {
let placed = xf.transform_rect_bbox(art.geometric);
match s.placed_visual(symbol, *xf).or_else(|| s.sliced_visual(symbol, *xf)) {
+42
View File
@@ -159,6 +159,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud },
BuiltinStyleLibrary { id: "status-effects", name: "Status Effects", make: status_effects },
];
/// Built-in library `id`, made once.
@@ -482,6 +483,43 @@ fn game_hud() -> Vec<GraphicStyle> {
]
}
/// Status Effects: buffs and debuffs for RPG/gamedev art (original, catalogue stylize effects only).
fn status_effects() -> Vec<GraphicStyle> {
let stealth = GraphicStyle {
opacity: 0.45,
blend: BlendMode::Normal,
..style("Stealth Fade", vec![F(fill("#7f8c8d")), S(stroke("#2c3e50", 1.0))], vec![])
};
vec![
style(
"Poison Tint",
vec![F(fill("#2ecc71"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 80.0, "blur": 6.0, "color": "#58d68d"}))],
),
style(
"Freeze Edge",
vec![F(fill("#aed6f1")), S(stroke("#5dade2", 2.0))],
vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 70.0, "blur": 5.0, "color": "#d6eaf8", "source": "edge"}))],
),
style(
"Burn Aura",
vec![F(fill("#e67e22"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 8.0, "color": "#f39c12"}))],
),
style(
"Stun Pulse",
vec![F(fill("#f4d03f"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 7.0, "color": "#f7dc6f"}))],
),
stealth,
style(
"Shield Buff",
vec![F(fill("#85c1e9")), S(round("#2874a6", 2.0))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 70.0, "blur": 5.0, "color": "#5dade2"}))],
),
]
}
#[cfg(test)]
mod tests {
use super::*;
@@ -508,6 +546,10 @@ mod tests {
assert_eq!(game.name, "Game HUD");
let names: Vec<&str> = game.styles.iter().map(|g| g.name.as_str()).collect();
assert_eq!(names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]);
let status = builtin_style_library("status-effects").unwrap();
assert_eq!(status.name, "Status Effects");
let status_names: Vec<&str> = status.styles.iter().map(|g| g.name.as_str()).collect();
assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]);
}
#[test]
+47
View File
@@ -5,6 +5,52 @@ mod lookups;
mod slices;
mod units;
/// A guide label's text is a layer color's name or `#rrggbb`, and reads back as the same color;
/// other spellings, an alpha part and a short form are not labels.
#[test]
fn guide_label_text_names_a_layer_color_or_rgb() {
for (i, (name, _)) in LAYER_COLORS.iter().enumerate() {
let c = LayerColor::Preset(u8::try_from(i).unwrap());
assert_eq!(c.label_text(), *name);
assert_eq!(LayerColor::from_label_text(name), Some(c));
}
let custom = LayerColor::Custom([0x0a, 0xbc, 0xff]);
assert_eq!(custom.label_text(), "#0abcff");
assert_eq!(LayerColor::from_label_text("#0ABCff"), Some(custom));
// A preset past the layer colors has no name: its text is the color it draws in.
let [r, g, b] = LayerColor::Preset(200).rgb();
assert_eq!(LayerColor::Preset(200).label_text(), format!("#{r:02x}{g:02x}{b:02x}"));
for bad in ["red", "Red ", "", "#", "#fff", "#0abcff00", "0abcff", "#0abcfg", "#0abcff"] {
assert_eq!(LayerColor::from_label_text(bad), None, "{bad:?}");
}
}
/// An artboard's guide label: none unless set, left out of the JSON when none, and a preset past
/// the layer colors reading as none.
#[test]
fn artboard_guide_label_defaults_and_skips_in_json() {
let mut a = Document::new(100.0, 100.0).artboards[0].clone();
assert_eq!(a.guide_label, None);
let plain = serde_json::to_value(&a).unwrap();
assert!(plain.get("guide_label").is_none(), "{plain}");
a.guide_label = Some(LayerColor::Custom([1, 2, 3]));
let v = serde_json::to_value(&a).unwrap();
assert_eq!(v["guide_label"], serde_json::json!({"Custom": [1, 2, 3]}));
assert_eq!(serde_json::from_value::<Artboard>(v).unwrap(), a);
let read = |label: serde_json::Value| {
let mut v = plain.clone();
v["guide_label"] = label;
serde_json::from_value::<Artboard>(v).map(|a| a.guide_label)
};
assert_eq!(read(serde_json::json!({"Preset": 26})).unwrap(), Some(LayerColor::Preset(26)));
assert_eq!(read(serde_json::json!({"Preset": 27})).unwrap(), None);
assert_eq!(read(serde_json::json!({"Preset": 255})).unwrap(), None);
assert_eq!(read(serde_json::Value::Null).unwrap(), None);
assert!(read(serde_json::json!({"Preset": -1})).is_err());
assert!(read(serde_json::json!({"Tint": 1})).is_err());
assert_eq!(serde_json::from_value::<Artboard>(plain).unwrap().guide_label, None, "older files have none");
}
/// Zooming in on an inch ruler divided the inch into tenths (#2827). Its steps below an inch
/// are binary fractions now, and the minor ticks between them stay binary too; every other
/// unit is still read in tenths.
@@ -146,6 +192,7 @@ fn art_on_a_locked_artboard_cannot_be_selected_or_edited() {
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
});
let rect = |d: &mut Document, r: Rect, appearance: Appearance| {
let id = d.alloc_id();
+2 -2
View File
@@ -22,10 +22,10 @@ pub struct CharStyle {
/// Leading in points; None = Auto (120% of size).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub leading: Option<f64>,
/// Tracking in 1/1000 em.
/// Tracking in 1/1000 em; in horizontal type, of the em as [`Self::h_scale`] draws it.
#[serde(default)]
pub tracking: f64,
/// Manual pair spacing in 1/1000 em; None uses the automatic mode.
/// Manual pair spacing in 1/1000 em, as [`Self::tracking`]; None uses the automatic mode.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kerning: Option<f64>,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
+5 -3
View File
@@ -468,12 +468,14 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images
}
/// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in
/// `d` (named by their content), and a symbol instance stands for its symbol's art.
pub fn adjust_in_document(d: &mut Document, n: &Node) -> Option<Node> {
/// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art`
/// when given, otherwise the symbol's art with the instance's own appearance changes.
pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option<Node>) -> Option<Node> {
let art;
let src = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => {
let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n));
let symbol = symbol_art
.or_else(|| d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)));
art = crate::reshape::as_art(Some(d), n, symbol.as_ref())?;
&art
}
+2 -2
View File
@@ -112,7 +112,7 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
}
// Colour adjustments: the object recoloured (inside it too), then baked as it is.
if has_adjustment(n)
&& let Some(m) = adjust_in_document(d, n)
&& let Some(m) = adjust_in_document(d, n, None)
{
return Some(bake_node(d, &m).unwrap_or(m));
}
@@ -395,7 +395,7 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
if !kept {
return None;
}
reshape_leaves(&mut m, &fx, Some(d));
reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d));
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !is_geometry(&e.id));
m.appearance.items.clear();
m.appearance.contents_index = None;
+17 -3
View File
@@ -26,6 +26,10 @@ pub struct GeomContext<'a> {
/// The document that the swatches and patterns named by a live-effect plug-in that paints its
/// pieces are looked up in. Without one, a result that names any is refused.
pub doc: Option<&'a Document>,
/// The object, fill or stroke and effect index a deferred live-effect plug-in is listed by
/// ([`vectorcraft_plugins::deferred`]). When `None`, it is the object `seed` names, `item` and
/// the effect's index in the list being applied.
pub stage: Option<vectorcraft_plugins::deferred::Stage>,
}
impl<'a> GeomContext<'a> {
@@ -36,7 +40,17 @@ impl<'a> GeomContext<'a> {
_ => FillRule::NonZero,
};
let stroke = n.appearance.stroke().filter(|s| !s.paint.is_none() && s.width > 0.0);
Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None, doc: None }
Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None, doc: None, stage: None }
}
/// The context of effect `e`, one of `list`: unless [`Self::stage`] is set, a live-effect
/// plug-in there is listed by `e`'s index in `list`.
pub(crate) fn at(self, list: &[Effect], e: &Effect) -> Self {
let stage = self.stage.or_else(|| {
let effect = list.iter().position(|x| std::ptr::eq(x, e))?;
Some(vectorcraft_plugins::deferred::Stage { object: self.seed, effect, item: self.item })
});
Self { stage, ..self }
}
/// The context of the effects on `item`, one of the same object's appearance items: a
@@ -335,7 +349,7 @@ pub(crate) fn apply_geometry_carrying_within(
}
let p = merged_params(&e.id, &e.params);
let limit = *limit.get_or_insert_with(|| budget.at_least(Budget::of(path)));
if let Some(next) = apply_one(&e.id, &p, &cur, b, ctx, limit) {
if let Some(next) = apply_one(&e.id, &p, &cur, b, &ctx.at(effects, e), limit) {
if let Some(c) = carry.as_deref_mut() {
c.push(Carry::of(&e.id, &p, b, cur.bounds(), next.bounds(), ctx.seed));
}
@@ -377,7 +391,7 @@ fn builds_within(id: &str) -> bool {
fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, max: usize) -> PathData {
use util::{join, num};
if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) {
let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item };
let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item, at: ctx.stage };
return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints, ctx.doc).unwrap_or_else(|| path.clone());
}
match id {
+3 -3
View File
@@ -209,7 +209,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
Some(area) => Some(reshaped(&area, n, doc)),
None => {
let mut m = crate::reshape::outlined_members_with(None, doc, n, outline, nodes);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
// The group's own fills and strokes follow the effects as its members do.
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
@@ -225,7 +225,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
let art = h(n).filter(|art| nodes.charge(art))?;
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
crate::reshape::outline_nested_text(doc, &mut art, false);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, doc);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
// The art's own fills and strokes follow the effects as its members do.
if carry.moves(&art.appearance) {
carry.apply(&mut art.appearance);
@@ -738,7 +738,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
if !fx.is_empty() {
m = crate::reshape::outlined_members(doc, &m);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
// The group's own fills and strokes paint the members as a whole: their gradients follow
// the effects as the members' do.
if paint && carry.moves(&m.appearance) {
+3 -2
View File
@@ -161,7 +161,8 @@ pub fn any_plugin_paints_output() -> bool {
vectorcraft_plugins::registry::list().iter().any(|p| vectorcraft_plugins::effect::paints_output(&p.manifest().id))
}
/// The plug-in registry's revision, which changes whenever a plug-in is installed or removed.
/// Changes whenever a plug-in is installed or removed (the registry's revision), and when deferred
/// live-effect plug-in stages give results ([`vectorcraft_plugins::deferred::revision`]).
pub fn plugin_revision() -> u64 {
vectorcraft_plugins::registry::revision()
vectorcraft_plugins::registry::revision() ^ vectorcraft_plugins::deferred::revision().rotate_left(32)
}
+52 -28
View File
@@ -573,7 +573,7 @@ fn as_art_opts(
}
_ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?,
};
reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart, paint_doc);
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, apart, paint_doc);
if apart {
hoist_copies(&mut art);
}
@@ -636,21 +636,22 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
/// effects leave them as they are (a raster follows a non-affine map only as a mesh warp). The
/// paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path
/// whose effect would pass what the others leave of it keeps its shape. The swatches and patterns
/// that live-effect plug-ins painting their pieces name are looked up in `doc`
/// ([`reshape_leaves_apart`]).
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) {
reshape_leaves_within(art, fx, Budget::EFFECTS, doc);
/// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one
/// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]).
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) {
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc);
}
/// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and
/// strokes) follow the effects ([`crate::Carry`]).
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) -> crate::Carry {
reshape_leaves_within(art, fx, Budget::EFFECTS, doc)
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) -> crate::Carry {
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc)
}
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost.
#[cfg(test)]
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry {
reshape_leaves_apart(art, fx, budget, false, doc)
reshape_leaves_apart(art, fx, &[], budget, false, doc)
}
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
@@ -669,12 +670,15 @@ fn hoist_copies(art: &mut Node) {
}
}
/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost; with
/// `apart`, a Transform effect's copies of each path are objects
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
/// Returns how gradients that paint the art as a whole follow the effects.
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
/// Returns how gradients that paint the art as a whole follow the effects. A deferred live-effect
/// plug-in is listed by its index in `owner`, the effect list `fx` was taken from, or in `fx` when
/// `owner` does not hold it.
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
let mut whole = crate::Carry::default();
if fx.is_empty() {
return whole;
@@ -693,6 +697,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
});
let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
let style_safe = leaves_safe && !art_stroke;
let listed = fx;
let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe);
let fx = opt_fx.as_slice();
let seed = art.id.0;
@@ -703,12 +708,15 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
for e in fx {
let Some(bounds) = art.geometric_bounds() else { break };
let params = merged_params(&e.id, &e.params);
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
if let Some(plugin) = painted_plugin(e) {
let at = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
for_each_leaf(art, &mut |leaf| {
let Some((path, _)) = leaf_geometry(leaf) else { return };
let before = Budget::of(&path);
let room = max.minus(used.minus(before));
if let Some(made) = paint_leaf(leaf, plugin, &params, bounds, room, doc) {
if let Some(made) = paint_leaf(leaf, plugin, &params, bounds, room, doc, at) {
used = used.minus(before).plus(made);
}
});
@@ -778,7 +786,8 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
return;
}
}
let Some(out) = apply_one(&e.id, &params, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) }, room) else {
let stage = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
let Some(out) = apply_one(&e.id, &params, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else {
kept_ids.insert(leaf.id);
return;
};
@@ -1056,10 +1065,18 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
/// its own ([`vectorcraft_plugins::painted::appearance`]). The swatches and patterns the pieces
/// name must be in `doc`, and without one the pieces may name none. Returns what the pieces cost
/// ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, the pieces are
/// refused, or they would pass `budget`.
fn paint_leaf(leaf: &mut Node, plugin: &str, params: &serde_json::Value, bounds: Rect, budget: Budget, doc: Option<&Document>) -> Option<Budget> {
/// refused, or they would pass `budget`. A deferred run is listed by `at`.
fn paint_leaf(
leaf: &mut Node,
plugin: &str,
params: &serde_json::Value,
bounds: Rect,
budget: Budget,
doc: Option<&Document>,
at: Option<vectorcraft_plugins::deferred::Stage>,
) -> Option<Budget> {
let (path, rule) = leaf_geometry(leaf)?;
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None };
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None, at };
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
if !budget.fits(made) {
@@ -1097,18 +1114,18 @@ fn piece_cost(path: &PathData) -> Budget {
/// other fills and strokes; one that gives none keeps the leaf's. Returns
/// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails,
/// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass
/// `budget`.
/// `budget`. A deferred run is listed by `at`.
fn paint_piece(
leaf: &mut Node,
item: &AppearanceItem,
plugin: &str,
params: &serde_json::Value,
(plugin, params): (&str, &serde_json::Value),
bounds: Rect,
budget: Budget,
doc: Option<&Document>,
at: Option<vectorcraft_plugins::deferred::Stage>,
) -> Option<Budget> {
let (path, rule) = leaf_geometry(leaf)?;
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0) };
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0), at };
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
if !budget.fits(made) {
@@ -1241,6 +1258,8 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
};
let Some(tb) = g.bounds() else { continue };
let params = merged_params(&fx[at].id, &fx[at].params);
// Where each effect the piece keeps sits among the item's effects.
let kept: Vec<usize> = (0..at).filter(|&k| !is_geometry(&fx[k].id)).chain(at + 1..fx.len()).collect();
if let Some(plugin) = painted_plugin(&fx[at]) {
let mut it = item.clone();
let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect();
@@ -1250,7 +1269,8 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
carry.apply(&mut one);
}
let it = one.items.pop().unwrap_or(it);
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i) };
let stage = vectorcraft_plugins::deferred::Stage { object: ctx.seed, effect: at, item: Some(i) };
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i), at: Some(stage) };
let painted = vectorcraft_plugins::effect::apply_painted(plugin, &params, &g, tb, rule, paints, doc)
.map(|pieces| pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p))).collect::<Vec<_>>())
.filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus)));
@@ -1264,7 +1284,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
group.push(Arc::new(p));
}
let mut p = Node::group(leaf.id, group);
transform_piece(&mut p, ctx.seed, limit, used, doc);
transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc);
pieces.push(Arc::new(p));
continue;
}
@@ -1281,7 +1301,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
set_geometry(&mut p, g.clone(), rule);
let (made, _) = transform_leaf(&mut p, &g, map, copies, options, room);
*used = used.plus(made);
transform_piece(&mut p, ctx.seed, limit, used, doc);
transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc);
pieces.push(Arc::new(p));
}
if !plain.is_empty() {
@@ -1297,14 +1317,17 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
/// Apply the visible geometry effects left on the one fill or stroke of each path under `p` (a
/// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece:
/// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's
/// own effects reshape all its paths ([`reshape_leaves_within`]). Each path applies its own copy of
/// own effects reshape all its paths ([`reshape_leaves_carrying`]). Each path applies its own copy of
/// the effect, whose distances its Scale Strokes & Effects scaled. A Transform effect with
/// Transform Patterns or Scale Strokes & Effects on transforms each path as [`transform_leaf`] does.
/// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path
/// for each piece it returns ([`paint_piece`]). The geometry effects then leave the fills and
/// strokes; their other effects stay. The paths keep to `max` together with the rest of the art
/// (`used`), and the swatches and patterns painted pieces name must be in `doc`.
fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc: Option<&Document>) {
/// (`used`), and the swatches and patterns painted pieces name must be in `doc`. `(seed, source,
/// kept)`: the object's seed, the index in the object's appearance of the fill or stroke the
/// piece was made from, and the index among that item's effects of each effect the piece kept,
/// which a deferred live-effect plug-in is listed by.
fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), max: Budget, used: &mut Budget, doc: Option<&Document>) {
let mut count = 0;
for_each_leaf(p, &mut |l| {
if let Some(item) = l.appearance.items.first() {
@@ -1320,8 +1343,9 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc:
// What the other paths leave of the budget.
let before = Budget::of(&path);
let room = max.minus(used.minus(before));
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
if let Some(plugin) = painted_plugin(&e) {
if let Some(made) = paint_piece(leaf, &item, plugin, &merged_params(&e.id, &e.params), bounds, room, doc) {
if let Some(made) = paint_piece(leaf, &item, (plugin, &merged_params(&e.id, &e.params)), bounds, room, doc, Some(stage)) {
*used = used.minus(before).plus(made);
}
return;
@@ -1340,7 +1364,7 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc:
AppearanceItem::Stroke(s) => Some(s),
AppearanceItem::Fill(_) => None,
};
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc };
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc, stage: Some(stage) };
let mut carry = crate::Carry::default();
let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(&e), &path, bounds, &ctx, room, Some(&mut carry));
*used = used.minus(before).plus(Budget::of(&out));
+5 -1
View File
@@ -544,7 +544,11 @@ fn merge(chain: &[&Piece]) -> std::result::Result<TextObject, usize> {
for (k, w) in off.windows(2).enumerate() {
let (delta, Some(&(s, e))) = (w[1] - w[0], before.get(k)) else { continue };
if delta.abs() > 1e-9 {
edit::style_range(&mut m.runs, s, e, |st| st.tracking += delta / st.size.max(1e-6) * 1000.0);
// Thousandths of the em as the Horizontal Scale draws it (`spacing_scale`).
let vertical = m.vertical;
edit::style_range(&mut m.runs, s, e, |st| {
st.tracking += delta / (st.size * vectorcraft_text::spacing_scale(st, vertical)).max(1e-6) * 1000.0;
});
if !TRACKING.contains(&edit::style_at(&m.runs, s).tracking) {
return Err(k + 1);
}
@@ -176,6 +176,24 @@ fn combine_joins_only_pieces_on_one_line_turned_alike() {
assert!(other(s.execute("addon.cleanup.combineText", &json!({}))).contains("combine"));
}
/// Pieces in horizontally scaled type: the tracking that puts each back where it was is measured in
/// the em as the Horizontal Scale draws it (`vectorcraft_text::spacing_scale`), as layout spaces it.
#[test]
fn combine_puts_horizontally_scaled_pieces_back_where_they_were() {
let mut s = session();
let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20}));
let b = text(&mut s, json!({"x": 160, "y": 100, "text": "Right", "size": 20}));
for id in [a, b] {
s.execute("text.setRangeStyle", &json!({"id": id.0, "hScale": 200})).unwrap();
}
let was = glyphs(&s, &[a, b]);
select(&mut s, &[a, b]);
let r = s.execute("addon.cleanup.combineText", &json!({})).unwrap();
assert_eq!(ids(&r), [a]);
assert_eq!(obj(&s, a).plain_text(), "Left Right");
assert_same_places(&was, &glyphs(&s, &[a]));
}
/// Join Point Text makes one object of stacked one-line pieces: lines top to bottom as paragraphs,
/// pieces on a line left to right, each line's baseline where it was (its leading is the distance
/// from the line above), in one undo step. A piece turned unlike the top-left one stays.
+7 -2
View File
@@ -939,7 +939,10 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
})?;
s.remap_appearance_item(&ids, |a| (!idx.contains(&a)).then(|| a - idx.iter().filter(|i| **i < a).count()));
// The rows removed from the active row's object, which need not come first in `ids`.
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
let gone = active.and_then(|a| ids.iter().position(|id| *id == a)).and_then(|k| per.get(k)).unwrap_or(&idx);
s.remap_appearance_item(&ids, |a| (!gone.contains(&a)).then(|| a - gone.iter().filter(|i| **i < a).count()));
ok()
}
@@ -1023,10 +1026,12 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
let m = idx.len();
let landed = active_at.or(first_at);
// The rows copied in the active row's object, which need not come first in `ids`.
let copied = active.and_then(|a| ids.iter().position(|id| *id == a)).and_then(|k| per.get(k)).unwrap_or(&idx);
s.remap_appearance_item(&ids, |a| {
Some(match to {
Some(_) => a + if landed.is_some_and(|at| at <= a) { m } else { 0 },
None => a + idx.iter().filter(|i| **i < a).count(),
None => a + copied.iter().filter(|i| **i < a).count(),
})
});
ok()
+1 -1
View File
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Break Link to Symbol",
[],
None,
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask → {ids}",
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask; a hidden or locked instance's art stays hidden or locked and is not selected → {ids}",
has_selection,
symbol_break_link
),
+23 -8
View File
@@ -390,10 +390,11 @@ fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 {
most.saturating_add(1).saturating_add(mask)
}
/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the
/// art's ids. Fails before any edit when the instances together would make more than
/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). A hidden or
/// locked instance's art stays hidden or locked. Returns each replaced instance's id with its art's
/// id. Fails before any edit when the instances together would make more than
/// [`MAX_EXPAND_NODES`] objects.
fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId>> {
fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<(NodeId, NodeId)>> {
let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, own)));
if total > MAX_EXPAND_NODES as u64 {
return Err(EngineError::Other("Too many pieces to make at once".into()));
@@ -401,12 +402,14 @@ fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId
let mut out = vec![];
for id in ids {
let Some(inst) = d.node(*id).cloned() else { continue };
let Some(art) = expanded_instance(d, &inst, own) else { continue };
let Some(mut art) = expanded_instance(d, &inst, own) else { continue };
let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?;
art.visible &= inst.visible;
art.locked |= inst.locked;
let aid = art.id;
d.remove(*id)?;
d.insert(par, idx, art)?;
out.push(aid);
out.push((*id, aid));
}
Ok(out)
}
@@ -491,10 +494,22 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(EngineError::Other("no symbol instances selected".into()));
}
let iso = s.doc()?.isolation;
let out = s.edit("Break Link to Symbol", |d, sel| {
let out = break_links(d, &ids, true)?;
sel.set(out.iter().copied());
Ok(out)
let fresh = d.new_art.get();
let made = break_links(d, &ids, true)?;
// Art that is hidden or locked, or in a hidden or locked group or layer, is left out of the
// selection, as is art on a locked artboard unless the instance it replaces was new art.
let locks = d.locked_artboards();
sel.set(made.iter().filter_map(|(inst, art)| {
let keep = if fresh.contains(inst) {
crate::cmd::select::is_selectable_on_any_artboard(d, iso, *art)
} else {
crate::cmd::select::is_selectable(d, iso, &locks, *art)
};
keep.then_some(*art)
}));
Ok(made.into_iter().map(|(_, art)| art).collect::<Vec<_>>())
})?;
Ok(json!({ "ids": ids_json(&out) }))
}
+96 -3
View File
@@ -21,8 +21,8 @@ use serde_json::{Map, Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{
Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration,
TextStyleDef,
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice,
SymbolRegistration, TextStyleDef,
};
use super::super::brushsym::{set_natural_size, stored_natural_size};
@@ -140,6 +140,31 @@ fn node_refs(n: &Node, f: Visit) {
});
}
/// The `(name, xml)` of `e` when it is an SVG filter effect.
fn filter_of(e: &Effect) -> Option<(String, String)> {
let text = |k: &str| e.params.get(k).and_then(Value::as_str).map(str::to_string);
if e.id != Appearance::SVG_FILTER {
return None;
}
Some((text("name")?, text("xml")?))
}
/// The SVG filter effects of appearance `a` (its own and its fills' and strokes').
fn appearance_filters(a: &Appearance, out: &mut BTreeSet<(String, String)>) {
let items = a.items.iter().flat_map(|i| i.effects().iter());
out.extend(a.effects.iter().chain(items).filter_map(filter_of));
}
/// The SVG filter effects in the subtree of `n` (opacity-mask art included).
fn node_filters(n: &Node, out: &mut BTreeSet<(String, String)>) {
n.walk(&mut |m| {
appearance_filters(&m.appearance, out);
if let Some(mask) = &m.extras().mask {
node_filters(&mask.art, out);
}
});
}
/// A global or spot colour of its own (not a tint of another swatch): what colours link to.
fn is_base(w: &Swatch) -> bool {
(w.global || w.spot) && matches!(w.paint, Paint::Solid { swatch: None, .. })
@@ -527,6 +552,9 @@ impl SwatchChoices {
#[derive(Clone, Debug, Default)]
struct Relink {
renames: BTreeMap<Res, BTreeMap<String, String>>,
/// An SVG filter effect's `(name, xml)` on the clipboard → its `(name, xml)` in the document
/// ([`Clipboard::filter_links`]).
filters: BTreeMap<(String, String), (String, String)>,
/// Graphic style id on the clipboard → its id in the document. Links to other ids are dropped.
styles: BTreeMap<u32, u32>,
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
@@ -566,6 +594,15 @@ impl Relink {
});
}
fn appearance(&self, a: &mut Appearance) {
if !self.filters.is_empty() {
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
for e in a.effects.iter_mut().chain(items) {
if let Some((name, xml)) = filter_of(e).and_then(|k| self.filters.get(&k)) {
e.params["name"] = json!(name);
e.params["xml"] = json!(xml);
}
}
}
for it in &mut a.items {
self.paint(it.paint_mut());
if let AppearanceItem::Stroke(l) = it
@@ -1013,6 +1050,7 @@ impl Clipboard {
/// of definitions that use each other is matched on its own ([`loop_groups`]).
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Imported {
let mut out = Imported::default();
out.relink.filters = self.filter_links(d, same_doc);
self.import_images(d, used, same_doc, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
@@ -1170,10 +1208,65 @@ impl Clipboard {
}
vectorcraft_brush::store(d, &lib);
}
out.relinks = !(out.relink.renames.is_empty() && out.relink.styles.is_empty() && out.relink.colors.is_empty() && used.styles.is_empty());
out.relinks = !(out.relink.renames.is_empty()
&& out.relink.filters.is_empty()
&& out.relink.styles.is_empty()
&& out.relink.colors.is_empty()
&& used.styles.is_empty());
out
}
/// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's
/// filter of its name; one that draws another definition than that filter takes the document's
/// filter when pasted back into the document it came from, and elsewhere keeps its own under a
/// free name, so editing or deleting the document's filter leaves it alone. When that name would
/// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else
/// a free letter or digit; the filter's id is always its name.
fn filter_links(&self, d: &Document, same_doc: bool) -> BTreeMap<(String, String), (String, String)> {
let mut found = BTreeSet::new();
for n in &self.nodes {
node_filters(n, &mut found);
}
for s in &self.symbols {
node_filters(&s.art, &mut found);
}
for a in self.patterns.iter().flat_map(|p| p.art.iter()) {
node_filters(a, &mut found);
}
for a in self.brushes.iter().flat_map(Brush::art) {
node_filters(a, &mut found);
}
for g in &self.graphic_styles {
appearance_filters(&g.appearance, &mut found);
}
let mut taken: BTreeSet<String> = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect();
let mut links = BTreeMap::new();
for (name, xml) in found {
let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue };
let to = if same_doc {
(name.clone(), held.xml.clone())
} else {
// Free names made from the starts of the name, longest first, then free letters and
// digits: the first under which the filter still draws.
let mut ends: Vec<usize> = name.char_indices().map(|(i, _)| i).skip(1).collect();
ends.push(name.len());
let starts = ends.iter().rev().filter_map(|&end| name.get(..end).map(str::trim_end)).filter(|b| !b.is_empty());
let shorter = starts.map(|b| unique_name(b, |n| taken.contains(n)));
let single = ('a'..='z').chain('0'..='9').map(String::from).filter(|n| !taken.contains(n));
let renamed = shorter.chain(single).find_map(|new| {
let drawn = vectorcraft_render::effects::svg_filter::with_id(&xml, &new)
.filter(|x| vectorcraft_render::effects::svg_filter::check(x).is_ok())?;
Some((new, drawn))
});
let Some((new, drawn)) = renamed else { continue };
taken.insert(new.clone());
(new, drawn)
};
links.insert((name, xml), to);
}
links
}
/// Image blobs: a different blob under a key the document uses gets a new key.
fn import_images(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) {
for (key, blob) in self.images.iter().filter(|(k, _)| used.has(Res::Image, k)) {
@@ -478,6 +478,32 @@ fn an_opened_file_measures_its_type_in_its_own_composite_fonts() {
assert_eq!(actual.cached_bounds, Some(expected));
}
/// Threaded type read from a file flows through its frames in the file's own composite fonts, when
/// no open document defines them.
#[test]
fn an_opened_file_flows_its_threads_in_its_own_composite_fonts() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Threaded")]})).unwrap();
let story = "The quick brown fox jumps over the lazy dog and keeps running. ".repeat(4);
let a = s
.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 20, "font": "CF Threaded", "area": {"width": 150, "height": 60}}))
.unwrap()["id"]
.as_u64()
.unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 300})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
let first = text(&s, a).plain_text();
assert!(!first.is_empty() && first.len() < story.len());
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
// A new front document without the font: the font database no longer holds it.
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert!(vectorcraft_text::FontDb::global().composite_font("CF Threaded").is_none());
let file = crate::cmd::fileio::read_for_open("threaded.vectorcraft", &bytes, None, &json!({}), false, false).unwrap();
crate::cmd::fileio::open_read(&mut s, file).unwrap();
assert_eq!(text(&s, a).plain_text(), first);
}
/// A document replaced while in the back (File › Revert) is measured in its own composite fonts
/// when it comes to the front, not in the front document's.
#[test]
+163 -14
View File
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Dimension",
[],
None,
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
has_doc,
create
),
@@ -231,9 +231,10 @@ fn apply_to_all(s: &mut Session, p: &Value) -> Result<Value> {
fn replace(doc: &mut Document, id: NodeId, dim: Dimension) -> Result<()> {
let old: Vec<NodeId> = doc.node(id).and_then(Node::children).map(|ch| ch.iter().map(|n| n.id).collect()).unwrap_or_default();
let children = artwork(doc, &dim, &old)?;
let name = format!("Dimension · {}", dim.label().map_err(error)?);
if let Some(n) = doc.node_mut(id) {
n.kind = NodeKind::Group { children, clip: false };
n.name = Some(format!("Dimension · {}", dim.label().map_err(error)?));
n.name = Some(name);
n.extras_mut().dimension = Some(Box::new(dim));
}
Ok(())
@@ -271,8 +272,9 @@ impl EndedLink {
}
/// The [`reached`] dimensions become plain groups, whose art does not redraw or follow what it
/// measured. A command that replaces art calls this before it changes anything, since replacing
/// the art a dimension measures would remove the dimension, and then [`restore_unchanged`].
/// measured. A command that replaces art calls this before it changes anything and
/// [`restore_unchanged`] after, so that a dimension whose own art the command changed stays a
/// plain group.
pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec<EndedLink> {
let mut ended = Vec::new();
for id in reached(doc, roots) {
@@ -285,18 +287,156 @@ pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec<EndedLink>
ended
}
/// The dimensions in `ended` whose art is as it was are live again.
pub(crate) fn restore_unchanged(doc: &mut Document, ended: Vec<EndedLink>) {
/// The dimensions in `ended` whose own art is as it was are live again. One whose measured art the
/// command changed from `before` so that the art no longer fits its link stays where it was, no
/// longer linked, as [`refresh`] leaves a dimension whose art was deleted.
pub(crate) fn restore_unchanged(before: &Document, doc: &mut Document, ended: Vec<EndedLink>) {
for e in ended {
if doc.node(e.id).and_then(Node::children).is_some_and(|art| *art == e.art)
&& let Some(n) = doc.node_mut(e.id)
{
n.extras_mut().dimension = Some(Box::new(e.recipe));
if !doc.node(e.id).and_then(Node::children).is_some_and(|art| *art == e.art) {
continue;
}
let recipe = if e.source_kept(before, doc) { e.recipe } else { unlinked(&e.recipe) };
if let Some(n) = doc.node_mut(e.id) {
n.extras_mut().dimension = Some(Box::new(recipe));
doc.dimensions = true;
}
}
}
/// `old` where it was, no longer linked. A move it had on its own and not yet drawn is kept when
/// the moved dimension is valid.
fn unlinked(old: &Dimension) -> Dimension {
let mut unlinked = old.clone();
unlinked.source = None;
unlinked.moved = None;
if let Some(v) = old.moved {
let mut shifted = unlinked.clone();
(shifted.a, shifted.b, shifted.vertex) = (shifted.a + v, shifted.b + v, shifted.vertex + v);
if shifted.validate().is_ok() {
unlinked = shifted;
}
}
unlinked
}
/// The whole dimensions under `roots` that are selected together with art they measure (art under
/// `roots`), each one a root or held by groups without fills, strokes or effects of their own.
/// Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave their
/// lines and label as they are. A group with an appearance of its own changes everything it holds
/// when it expands, its dimensions included.
pub(crate) fn with_their_art(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
if !doc.dimensions {
return Vec::new();
}
let mut found = Vec::new();
for root in roots {
let Some(n) = doc.node(*root) else { continue };
n.walk(&mut |c| {
if let Some(source) = c.extras().dimension.as_ref().and_then(|d| d.source.as_ref()) {
found.push((*root, c.id, source.nodes()));
}
});
}
let under_roots = |id: NodeId| doc.ancestry(id).is_some_and(|a| a.iter().any(|a| roots.contains(a)));
found
.into_iter()
.filter(|(root, id, _)| {
let Some(ancestry) = doc.ancestry(*id) else { return false };
let from = ancestry.iter().position(|a| a == root).unwrap_or(ancestry.len());
ancestry.get(from..ancestry.len().saturating_sub(1)).unwrap_or_default().iter().all(|a| doc.node(*a).is_some_and(plain_group))
})
.filter(|(_, _, measured)| measured.iter().any(|m| under_roots(*m)))
.map(|(_, id, _)| id)
.collect()
}
/// A group or layer without fills, strokes or effects of its own.
fn plain_group(n: &Node) -> bool {
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && n.appearance.items.is_empty() && n.appearance.effects.is_empty()
}
/// A dimension [`lift`] took out of the document, with its place, the export assets that list it or
/// its parts (with their places in the asset list) and its parts' variable bindings.
pub(crate) struct Lifted {
parent: Option<NodeId>,
index: usize,
node: Arc<Node>,
assets: Vec<(usize, vectorcraft_doc::assets::ExportAsset)>,
bindings: Vec<(NodeId, std::collections::BTreeSet<String>)>,
}
impl Lifted {
pub(crate) fn id(&self) -> NodeId {
self.node.id
}
}
/// Takes the [`with_their_art`] dimensions under `roots` out of `doc`, so a command that replaces
/// art does not reach them; [`put_back`] puts them back.
pub(crate) fn lift(doc: &mut Document, roots: &[NodeId]) -> Vec<Lifted> {
let mut lifted = Vec::new();
for id in with_their_art(doc, roots) {
let Some((parent, index, _)) = doc.position(id) else { continue };
let mut parts = std::collections::BTreeSet::new();
if let Some(n) = doc.node(id) {
n.walk(&mut |c| {
parts.insert(c.id);
});
}
let assets = doc.assets.iter().enumerate().filter(|(_, a)| a.nodes.iter().any(|n| parts.contains(n))).map(|(i, a)| (i, a.clone())).collect();
let bindings = doc.variables.bindings.iter().filter(|(n, _)| parts.contains(n)).map(|(n, b)| (*n, b.clone())).collect();
if let Ok(node) = doc.remove(id) {
lifted.push(Lifted { parent, index, node, assets, bindings });
}
}
lifted
}
/// Each dimension [`lift`] took out, as it was, back in its place in `doc`, with its parts back in
/// the export assets that listed them and their variable bindings back: edits made while it was out
/// let go of them. A dimension whose group is gone goes on top of the first layer.
pub(crate) fn put_back(doc: &mut Document, lifted: Vec<Lifted>) {
for l in lifted.into_iter().rev() {
let parent = if doc.children(l.parent).is_some() { l.parent } else { doc.layers.first().map(|layer| layer.id) };
let Ok(ch) = doc.children_mut(parent) else { continue };
let i = if parent == l.parent { l.index.min(ch.len()) } else { ch.len() };
ch.insert(i, l.node);
doc.dimensions = true;
for (at, saved) in l.assets {
let there: Vec<NodeId> = saved.nodes.iter().copied().filter(|n| doc.node(*n).is_some()).collect();
if let Some(a) = doc.assets.iter_mut().find(|a| a.id == saved.id) {
for (k, n) in there.iter().enumerate() {
if !a.nodes.contains(n) {
let k = k.min(a.nodes.len());
a.nodes.insert(k, *n);
}
}
} else if !there.is_empty() {
let at = at.min(doc.assets.len());
doc.assets.insert(at, vectorcraft_doc::assets::ExportAsset { nodes: there, ..saved });
}
}
for (n, b) in l.bindings {
doc.variables.bindings.entry(n).or_insert(b);
}
}
}
/// `doc` without the [`with_their_art`] dimensions under `roots`, to see what a command that leaves
/// them alone would change: `doc` itself when there are none.
pub(crate) fn without_kept<'a>(doc: &'a Document, roots: &[NodeId]) -> std::borrow::Cow<'a, Document> {
let ids = with_their_art(doc, roots);
if ids.is_empty() {
return std::borrow::Cow::Borrowed(doc);
}
let mut view = doc.clone();
for id in ids {
// A dimension already gone (inside another one removed) needs nothing more.
let _ = view.remove(id);
}
std::borrow::Cow::Owned(view)
}
/// Called inside every edit, so dimensions and their undo history stay in step with the art they
/// measure. Returns at once in documents without dimensions.
pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
@@ -315,18 +455,27 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
let mut next = old.clone();
let moved = next.moved.take();
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || next.resolve(doc).is_err() {
// A deleted/degenerate source has no valid measurement. Remove its annotation in
// this same undo step instead of keeping a silently wrong number.
doc.remove(id)?;
// The art it measured was deleted, or rebuilt with other anchors, or no longer fits
// (an ellipse that was a circle): it stays where it was, no longer linked, in this
// same undo step, rather than attaching to a different edge.
if replace(doc, id, unlinked(&old)).is_err()
&& let Some(n) = doc.node_mut(id)
{
// Its recipe cannot be drawn again: its art stays as it is, as a plain group.
n.extras_mut().dimension = None;
}
changed = true;
continue;
}
next.keep_gap(&old);
if let Some(xf) = next.source.as_ref().and_then(|s| s.reflection(before, doc)) {
next.mirror_line(&old, xf * old.handle());
}
// Moved on its own (the art it measures stayed put): it keeps its new place.
if let Some(v) = moved
&& (next.a, next.b, next.vertex) == (old.a, old.b, old.vertex)
{
next.place(next.handle() + v);
next.place(old.handle() + v);
if next.resolve(doc).is_err() {
next = old.clone();
next.moved = None;
+179 -11
View File
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand Appearance",
["Object"],
None,
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
can_expand,
expand_appearance
),
@@ -109,9 +109,155 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
move_effect
),
cmd!(
query "effect.deferredStatus",
"Deferred Effects",
[],
None,
"{} the live-effect plug-in stages the active document left undrawn: while a document is drawn on screen, the plug-in effects of its first view share a 2,000 ms budget (each run also keeps to its own 5,000 ms limit); a stage left out for want of time, or one that times out, fails or has no plug-in, draws its input art unchanged and stays listed until it gives a result (Effect › Refresh Deferred Effects, an edit to its input or parameters, or an export, which runs every stage under the per-call limit), or until its object is deleted or its effect is removed, moved or hidden (or its fill or stroke is hidden) → {budgetMs: 2000, effects: [{objectId (also an object in the art of a symbol, pattern, brush or opacity mask), effectIndex (in the object's effects, or in the fill's or stroke's), item? (the fill or stroke whose effect it is), pluginId, reason: budget|timeout|missing|failed|safeMode}]} (empty: none)",
has_doc,
deferred_status
),
cmd!(
"effect.refreshDeferred",
"Refresh Deferred Effects",
["Effect"],
None,
"{ids?: [object id] (objects of the document; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
has_deferred,
refresh_deferred
),
]
}
/// The active document has deferred live-effect plug-in stages ([`deferred_status`]).
fn has_deferred(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if deferred_effects(&st.doc, &st.plugin_effects).is_empty() { Err("no plug-in effect is deferred".into()) } else { Ok(()) }
}
/// The objects the deferred stages of `fx` name, by id, each with whether it is in `d`'s layers.
/// An object that is not is looked for in the art `d` draws from elsewhere, where live-effect
/// plug-ins run too: the art of its symbols, patterns and brushes, and opacity masks.
fn stage_objects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> std::collections::HashMap<u64, (Arc<Node>, bool)> {
let mut out = std::collections::HashMap::new();
let mut rest = Vec::new();
for object in fx.list().into_iter().map(|x| x.stage.object) {
match d.node_arc(NodeId(object)) {
Some(n) => {
out.insert(object, (n.clone(), true));
}
None => rest.push(object),
}
}
if rest.is_empty() {
return out;
}
let brushes = vectorcraft_brush::library(d);
let symbols = d.symbols.iter().map(|s| &*s.art);
let patterns = d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a));
let layers = d.layers.iter().map(|a| &**a);
let mut look = |n: &Node| {
if rest.contains(&n.id.0) {
out.entry(n.id.0).or_insert_with(|| (Arc::new(n.clone()), false));
}
};
for a in symbols.chain(patterns).chain(brushes.iter().flat_map(|b| b.art())).chain(layers) {
vectorcraft_doc::swatches::walk_with_masks(a, &mut look);
}
out
}
/// Is plug-in `plugin`'s effect at `stage`'s place in `n` (`None`: no such object), and visible,
/// on a visible fill or stroke when it is one's?
fn stage_holds(n: Option<&Node>, stage: vectorcraft_plugins::deferred::Stage, plugin: &str) -> bool {
let Some(n) = n else { return false };
let list = match stage.item {
None => Some(n.appearance.effects.as_slice()),
Some(i) => n.appearance.items.get(i).filter(|it| it.visible()).map(|it| it.effects().as_slice()),
};
list.and_then(|l| l.get(stage.effect)).is_some_and(|e| e.visible && e.id == vectorcraft_plugins::effect::effect_id(plugin))
}
/// Drops the records of `fx`'s stages whose object or plug-in effect is no longer at their place
/// in `d` ([`stage_holds`]), and gives the objects of the others ([`stage_objects`]).
fn prune(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> std::collections::HashMap<u64, (Arc<Node>, bool)> {
let objects = stage_objects(d, fx);
fx.retain(|stage, plugin| stage_holds(objects.get(&stage.object).map(|(n, _)| &**n), stage, plugin));
objects
}
/// The deferred stages of `d` as `effect.deferredStatus` lists them. The records of stages whose
/// object or plug-in effect is no longer at their place in `d` are dropped first.
fn deferred_effects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) -> Vec<Value> {
prune(d, fx);
fx.list()
.into_iter()
.map(|x| {
let mut v = json!({"objectId": x.stage.object, "effectIndex": x.stage.effect, "pluginId": x.plugin, "reason": x.reason.name()});
if let Some(i) = x.stage.item {
v["item"] = json!(i);
}
v
})
.collect()
}
/// `effect.deferredStatus`.
fn deferred_status(s: &mut Session, _: &Value) -> Result<Value> {
let st = s.doc()?;
Ok(json!({"budgetMs": vectorcraft_plugins::deferred::OPENING_BUDGET_MS, "effects": deferred_effects(&st.doc, &st.plugin_effects)}))
}
/// Draws `n` alone, small, as the canvas would (its live-effect plug-ins run inside the view that
/// applies): what matters is that it is drawn, not its pixels. Is every part of it drawn, none left
/// out for its size?
fn draw_small(renderer: &mut vectorcraft_render::Renderer, doc: &Document, n: &Arc<Node>) -> bool {
let Some(b) = n.geometric_bounds() else { return false };
let scale = 64.0 / b.width().max(b.height()).max(1.0);
let view = vectorcraft_geom::Affine::scale(scale) * vectorcraft_geom::Affine::translate((1.0 - b.x0, 1.0 - b.y0));
renderer.stats = Default::default();
renderer.render_node(doc, n, 66, 66, view);
renderer.stats.culled == 0
}
/// `effect.refreshDeferred`: each object of the document's layers is drawn again alone, small,
/// inside the document's view, so its stages are run with the input they were deferred with; a
/// hidden object, or one in a hidden layer or group, is not drawn. An object in the art of a
/// symbol, pattern, brush or opacity mask runs where that art is used: the visible layers are
/// drawn then. A stage input left out of a small drawing for its size stays deferred.
fn refresh_deferred(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let (doc, fx) = (st.doc.clone(), st.plugin_effects.clone());
let ids = super::named_ids(p)?;
let objects = prune(&doc, &fx);
if let Some(id) = ids.iter().flatten().find(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)) {
return Err(EngineError::NoNode(*id));
}
let ids: Option<Vec<u64>> = ids.map(|ids| ids.iter().map(|id| id.0).collect());
let counts = fx.refresh(ids.as_deref(), |targets| {
let mut renderer = vectorcraft_render::Renderer::new();
let mut whole = Vec::new();
fx.view(|| {
let mut elsewhere = false;
for id in targets {
match objects.get(id) {
Some((n, true)) if doc.is_visible(NodeId(*id)) && draw_small(&mut renderer, &doc, n) => whole.push(*id),
Some((_, false)) => elsewhere = true,
_ => {}
}
}
if elsewhere {
for layer in doc.layers.iter().filter(|l| l.visible) {
draw_small(&mut renderer, &doc, layer);
}
}
});
whole
});
Ok(json!({"refreshed": counts.refreshed, "stillDeferred": counts.still_deferred, "failed": counts.failed}))
}
fn ids_json(ids: &[NodeId]) -> Value {
json!(ids.iter().map(|i| i.0).collect::<Vec<_>>())
}
@@ -674,11 +820,19 @@ fn load_texture(params: &mut Value, cmd: &str) -> Result<()> {
/// fills, strokes or effects of its own or such members, other objects with effects, or type with
/// fills or strokes of its own?
pub(crate) fn expandable(n: &Node) -> bool {
expandable_except(n, &[])
}
/// [`expandable`], leaving out the objects `skip` lists and what they hold.
pub(crate) fn expandable_except(n: &Node, skip: &[NodeId]) -> bool {
if skip.contains(&n.id) {
return false;
}
match &n.kind {
NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } => false,
NodeKind::Path { .. } | NodeKind::Compound { .. } => !n.appearance.is_basic() || vectorcraft_brush::has_brush(n),
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
!n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable(c))
!n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable_except(c, skip))
}
NodeKind::Text(_) => !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(),
NodeKind::Image(_) => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(),
@@ -688,9 +842,11 @@ pub(crate) fn expandable(n: &Node) -> bool {
fn can_expand(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
let d = &s.doc().map_err(|e| e.to_string())?.doc;
let ids = appearance_targets(s, &Value::Null).map_err(|e| e.to_string())?;
if ids.iter().filter_map(|id| d.node(*id)).any(expandable) {
let d = &s.doc().map_err(|e| e.to_string())?.doc;
// A dimension selected with the art it measures is left as it is.
let kept = super::dimension::with_their_art(d, &ids);
if ids.iter().filter_map(|id| d.node(*id)).any(|n| expandable_except(n, &kept)) {
Ok(())
} else {
Err("select (or target) objects whose appearance isn't basic".into())
@@ -814,8 +970,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
let mut changed = false;
// Is `n` in `out` yet?
let mut listed_n = false;
// A symbol instance's fill tints its art before the adjustment, as the canvas draws it.
let symbol_art = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if effects::has_adjustment(&n) => {
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_render::instance_art(&s.art, &n))
}
_ => None,
};
if effects::has_adjustment(&n)
&& let Some(m) = effects::adjust_in_document(d, &n)
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
{
out.push((id, 0));
listed_n = true;
@@ -968,7 +1131,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
// In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the
// geometry it hasn't changed.
if vectorcraft_plugins::safe_mode::active() {
let d = &s.doc()?.doc;
// A dimension selected with the art it measures is left as it is.
let d = &*super::dimension::without_kept(&s.doc()?.doc, &roots);
let mut seen = std::collections::HashSet::new();
if roots.iter().filter_map(|id| d.node(*id)).any(|n| holds_plugin_effect(d, n, false, &mut seen)) {
return Err(EngineError::Other("Expand Appearance: a plug-in effect in the selection can't be expanded in Safe Mode".into()));
@@ -978,20 +1142,24 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let ids = s.edit("Expand Appearance", |d, _| {
let before = d.clone();
let mut ended = super::dimension::end_links(d, &roots);
// A dimension selected with the art it measures keeps its own lines and label: it is out
// of the document while the art expands.
let lifted = super::dimension::lift(d, &roots);
let kept = !lifted.is_empty();
let ended = super::dimension::end_links(d, &roots);
let brushes = vectorcraft_brush::library(d);
let mut out = vec![];
let threaded = super::threads::frames(d);
for id in &roots {
expand_node(d, *id, &brushes, &mut out);
}
// A dimension whose source was replaced stays plain: its link no longer fits that art.
ended.retain(|e| e.source_kept(&before, d));
super::dimension::restore_unchanged(d, ended);
super::dimension::put_back(d, lifted);
// A dimension whose source was replaced stays where it was, no longer linked.
super::dimension::restore_unchanged(&before, d, ended);
// Outlined frames of threaded text leave their threads with the text they show; type that
// stays type under a new id takes its frame's place.
super::threads::leave_threads(d, &threaded);
if out.is_empty() {
if out.is_empty() || (kept && d.layers == before.layers) {
return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into()));
}
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?;
+36 -12
View File
@@ -5,7 +5,8 @@
//! gradient mesh, or solid strips / concentric ellipses, inside a clip group shaped like the object; a freeform
//! gradient becomes a mesh shaped like the object. A pattern fill becomes the tiles it paints inside a clip
//! group shaped like the object. Create Gradient Mesh shares the sampling. A dimension whose art
//! Expand changes becomes a plain group of that art.
//! Expand changes becomes a plain group of that art, except one selected with art it measures,
//! which Expand leaves as it is.
use std::collections::BTreeSet;
use std::sync::Arc;
@@ -43,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art → {ids}",
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
has_selection,
expand
),
@@ -55,7 +56,8 @@ pub fn specs() -> Vec<CommandSpec> {
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
has_selection,
|s, _| {
let e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
let roots = selected_roots(s)?;
let e = Expandable::of(&super::dimension::without_kept(&s.doc()?.doc, &roots), &roots);
let mut info =
json!({"object": e.object(), "fill": e.fill, "stroke": e.stroke, "gradient": e.gradient, "appearance": has_appearance(s)});
if e.symbols {
@@ -74,7 +76,9 @@ pub fn specs() -> Vec<CommandSpec> {
/// (#3089); `object.expand` itself still bakes them.
pub fn has_appearance(s: &Session) -> bool {
let (Ok(st), Ok(roots)) = (s.doc(), selected_roots(s)) else { return false };
roots.iter().filter_map(|r| st.doc.node(*r)).any(super::effectcmd::expandable)
// A dimension selected with the art it measures is left as it is.
let kept = super::dimension::with_their_art(&st.doc, &roots);
roots.iter().filter_map(|r| st.doc.node(*r)).any(|n| super::effectcmd::expandable_except(n, &kept))
}
/// Every placed document in `roots` of `d` (at any depth) replaced by an editable copy of the art it
@@ -241,9 +245,18 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
let stroke = switch_or(p, "stroke", true, C)?;
let to = GradientTo::parse(p)?;
let from = s.doc()?.history.undo.len();
let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
// Before anything expands: outlining the art a dimension measures would remove the dimension.
// Before anything expands: outlining the art a dimension measures would leave the dimension unlinked.
let before = s.doc()?.doc.clone();
let selected = s.doc()?.selection.objects.clone();
// A dimension selected with the art it measures keeps its own lines and label: it is out of the
// document while the art expands, so no step below reaches it.
let roots = selected_roots(s)?;
let mut lifted = vec![];
if !super::dimension::with_their_art(&before, &roots).is_empty() {
lifted = s.edit("Expand", |d, _| Ok(super::dimension::lift(d, &roots)))?;
}
let kept: Vec<NodeId> = lifted.iter().map(super::dimension::Lifted::id).collect();
let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
let mut ended = vec![];
end_dimension_links(s, &mut ended)?;
let rev0 = s.doc()?.revision;
@@ -339,14 +352,25 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
if s.doc()?.revision == rev0 {
return Err(EngineError::Other("Expand: nothing to expand".into()));
}
if !ended.is_empty() {
// A dimension whose source Expand replaced stays plain: its link no longer fits that art.
let after = s.doc()?.doc.clone();
ended.retain(|e| e.source_kept(&before, &after));
s.edit("Expand", |d, _| {
super::dimension::restore_unchanged(d, std::mem::take(&mut ended));
if !ended.is_empty() || !lifted.is_empty() {
s.edit("Expand", |d, sel| {
if !lifted.is_empty() {
super::dimension::put_back(d, lifted);
// The dimensions put back follow what Expand made of the art they measure: a
// dimension whose art no longer fits its link stays where it was, no longer linked.
super::dimension::refresh(&before, d)?;
let mut ids = sel.objects.clone();
let again: Vec<NodeId> = kept.iter().copied().filter(|id| selected.contains(id) && !ids.contains(id)).collect();
ids.extend(again);
sel.set(ids);
}
// A dimension whose source Expand replaced stays where it was, no longer linked.
super::dimension::restore_unchanged(&before, d, ended);
Ok(())
})?;
if !kept.is_empty() && s.doc()?.doc.layers == before.layers {
return Err(EngineError::Other("Expand: nothing to expand".into()));
}
}
squash(s, from, "Expand");
Ok(json!({ "ids": s.doc()?.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>() }))
@@ -88,6 +88,7 @@ impl Builder {
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
})
.collect();
if self.doc.artboards.is_empty() {
+1
View File
@@ -373,6 +373,7 @@ pub(crate) fn with_single_artboard(mut d: Document, rect: Rect, name: &str) -> D
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
}];
d
}
+3 -1
View File
@@ -270,7 +270,9 @@ fn flattened(src: &Document, at: usize, id: NodeId) -> Result<Option<Flat>> {
let pt = im.xf.determinant().abs().sqrt();
let ppi = if pt.is_finite() && pt > 0.0 { (72.0 / pt).clamp(MIN_PPI, MAX_PPI) } else { MIN_PPI };
let area = (bounds.width() * bounds.height()).max(1.0);
let scale = (ppi / 72.0).min((super::super::menucmds::MAX_PIXELS / area).sqrt());
// No side longer than the renderer draws (rounded up to whole pixels below).
let longest = (f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0) / bounds.width().max(bounds.height()).max(1.0);
let scale = (ppi / 72.0).min((super::super::menucmds::MAX_PIXELS / area).sqrt()).min(longest);
if !(scale.is_finite() && scale > 0.0) {
return Ok(None);
}
+23 -2
View File
@@ -43,6 +43,22 @@ impl Loaded {
}
self
}
/// The file in the units of Preferences › Units › General when it records none of its own: a
/// PDF, an EPS or `.ai` without ruler units, a raster image, a metafile, an Affinity file or
/// what an importer plug-in reads, as the reference app opens such files (#5820). A native
/// document (also one that an SVG, PDF, `.ai` or EPS file carries, `restored`), an SVG (the
/// units of its root's size, pixels when it gives none), a DXF drawing (the unit it was read
/// in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows
/// change, not its art.
pub(crate) fn with_unit_prefs(mut self, prefs: &Prefs) -> Self {
let records_units =
self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf");
if !records_units {
self.doc.units = crate::units::pref_unit(&prefs.units_general);
}
self
}
}
/// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG
@@ -490,7 +506,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// document keeps its text as saved), and every frame of a thread takes its first frame's
// 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.
// frames keep their size: Auto Size is off for them. The story is laid out in the document's
// own composite fonts.
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);
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() {
@@ -501,6 +520,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// paragraph's first-line indent and list marker.
crate::cmd::threads::mark_continued(&mut doc);
}
drop(lent);
if let Some(mode) = opts.color_mode.filter(|m| *m != doc.color_mode) {
super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, opts.grays);
}
@@ -610,7 +630,8 @@ pub fn open_template(s: &mut Session, name: &str, bytes: &[u8], path: Option<&st
/// Make a loaded file the new active document; `links` is what became of its linked files, and
/// `opts` are the options it was read with.
fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<String>, opts: &LoadOptions, as_template: bool) -> Result<Value> {
let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } = loaded.with_grid_prefs(&s.prefs);
let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } =
loaded.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
// EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing
// fallbacks must ask before overwriting the richer source they could not fully read.
let losses: Vec<String> = warnings
+18 -7
View File
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and search Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: fa Line truncated
has_doc,
export_pdf
),
@@ -360,9 +360,9 @@ fn encode_carrying_at(
if set.pdf13() {
vectorcraft_doc::cancel::progress(0, 0, "Flattening transparency");
}
let flat = flatten_for(cmd, doc, set, p)?;
let (flat, flattened) = flatten_for(cmd, doc, set, p)?;
vectorcraft_doc::cancel::check()?;
if flat.is_some() {
if flattened {
let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() };
warnings.push(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset"));
}
@@ -379,11 +379,19 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution";
/// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener`
/// options over it; images with see-through pixels and colorized images, including those in
/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and
/// discarded overprints are dropped. `None` when nothing changes (or the file keeps transparency).
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<Option<Document>> {
/// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked
/// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is)
/// and whether its transparency was flattened.
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, bool)> {
if !set.pdf13() {
return Ok(None);
return Ok((None, false));
}
let printed = if set.include_non_printing || set.create_layers { None } else { without_non_printing(&doc.layers) };
let shown = printed.map(|layers| {
let mut d = doc.clone();
d.layers = layers;
d
});
let name = Some(set.flattener_preset.trim()).filter(|n| !n.is_empty()).unwrap_or(DEFAULT_FLATTENER);
let mut o = FlattenOptions::for_export(Some(name), p.get("flattener"), &[]).map_err(|e| bad(cmd, format!("PDF flattener: {e}")))?;
o.preserve_overprints &= set.advanced.overprint == Overprint::Preserve;
@@ -391,7 +399,10 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul
// Without soft masks a rasterized area can't be a rectangle with see-through pixels around
// its art: it is clipped to its regions (opaque inside them).
o.clip_complex_regions = true;
flatten_document(doc, &o)
Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? {
Some(flat) => (Some(flat), true),
None => (shown, false),
})
}
/// The pages `opts` export of `doc` drawn on white, [`THUMBNAIL_SIZE`] pixels on their long side:
+1 -1
View File
@@ -1051,7 +1051,7 @@ fn can_revert(s: &Session) -> std::result::Result<(), String> {
fn revert(s: &mut Session, _: &Value) -> Result<Value> {
let index = s.active_index().ok_or(crate::EngineError::NoDocument)?;
let path = s.doc()?.path.clone().ok_or_else(|| bad("file.revert", "the document has never been saved"))?;
let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs);
let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
doc.template = false;
// Back to the saved file: its recovery copy has nothing left to recover.
let uid = s.doc()?.uid;
+22
View File
@@ -170,6 +170,28 @@ fn transparency_is_flattened_with_the_flattener_preset() {
assert!(e.contains("preset"), "{e}");
}
/// A picture cropped by a clipping path, in a clip group at 80%, over a square that only the
/// hidden part of the picture covers: the file prints the square, and its image is as large as
/// the crop, with the default preset (a rectangle of image) and with High Resolution (an image
/// clipped to its regions).
#[test]
fn flattening_cropped_art_keeps_the_art_under_its_hidden_part() {
use super::tests_pdfx::{Art, CROP, cropped, drawn, lost, shown_image_sizes};
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
for preset in ["medium", "high"] {
let (mut s, _) = cropped("rgb", 400.0, Art::Image { see_through: false });
s.execute("transparency.set", &json!({"opacity": 80})).unwrap();
let canvas = drawn(&s.doc().unwrap().doc);
let opts = json!({"artboards": [0], "flattenerPreset": preset, "previewFormat": "none", "thumbnails": false});
let r = s.execute("document.exportEps", &opts).unwrap();
// What the file prints, not the document it carries.
let back = vectorcraft_eps::import_with(&b64(&r), false).unwrap().document;
assert_eq!(lost(&canvas, &drawn(&back)), 0, "{preset}: art went missing");
let sizes = shown_image_sizes(&back);
assert!(!sizes.is_empty() && sizes.iter().all(|(w, h)| *w <= CROP[2] + 1.0 && *h <= CROP[3] + 1.0), "{preset}: the images show {sizes:?}");
}
}
#[test]
fn overprints_are_kept_or_discarded() {
let mut s = session(100.0, 100.0, 1);
+513
View File
@@ -186,3 +186,516 @@ fn pdfx_1a_flattening_keeps_the_inks_behind_an_image_in_a_cmyk_document() {
let ink = image_inks_at(&back, vectorcraft_geom::Point::new(88.0, 50.0)).expect("a CMYK image behind the see-through pixels");
assert!(ink.iter().zip(teal).all(|(a, b)| (a - b).abs() <= 1.5 / 255.0), "{ink:?} is not {teal:?}");
}
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}
/// The art a clip group crops in [`cropped`].
#[derive(Clone, Copy)]
pub(super) enum Art {
/// A 240 × 160 image, with see-through pixels or without.
Image { see_through: bool },
/// A rectangle with a gradient fill.
Gradient,
/// A rectangle with a drop shadow.
Shadow,
}
/// Where [`cropped`] puts the cropped art, [x, y, width, height].
const FRAME: [f64; 4] = [40.0, 40.0, 240.0, 160.0];
/// The part of [`FRAME`] the clipping path of [`cropped`] shows.
pub(super) const CROP: [f64; 4] = [50.0, 50.0, 80.0, 60.0];
/// A `mode` document whose first artboard is `width` wide, with a dark square and, over it, `art`
/// filling [`FRAME`] in a clip group that shows [`CROP`] of it. The square lies inside the frame
/// and outside the crop: only the hidden part of the art covers it. → the session with the clip
/// group selected, and the group's id.
pub(super) fn cropped(mode: &str, width: f64, art: Art) -> (Session, u64) {
cropped_by(mode, width, art, false)
}
/// [`cropped`], with the art and its clipping path in a clipping layer above the square's layer
/// when `layer`. → the session and the clip group's or the layer's id.
fn cropped_by(mode: &str, width: f64, art: Art, layer: bool) -> (Session, u64) {
let [x, y, w, h] = FRAME;
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": width, "height": 300, "colorMode": mode}));
run(&mut s, "shape.rectangle", json!({"x": 180, "y": 90, "width": 60, "height": 60}));
run(&mut s, "paint.setFill", json!({"color": "#203040"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
let layer = layer.then(|| run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap());
let art = match art {
Art::Image { see_through } => {
let mut png = vec![];
image::RgbaImage::from_fn(240, 160, |x, y| {
image::Rgba([200, (x % 256) as u8, (y % 256) as u8, if see_through && x < 60 { 128 } else { 255 }])
})
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let placed =
run(&mut s, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME}));
placed["ids"][0].clone()
}
Art::Gradient | Art::Shadow => {
let id = run(&mut s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].clone();
run(&mut s, "paint.setStroke", json!({"none": true}));
if matches!(art, Art::Gradient) {
let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]);
run(&mut s, "paint.setFill", json!({"gradient": {"kind": "linear", "stops": stops}}));
} else {
run(&mut s, "paint.setFill", json!({"color": "#c04020"}));
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [id]}));
}
id
}
};
let [x, y, w, h] = CROP;
let clip = run(&mut s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].clone();
if let Some(layer) = layer {
run(&mut s, "layer.clippingMask.toggle", json!({"id": layer}));
run(&mut s, "select.set", json!({"ids": [art]}));
return (s, layer);
}
run(&mut s, "select.set", json!({"ids": [art, clip]}));
let group = run(&mut s, "object.clippingMask.make", json!({}))["id"].as_u64().unwrap();
(s, group)
}
/// `document.exportPdf` with `p`, read back.
fn read_back(s: &mut Session, p: &Value) -> vectorcraft_doc::Document {
let v = run(s, "document.exportPdf", p.clone());
vectorcraft_pdf::import(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap()
}
/// `doc`'s artboards drawn on white at 72 ppi.
pub(super) fn drawn(doc: &vectorcraft_doc::Document) -> vectorcraft_render::Rendered {
let pages = doc.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)).unwrap();
vectorcraft_render::Renderer::new().render_region(doc, pages, 1.0, true)
}
/// How many pixels show art in `reference` and are blank in `variant`.
pub(super) fn lost(reference: &vectorcraft_render::Rendered, variant: &vectorcraft_render::Rendered) -> usize {
assert_eq!((reference.width, reference.height), (variant.width, variant.height));
let (reference, variant) = (reference.pixels.as_chunks::<4>().0, variant.pixels.as_chunks::<4>().0);
reference.iter().zip(variant).filter(|(r, v)| r[..3].iter().any(|c| *c < 200) && v[..3].iter().all(|c| *c >= 250)).count()
}
/// How many pixels of `a` and `b` differ by more than 24 in a channel.
fn differ(a: &vectorcraft_render::Rendered, b: &vectorcraft_render::Rendered) -> usize {
assert_eq!((a.width, a.height), (b.width, b.height));
let (a, b) = (a.pixels.as_chunks::<4>().0, b.pixels.as_chunks::<4>().0);
a.iter().zip(b).filter(|(p, q)| p[..3].iter().zip(&q[..3]).any(|(x, y)| x.abs_diff(*y) > 24)).count()
}
/// The width and height of what each of `doc`'s images shows: its frame inside the clipping
/// paths around it.
pub(super) fn shown_image_sizes(doc: &vectorcraft_doc::Document) -> Vec<(f64, f64)> {
use vectorcraft_geom::Rect;
fn visit(n: &vectorcraft_doc::Node, clip: Option<Rect>, out: &mut Vec<(f64, f64)>) {
let within = |r: Rect| clip.map_or(r, |c| c.intersect(r));
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
let frame = im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, im.width as f64, im.height as f64));
let shown = within(frame);
out.push((shown.width(), shown.height()));
}
let clip = if n.clips() { n.visual_bounds().map(within) } else { clip };
for c in n.children().into_iter().flatten() {
visit(c, clip, out);
}
}
let mut out = vec![];
for l in &doc.layers {
visit(l, None, &mut out);
}
out
}
/// Checks that the PDF/X-1a, PDF/X-3 and PDF 1.3 files of `s` (with `extra` options) show all the
/// art the file with transparency shows, and that no image in them shows more than [`CROP`]. Adds
/// what is wrong to `wrong`.
fn check_flat_files(s: &mut Session, extra: &Value, what: &str, wrong: &mut Vec<String>) {
let reference = drawn(&read_back(s, extra));
for flat in [json!({"standard": "pdfX1a"}), json!({"standard": "pdfX3"}), json!({"compatibility": "1.3", "preserveEditing": false})] {
let mut p = flat.clone();
super::pdf::merge(&mut p, extra);
let back = read_back(s, &p);
let lost = lost(&reference, &drawn(&back));
if lost > 0 {
wrong.push(format!("{what}, {flat}: {lost} pixels of art went missing"));
}
let sizes = shown_image_sizes(&back);
// An image reaches a pixel past its regions, and a group rasterized whole a point past
// its visible bounds.
if sizes.is_empty() || sizes.iter().any(|(w, h)| *w > CROP[2] + 3.0 || *h > CROP[3] + 3.0) {
wrong.push(format!("{what}, {flat}: the images show {sizes:?}"));
}
}
}
/// Art cropped by a clipping path, in a PDF file without transparency: the part of the art the
/// clipping path hides is not rasterized, so art that lies under the hidden part alone still
/// shows. Each case is one way the cropped art comes to be flattened.
#[test]
fn flattening_cropped_art_for_pdfx_keeps_the_art_under_its_hidden_part() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let opaque = Art::Image { see_through: false };
type Change = fn(&mut Session, u64);
let cases: [(&str, Art, Change); 9] = [
("an image with see-through pixels", Art::Image { see_through: true }, |_, _| {}),
("a clip group with opacity", opaque, |s, _| {
run(s, "transparency.set", json!({"opacity": 80}));
}),
("a clip group with a blend mode", opaque, |s, _| {
run(s, "transparency.set", json!({"blendMode": "multiply"}));
}),
("a see-through object over the crop", opaque, |s, _| {
run(s, "shape.rectangle", json!({"x": 60, "y": 60, "width": 40, "height": 30}));
run(s, "paint.setFill", json!({"color": "#ffffff"}));
run(s, "transparency.set", json!({"opacity": 60}));
}),
("a gradient", Art::Gradient, |s, _| {
run(s, "transparency.set", json!({"opacity": 80}));
}),
("a raster effect", Art::Shadow, |_, _| {}),
("a clip group inside a clip group", Art::Image { see_through: true }, |s, group| {
let outer = run(s, "shape.rectangle", json!({"x": 45, "y": 45, "width": 85, "height": 65}))["id"].clone();
run(s, "select.set", json!({"ids": [group, outer]}));
run(s, "object.clippingMask.make", json!({}));
}),
("a clip group inside a group with opacity", opaque, |s, _| {
run(s, "object.group", json!({}));
run(s, "transparency.set", json!({"opacity": 80}));
}),
("an even-odd compound clipping path", opaque, |s, group| {
run(s, "transparency.set", json!({"opacity": 80}));
let doc = s.doc_mut().unwrap();
let mut d = (*doc.doc).clone();
let clip = d.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap()[0].id;
let mut ring = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(50.0, 50.0, 130.0, 110.0));
ring.subpaths.extend(vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(70.0, 65.0, 110.0, 95.0)).subpaths);
if let vectorcraft_doc::NodeKind::Path { path, rule, .. } = &mut d.node_mut(clip).unwrap().kind {
(*path, *rule) = (ring, vectorcraft_geom::FillRule::EvenOdd);
}
doc.doc = d.into();
}),
];
let mut wrong = vec![];
for mode in ["cmyk", "rgb"] {
for (what, art, change) in cases {
let (mut s, group) = cropped(mode, 400.0, art);
change(&mut s, group);
check_flat_files(&mut s, &json!({}), &format!("{mode}: {what}"), &mut wrong);
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// The same with the Medium and Low Resolution presets, and with a balance of 0, which rasterizes
/// the whole group of the cropped art over the group's visible bounds.
#[test]
fn flattening_cropped_art_for_pdfx_keeps_the_art_under_its_hidden_part_with_each_preset() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut wrong = vec![];
for extra in [json!({"flattenerPreset": "medium"}), json!({"flattenerPreset": "low"}), json!({"flattener": {"balance": 0}})] {
for (art, name) in [(Art::Image { see_through: true }, "image"), (Art::Gradient, "gradient")] {
let (mut s, _) = cropped("cmyk", 400.0, art);
run(&mut s, "transparency.set", json!({"opacity": 80}));
check_flat_files(&mut s, &extra, &format!("{name}, {extra}"), &mut wrong);
}
}
// A cropped rectangle with a solid fill, rasterized whole.
let (mut s, group) = cropped("cmyk", 400.0, Art::Gradient);
let art = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap()[1].id.0;
run(&mut s, "paint.setFill", json!({"ids": [art], "color": "#c04020"}));
run(&mut s, "transparency.set", json!({"ids": [group], "opacity": 80}));
check_flat_files(&mut s, &json!({"flattener": {"balance": 0}}), "solid fill, balance 0", &mut wrong);
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// The hidden part of cropped art on one artboard lies over the next artboard: that page keeps
/// its art.
#[test]
fn flattening_cropped_art_for_pdfx_keeps_the_next_page_under_its_hidden_part() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
// The crop is on the first artboard, and the square on the second.
let (mut s, _) = cropped("cmyk", 150.0, Art::Image { see_through: true });
run(&mut s, "artboard.new", json!({"x": 170, "y": 0, "width": 230, "height": 300}));
assert_eq!(read_back(&mut s, &json!({"standard": "pdfX1a"})).artboards.len(), 2);
let mut wrong = vec![];
check_flat_files(&mut s, &json!({}), "two artboards", &mut wrong);
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// Art cropped by a clipping layer, over a square in the layer below: the square keeps showing,
/// also with a second square in that layer under both the crop and the hidden part, or with a
/// see-through rectangle over both in a layer above.
#[test]
fn flattening_art_of_a_clipping_layer_for_pdfx_keeps_the_art_under_its_hidden_part() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
type Change = fn(&mut Session, u64);
let cases: [(&str, Change); 3] = [
("alone", |_, _| {}),
("over a square under the crop's edge", |s, _| {
let below = s.doc().unwrap().doc.layers[0].id.0;
run(s, "layer.setCurrent", json!({"id": below}));
run(s, "shape.rectangle", json!({"x": 110, "y": 60, "width": 50, "height": 30}));
run(s, "paint.setFill", json!({"color": "#406020"}));
}),
("under a see-through rectangle over the crop's edge", |s, _| {
run(s, "layer.new", json!({}));
run(s, "shape.rectangle", json!({"x": 110, "y": 60, "width": 50, "height": 30}));
run(s, "paint.setFill", json!({"color": "#406020"}));
run(s, "transparency.set", json!({"opacity": 60}));
}),
];
let mut wrong = vec![];
for mode in ["cmyk", "rgb"] {
for art in [Art::Image { see_through: true }, Art::Gradient] {
for (what, change) in cases {
let (mut s, layer) = cropped_by(mode, 400.0, art, true);
run(&mut s, "transparency.set", json!({"opacity": 80}));
change(&mut s, layer);
check_flat_files(&mut s, &json!({}), &format!("{mode}: a clipping layer {what}"), &mut wrong);
}
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// Documents in which no clip group hides art export the same bytes as they did when the
/// flattener rasterized hidden art too.
#[test]
fn flat_pdf_files_of_art_that_no_clip_group_hides_are_unchanged() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
use crate::cmd::flatten::with_clips_ignored as before;
// Written at one time, so two files differ only by what they draw.
let bytes = |s: &mut Session, p: &Value| super::pdf::encode_at("document.exportPdf", &s.doc().unwrap().doc, p, Some(1_700_000_000)).unwrap().0;
let files = [
json!({"standard": "pdfX1a"}),
json!({"standard": "pdfX3"}),
json!({"compatibility": "1.3", "preserveEditing": false}),
json!({"standard": "pdfX1a", "flattener": {"balance": 0}}),
json!({"standard": "pdfX1a", "flattenerPreset": "low"}),
];
// Transparency without a clip group.
let mut plain = session();
// A clip group at 80% whose clipping path is as large as its art, over the edge of a square.
let mut fitted = Session::new();
run(&mut fitted, "file.new", json!({"width": 400, "height": 300, "colorMode": "cmyk"}));
run(&mut fitted, "shape.rectangle", json!({"x": 180, "y": 90, "width": 160, "height": 160}));
run(&mut fitted, "paint.setFill", json!({"color": "#203040"}));
let mut png = vec![];
image::RgbaImage::from_fn(240, 160, |x, y| image::Rgba([200, x as u8, y as u8, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let photo =
run(&mut fitted, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME}))["ids"][0]
.clone();
let [x, y, w, h] = FRAME;
let clip = run(&mut fitted, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].clone();
run(&mut fitted, "select.set", json!({"ids": [photo, clip]}));
run(&mut fitted, "object.clippingMask.make", json!({}));
run(&mut fitted, "transparency.set", json!({"opacity": 80}));
// Cropped art that is not flattened: nothing on it is see-through.
let (mut opaque, _) = cropped("cmyk", 400.0, Art::Image { see_through: false });
for (what, s) in [("no clip group", &mut plain), ("a clipping path as large as its art", &mut fitted), ("opaque cropped art", &mut opaque)] {
for p in &files {
assert!(bytes(s, p) == before(|| bytes(s, p)), "{what}, {p}");
}
}
// Art that a clip group hides is what changes.
let (mut s, _) = cropped("cmyk", 400.0, Art::Image { see_through: true });
assert!(bytes(&mut s, &files[0]) != before(|| bytes(&mut s, &files[0])));
}
/// The options of the PDF files without transparency.
const FLAT_FILES: [&str; 3] = [r#"{"standard": "pdfX1a"}"#, r#"{"standard": "pdfX3"}"#, r#"{"compatibility": "1.3", "preserveEditing": false}"#];
/// [`cropped_by`]'s clipping layer of a gradient at 80%, with a rectangle in the layer below that
/// crosses the crop's right edge. → the session and the clipping layer's id.
fn clipping_layer_over_a_rectangle(mode: &str) -> (Session, u64) {
let (mut s, layer) = cropped_by(mode, 400.0, Art::Gradient, true);
run(&mut s, "transparency.set", json!({"opacity": 80}));
let below = s.doc().unwrap().doc.layers[0].id.0;
run(&mut s, "layer.setCurrent", json!({"id": below}));
run(&mut s, "shape.rectangle", json!({"x": 100, "y": 60, "width": 120, "height": 40}));
run(&mut s, "paint.setFill", json!({"color": "#406020"}));
(s, layer)
}
/// A clipping layer over a layer that doesn't print, and a clipping layer that doesn't print
/// over one that does: the files without transparency print what the file with transparency
/// prints, and nothing of the layer that doesn't print.
#[test]
fn flattening_for_pdfx_leaves_out_the_layers_that_do_not_print() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut wrong = vec![];
for mode in ["cmyk", "rgb"] {
for clipping_layer_prints in [true, false] {
let (mut s, layer) = clipping_layer_over_a_rectangle(mode);
let below = s.doc().unwrap().doc.layers[0].id.0;
let off = if clipping_layer_prints { below } else { layer };
run(&mut s, "layer.setProps", json!({"id": off, "printable": false}));
let reference = drawn(&read_back(&mut s, &json!({})));
for flat in FLAT_FILES {
let back = drawn(&read_back(&mut s, &serde_json::from_str(flat).unwrap()));
let (lost, gained) = (lost(&reference, &back), lost(&back, &reference));
if lost + gained > 0 {
wrong.push(format!("{mode}, clipping layer prints: {clipping_layer_prints}, {flat}: {lost} pixels lost, {gained} gained"));
}
}
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// A clipping layer whose clipping path has a fill: the files without transparency show the art
/// over the fill, not the fill over the art.
#[test]
fn flattening_for_pdfx_keeps_the_art_of_a_clipping_layer_over_its_clipping_path_fill() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut wrong = vec![];
for mode in ["cmyk", "rgb"] {
let (mut s, layer) = clipping_layer_over_a_rectangle(mode);
let clip = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(layer)).unwrap().children().unwrap()[0].id.0;
run(&mut s, "paint.setFill", json!({"ids": [clip], "color": "#ffdd00"}));
let reference = drawn(&read_back(&mut s, &json!({})));
for flat in FLAT_FILES {
let back = drawn(&read_back(&mut s, &serde_json::from_str(flat).unwrap()));
// PDF/X-1a converts an RGB document's colors to CMYK.
let converted = mode == "rgb" && flat.contains("pdfX1a");
let (lost, differ) = (lost(&reference, &back), if converted { 0 } else { differ(&reference, &back) });
if lost > 0 || differ > 100 {
wrong.push(format!("{mode}, {flat}: {lost} pixels of art lost, {differ} pixels differ"));
}
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// Transparent art in a clipping layer whose clipping path is area type holding only a space,
/// which hides it: the files without transparency are written, without the art.
#[test]
fn flattening_for_pdfx_removes_transparent_art_that_a_clipping_layer_hides_entirely() {
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let [x, y, w, h] = FRAME;
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 400, "height": 300, "colorMode": "cmyk"}));
let layer = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
run(&mut s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}));
let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]);
run(&mut s, "paint.setFill", json!({"gradient": {"kind": "linear", "stops": stops}}));
run(&mut s, "transparency.set", json!({"opacity": 80}));
run(&mut s, "text.create", json!({"x": 50, "y": 50, "text": " ", "area": {"width": 80, "height": 60}}));
run(&mut s, "layer.clippingMask.toggle", json!({"id": layer}));
let reference = drawn(&read_back(&mut s, &json!({})));
for flat in FLAT_FILES {
let p: Value = serde_json::from_str(flat).unwrap();
let back = match s.execute("document.exportPdf", &p) {
Ok(v) => vectorcraft_pdf::import(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap(),
Err(e) => panic!("{flat}: {e}"),
};
assert_eq!(lost(&drawn(&back), &reference), 0, "{flat}: the hidden art prints");
}
}
/// Object › Flatten Transparency of art in a clipping layer and art in the layer below that
/// reaches past the clipping path: when the layer below doesn't print, the clipping layer has
/// opacity, or the clipping path has a fill (see-through too, flattened keeping alpha, in a layer
/// with opacity or Multiply mode, or
/// over a layer with opacity, overlapping art of a layer with opacity or art an opacity mask
/// hides), the group stays in the clipping layer, the art below stays in its layer, and the page
/// looks the same.
#[test]
fn flattening_keeps_the_group_in_the_clipping_layer_when_the_layer_below_differs() {
let mut wrong = vec![];
let cases = [
"the layer below doesn't print",
"the clipping path has a fill",
"the clipping path has a see-through fill, keeping alpha",
"the clipping path has a see-through fill, in a layer with opacity",
"the clipping path has a see-through fill, in a layer in Multiply mode",
"the clipping path has a see-through fill, over a layer with opacity",
"the clipping path has a see-through fill, over art that an opacity mask hides",
"the clipping path has a see-through fill, over overlapping art of a layer at 50%",
"the clipping path has no fill, in a layer with opacity",
];
for case in cases {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 400, "height": 300, "colorMode": "rgb"}));
let below = s.doc().unwrap().doc.layers[0].id.0;
let orange = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 200, "height": 150}))["id"].clone();
run(&mut s, "paint.setFill", json!({"color": "#ff8000"}));
let upper = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
let blue = run(&mut s, "shape.rectangle", json!({"x": 100, "y": 80, "width": 200, "height": 150}))["id"].clone();
run(&mut s, "paint.setFill", json!({"color": "#2040c0"}));
run(&mut s, "transparency.set", json!({"opacity": 50}));
let clip = run(&mut s, "shape.rectangle", json!({"x": 60, "y": 40, "width": 300, "height": 220}))["id"].clone();
run(&mut s, "layer.clippingMask.toggle", json!({"id": upper}));
if case.starts_with("the layer below") {
run(&mut s, "layer.setProps", json!({"id": below, "printable": false}));
} else if !case.contains("no fill") {
run(&mut s, "paint.setFill", json!({"ids": [clip], "color": "#88ffcc"}));
}
let keeping_alpha = case.ends_with("keeping alpha");
if case.contains("see-through fill") {
run(&mut s, "transparency.set", json!({"ids": [clip], "opacity": 50}));
}
if case.ends_with("in a layer with opacity") {
run(&mut s, "transparency.set", json!({"ids": [upper], "opacity": 80}));
}
if case.ends_with("over a layer with opacity") {
run(&mut s, "transparency.set", json!({"ids": [below], "opacity": 50}));
}
if case.ends_with("an opacity mask hides") {
run(&mut s, "layer.setCurrent", json!({"id": below}));
run(&mut s, "select.set", json!({"ids": [orange]}));
let group = run(&mut s, "object.group", json!({}))["id"].clone();
let mask = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 200, "height": 150}))["id"].clone();
run(&mut s, "paint.setFill", json!({"color": "#000000"}));
run(&mut s, "select.set", json!({"ids": [group, mask]}));
run(&mut s, "transparency.makeOpacityMask", json!({}));
}
if case.ends_with("Multiply mode") {
run(&mut s, "transparency.set", json!({"ids": [upper], "blendMode": "multiply"}));
}
let mut art = vec![orange.clone()];
if case.ends_with("a layer at 50%") {
run(&mut s, "layer.setCurrent", json!({"id": below}));
art.push(run(&mut s, "shape.rectangle", json!({"x": 80, "y": 60, "width": 120, "height": 120}))["id"].clone());
run(&mut s, "paint.setFill", json!({"color": "#20a040"}));
run(&mut s, "transparency.set", json!({"ids": [below], "opacity": 50}));
}
art.push(blue.clone());
// The page as it prints.
let printed = |d: &vectorcraft_doc::Document| {
let mut d = d.clone();
if case.starts_with("the layer below") {
let mut layer = (*d.layers[0]).clone();
layer.visible = false;
d.layers[0] = layer.into();
}
drawn(&d)
};
let before = printed(&s.doc().unwrap().doc);
run(&mut s, "select.set", json!({"ids": art}));
run(&mut s, "object.flattenTransparency", json!({"preserveAlpha": keeping_alpha}));
let d = &s.doc().unwrap().doc;
let layer_of = |id: &Value| id.as_u64().and_then(|id| d.ancestry(vectorcraft_doc::NodeId(id))).map(|a| a[0].0);
if layer_of(&orange) != Some(below) {
wrong.push(format!("{case}: the art below is in layer {:?}", layer_of(&orange)));
}
let upper_art = d.node(vectorcraft_doc::NodeId(upper)).and_then(|l| l.children()).map_or(0, Vec::len);
if d.node(vectorcraft_doc::NodeId(blue.as_u64().unwrap())).is_some() || upper_art != 2 {
wrong.push(format!("{case}: the clipping layer holds {upper_art} objects"));
}
let after = printed(d);
// Flat regions differ from see-through art along their antialiased edges.
let (lost, differ) = (lost(&before, &after), differ(&before, &after));
if lost > 0 || differ > 1200 {
wrong.push(format!("{case}: {lost} pixels of art lost, {differ} pixels differ"));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
+2 -2
View File
@@ -49,9 +49,9 @@ mod presets;
mod report;
pub(crate) use analysis::{outlined_text, see_through_images};
#[cfg(test)]
pub(crate) use apply::with_every_region;
pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images};
#[cfg(test)]
pub(crate) use apply::{with_clips_ignored, with_every_region};
pub use commands::specs;
pub use options::FlattenOptions;
pub use presets::{FlattenerPreset, PRESET_EXTS, PRESET_FORMAT};
+264 -11
View File
@@ -1,4 +1,4 @@
use super::analysis::{Scratch, outlined_text, overlapping, reach};
use super::analysis::{Scratch, has_effects, masked, outlined_text, overlapping, reach};
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
use super::options::FlattenOptions;
use super::{
@@ -107,27 +107,83 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
let art: Vec<Node> = baked.layers[0].children().into_iter().flatten().map(|a| (**a).clone()).collect();
let mut sc = Scratch { brushes: vectorcraft_brush::library(&baked), doc: baked.clone() };
let plain: Vec<Node> = art.iter().map(|n| sc.plain(n)).collect();
let reaches: Vec<Option<Rect>> = plain.iter().map(reach).collect();
// Each object as its clip groups and clipping layers show it.
let clipped: Vec<Node> = plain.iter().zip(roots).map(|(n, id)| clipped_by_ancestors(src, *id, n, None)).collect();
let reaches: Vec<Option<Rect>> = plain.iter().zip(&clipped).map(|(n, c)| reach(n).zip(reach(c)).map(|(a, b)| a.intersect(b))).collect();
let see_through: Vec<bool> = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect();
let cmyk = src.color_mode == ColorMode::Cmyk;
let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() };
// Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing).
vectorcraft_doc::cancel::check()?;
for g in overlapping(&reaches)? {
let mut queue = overlapping(&reaches)?;
queue.reverse();
while let Some(g) = queue.pop() {
vectorcraft_doc::cancel::check()?;
// A group that stays inside the clip groups and clipping layers of its topmost object
// replaces only the objects inside them, over the others, which are flattened on their own.
let (g, under) = match inside_and_under(src, roots, &g) {
Some((inside, under)) => {
queue.push(under.clone());
(inside, under)
}
None => (g, vec![]),
};
// Composited over white, the group covers what it is drawn over, so it is composited over
// the fills of the clipping paths around it and the objects under it in the same kind of
// layer. Composited over nothing, it keeps its alpha and they show through.
let backdrop = !o.preserve_alpha;
let state = g.last().map(|&i| layer_state(src, roots[i]));
let top = g.last().map(|&i| roots[i]);
// A blend mode of a layer or group around the group alone would blend the art under it
// twice.
let blends = |i: usize| top.is_some_and(|t| own_layers(src, t, Some(roots[i])).iter().any(|a| a.blend != BlendMode::Normal));
// Art under an opacity mask, effects or a knockout group is left out: the group can't draw it
// as those do.
let drawn_plainly = |i: usize| {
own_layers(src, roots[i], top).iter().all(|a| !masked(a) && !has_effects(a) && !matches!(a.knockout, vectorcraft_doc::Knockout::On))
};
let under_shown = under.iter().copied().filter(|&i| backdrop && Some(layer_state(src, roots[i])) == state && !blends(i) && drawn_plainly(i));
let composited: Vec<usize> = under_shown.chain(g.iter().copied()).collect();
let below = composited.len() - g.len();
let extent = composited.iter().filter_map(|&i| reaches[i]).reduce(|a, b| a.union(b)).unwrap_or_default();
let shown = |nodes: &[Node]| -> Vec<Node> {
let mut seen = vec![];
let (mut under, mut out) = (vec![], vec![]);
for (k, &i) in composited.iter().enumerate() {
let n = clipped_by_ancestors(src, roots[i], &nodes[i], backdrop.then_some((&mut seen, extent)));
if k < below {
let groups = own_layers(src, roots[i], top).into_iter().filter(|a| !draws_as_is(a)).collect();
under.push((groups, n));
} else {
out.push(n);
}
}
let mut all = in_groups(under, 0);
all.extend(out);
all
};
let ids: Vec<NodeId> = g.iter().map(|&i| roots[i]).collect();
let group = g.iter().any(|&i| see_through[i]).then(|| {
let plain: Vec<&Node> = g.iter().map(|&i| &plain[i]).collect();
flatten_group(&plain, o, cmyk)
let plain = shown(&plain);
flatten_group(&plain.iter().collect::<Vec<_>>(), o, cmyk)
});
let Some((regions, area)) = group.flatten() else {
out.kept.extend(ids);
// Transparent art that its clip groups or clipping layers hide entirely draws nothing:
// it is removed.
let hides = |i: usize| see_through[i] && reach(&plain[i]).is_some() && reach(&clipped[i]).is_none();
let (hidden, left): (Vec<usize>, Vec<usize>) = g.iter().partition(|&&i| hides(i));
if !hidden.is_empty() {
let roots = hidden.iter().map(|&i| roots[i]).collect();
out.flat.push(Flat { roots, regions: vec![], area: None, raster: None, lines: None });
}
out.kept.extend(left.iter().map(|&i| roots[i]));
continue;
};
let raster = match area.as_ref().filter(|_| render) {
Some(a) => {
let art: Vec<Node> = g.iter().map(|&i| art[i].clone()).collect();
Some(render_raster(&baked, &art, a.rect, a.ppi, a.clip.clone(), o)?)
// Drawn as planned: the image can land outside the clip groups and clipping layers
// around its art.
Some(render_raster(&baked, &shown(&art), a.rect, a.ppi, a.clip.clone(), o)?)
}
None => None,
};
@@ -140,6 +196,134 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
Ok(out)
}
/// `plain` (object `id` of `src` as plain art) inside a clip group for each clip group and
/// clipping layer around `id`, innermost first, each clipped by that group's or layer's clipping
/// path. `plain` itself when nothing around it clips. With `fills` (clipping paths, and an area),
/// the fill of each clipping path not in them yet goes behind the art, inside the area, and the
/// path is added to them.
fn clipped_by_ancestors(src: &Document, id: NodeId, plain: &Node, mut fills: Option<(&mut Vec<NodeId>, Rect)>) -> Node {
let mut out = plain.clone();
if !clips_count() {
return out;
}
let ancestry = src.ancestry(id).unwrap_or_default();
for pair in ancestry.windows(2).rev() {
let Some(above) = src.node(pair[0]).filter(|n| n.clips()) else { continue };
let Some(clip) = above.children().and_then(|c| c.first()) else { continue };
// The clipping path itself is not clipped art.
if clip.id == pair[1] {
continue;
}
// Its outline, unpainted: the group or layer around the object still paints the path.
// Nothing to clip by hides the clipped art, as in the compositor.
let Some((outline, rule)) = effects::clip_outline(clip) else {
out.visible = false;
return out;
};
let mut path = Node::path(clip.id, PathData::from_bezpath(&outline), Appearance::default());
if let NodeKind::Path { rule: r, .. } = &mut path.kind {
*r = rule;
}
let mut children = vec![Arc::new(path)];
// The renderer paints the fill behind the clipped art.
if let Some((seen, r)) = fills.as_mut()
&& !seen.contains(&clip.id)
&& let Some(fill) = clip.clip_paint().fill
{
let r = *r;
seen.push(clip.id);
let mut at = Node::group(above.id, vec![Arc::new(Node::path(clip.id, shapes::rectangle(r), Appearance::default())), Arc::new(fill)]);
at.set_clips(true);
children.push(Arc::new(at));
}
children.push(Arc::new(out));
let mut g = Node::group(above.id, children);
g.set_clips(true);
out = g;
}
out
}
/// Whether layer or group `n` draws what it holds as it is: opaque, in Normal mode, not isolated.
fn draws_as_is(n: &Node) -> bool {
n.opacity >= 1.0 && n.blend == BlendMode::Normal && !n.isolate
}
/// `items` (in paint order, each an object and the layers and groups around it, outermost first,
/// that don't draw it as it is) with the objects of each such layer or group in one group with its
/// opacity, blend mode and isolation, from the `depth`th around them on: they then composite
/// together as that layer or group draws them.
fn in_groups(items: Vec<(Vec<&Node>, Node)>, depth: usize) -> Vec<Node> {
let mut out = vec![];
let mut items = items.into_iter().peekable();
while let Some((around, n)) = items.next() {
let Some(a) = around.get(depth).copied() else {
out.push(n);
continue;
};
let mut run = vec![(around, n)];
while let Some(next) = items.next_if(|(around, _)| around.get(depth).is_some_and(|b| b.id == a.id)) {
run.push(next);
}
let mut g = Node::group(a.id, in_groups(run, depth + 1).into_iter().map(Arc::new).collect());
(g.opacity, g.blend, g.isolate) = (a.opacity, a.blend, a.isolate);
out.push(g);
}
out
}
/// The layers and groups around object `id` of `src` that are not also around `other`, outermost
/// first.
fn own_layers(src: &Document, id: NodeId, other: Option<NodeId>) -> Vec<&Node> {
let mine = src.ancestry(id).unwrap_or_default();
let theirs = other.and_then(|t| src.ancestry(t)).unwrap_or_default();
let shared = mine.iter().zip(&theirs).take_while(|(a, b)| a == b).count();
let own = mine.get(shared..mine.len().saturating_sub(1)).unwrap_or_default();
own.iter().filter_map(|a| src.node(*a)).collect()
}
/// The clip groups and clipping layers around object `id` of `d`, innermost first.
fn clip_ancestors(d: &Document, id: NodeId) -> Vec<NodeId> {
let mut a = d.ancestry(id).unwrap_or_default();
a.pop();
a.into_iter().rev().filter(|a| d.node(*a).is_some_and(Node::clips)).collect()
}
/// Whether the layers around object `id` of `d` all print, all show, and whether one is a
/// template.
fn layer_state(d: &Document, id: NodeId) -> (bool, bool, bool) {
let mut a = d.ancestry(id).unwrap_or_default();
a.pop();
a.iter().filter_map(|a| d.node(*a)).fold((true, true, false), |(print, show, template), n| match &n.kind {
NodeKind::Layer { printable, template: t, .. } => (print && *printable, show && n.visible, template || *t),
_ => (print, show, template),
})
}
/// For group `g` (indices of `roots` of `src`, in paint order) whose flattened group can't leave
/// the clip groups and clipping layers of its topmost object ([`place_of`]): the objects inside
/// them and the objects under them. `None` when the group can leave them, or every object is
/// inside them.
fn inside_and_under(src: &Document, roots: &[NodeId], g: &[usize]) -> Option<(Vec<usize>, Vec<usize>)> {
if !clips_count() || g.len() < 2 {
return None;
}
let ids: Vec<NodeId> = g.iter().map(|&i| roots[i]).collect();
let top = clip_ancestors(src, *ids.last()?);
if top.is_empty() {
return None;
}
let inside = |id: NodeId| {
let mine = clip_ancestors(src, id);
top.iter().all(|c| mine.contains(c))
};
if !inside(place_of(src, &ids)?) {
return None;
}
let (inside, under): (Vec<usize>, Vec<usize>) = g.iter().partition(|&&i| inside(roots[i]));
(!under.is_empty()).then_some((inside, under))
}
/// The regions and the image area replacing one group of overlapping objects (`plain`: the art as
/// composited; `cmyk`: in a CMYK document); `None` when it paints nothing.
fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Regions, Option<Area>)> {
@@ -163,8 +347,10 @@ fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Reg
let mut complex: Vec<usize> = vec![];
let mut gradients_only = !all;
for (k, r) in regions.iter().enumerate() {
if all || r.sources.iter().any(|&i| b.kinds[i] != Kind::Vector) {
gradients_only &= r.sources.iter().all(|&i| b.kinds[i] == Kind::Gradient);
// Art outside the clipping path of its clip group draws nothing there.
let shown = |i: &&usize| b.kinds[**i] == Kind::Vector || !(clips_count() && b.hidden(**i, &r.sources));
if all || r.sources.iter().filter(shown).any(|&i| b.kinds[i] != Kind::Vector) {
gradients_only &= r.sources.iter().filter(shown).all(|&i| b.kinds[i] == Kind::Gradient);
complex.push(k);
} else if let Some(fill) = region_fill(&elems, &r.sources, o, cmyk) {
vector.push((k, fill));
@@ -227,6 +413,35 @@ pub(crate) fn with_every_region<T>(f: impl FnOnce() -> T) -> T {
out
}
#[cfg(test)]
thread_local! {
/// Groups flattened on this thread rasterize art where its clip group or clipping layer hides
/// it too ([`with_clips_ignored`]).
static CLIPS_IGNORED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Whether a region outside the clipping path of a clip group or clipping layer leaves out the
/// art it hides there.
#[cfg(test)]
fn clips_count() -> bool {
!CLIPS_IGNORED.with(std::cell::Cell::get)
}
#[cfg(not(test))]
fn clips_count() -> bool {
true
}
/// `f` with every group it flattens rasterizing art where its clip group or clipping layer hides
/// it too.
#[cfg(test)]
pub(crate) fn with_clips_ignored<T>(f: impl FnOnce() -> T) -> T {
CLIPS_IGNORED.with(|e| e.set(true));
let out = f();
CLIPS_IGNORED.with(|e| e.set(false));
out
}
/// The flat colour of a region covered by `sources` (CMYK in a `cmyk` document); `None` where
/// nothing paints it.
fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool) -> Option<RegionFill> {
@@ -269,6 +484,9 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool
fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Option<PathData>, o: &FlattenOptions) -> Result<Raster> {
let mut scale = ppi / 72.0;
scale = scale.min((MAX_PIXELS / (rect.width() * rect.height()).max(1.0)).sqrt());
// No side longer than the renderer draws: the image grows by a pixel on each side and is
// rounded up to whole pixels below.
scale = scale.min((f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 4.0) / rect.width().max(rect.height()).max(1.0));
let px = 1.0 / scale;
let rect = rect.inflate(px, px);
let clip = clip.map(|c| Some(po::offset_path(&c, px, po::Join::Miter, 4.0)).filter(|g| !g.is_empty()).unwrap_or(c));
@@ -424,7 +642,18 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan
let one_pass = separate(d, &plan.flat.iter().flat_map(|f| f.roots.iter().copied()).collect::<Vec<_>>());
for f in plan.flat {
// A group always has objects.
let Some(&top) = f.roots.last() else { continue };
let Some(top) = place_of(d, &f.roots) else { continue };
// Art hidden entirely is removed.
if f.regions.is_empty() && f.area.is_none() {
if one_pass {
flat.extend(f.roots.iter().map(|r| (*r, vec![])));
} else {
for r in &f.roots {
d.remove(*r)?;
}
}
continue;
}
let mut children = vec![];
// The image goes under the regions, reaching a pixel past its own: their edges then fall on
// matching pixels instead of on what is behind the group.
@@ -494,6 +723,30 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan
Ok((ids, vector, rasterized))
}
/// The object of `roots` (in paint order) whose place their flattened group takes: the topmost one
/// that no clip group or clipping layer clips unless it clips every object of `roots`, else the
/// topmost one. The group stays with the topmost object rather than move to a layer that prints,
/// shows or is a template where the topmost object's layer differs, out from a clip group or
/// clipping layer whose clipping path has a fill, which would then cover it, or out from a layer
/// or group with opacity, a blend mode or isolation.
fn place_of(d: &Document, roots: &[NodeId]) -> Option<NodeId> {
let top = roots.last().copied()?;
if !clips_count() || roots.len() < 2 {
return Some(top);
}
let fills = |clip: &NodeId| d.node(*clip).and_then(|n| n.children()?.first().map(|c| c.clip_paint().fill.is_some())).unwrap_or(false);
let all: Vec<Vec<NodeId>> = roots.iter().map(|r| clip_ancestors(d, *r)).collect();
let above = all.last().map_or(&[][..], Vec::as_slice);
let shared = |mine: &Vec<NodeId>| mine.iter().all(|c| all.iter().all(|theirs| theirs.contains(c)));
let leaves_fill = |mine: &Vec<NodeId>| above.iter().any(|c| !mine.contains(c) && fills(c));
// Out of a layer or group with opacity, a blend mode or isolation, the group would lose it.
let leaves_compositing = |r: NodeId| own_layers(d, top, Some(r)).iter().any(|a| !draws_as_is(a));
let state = layer_state(d, top);
let place =
roots.iter().zip(&all).rev().find(|(r, mine)| shared(mine) && !leaves_fill(mine) && layer_state(d, **r) == state && !leaves_compositing(**r));
Some(place.map_or(top, |(r, _)| *r))
}
/// 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");
+1 -1
View File
@@ -10,7 +10,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Flatten Transparency…",
["Object"],
None,
"{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach; objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
"{preset?: \"high\"|\"medium\"|\"low\" or a saved preset's name (see flattener.presets.list; default medium), balance?: 0..100 (raster/vector balance; 0 rasterizes everything), lineArtPpi?: 1..2400, gradientPpi?: 1..2400 (areas only gradients and meshes reach; an image larger than 64 Mpx or 32,768 px a side is made at a lower resolution), textToOutlines?, strokesToOutlines?, clipComplexRegions? (clip images to the region outlines, else rectangles), antiAlias?, preserveAlpha? (composite over nothing instead of white), preserveOverprints? (areas showing one paint keep its colour and overprint; false clears overprints), options?: {the same keys}, ids?|id?} overlapping transparent objects become one group of flat-colour regions (CMYK colours composited ink by ink in CMYK documents), plus an image where gradients, patterns, images, masks or raster effects reach (only where a clip group's or clipping layer's clipping path shows them, over its fill; transparent objects such a path hides entirely are removed); objects without transparency stay; a frame of threaded text that is outlined or flattened leaves its thread with the text it shows → {ids, rasterized: images made, vector: regions made, options, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
has_doc,
flatten
),
+25 -1
View File
@@ -53,6 +53,11 @@ enum Body {
pub(super) struct Builder {
pub(super) shapes: Vec<po::Shape>,
pub(super) kinds: Vec<Kind>,
/// Per shape, the clipping path of the innermost clip group it is in (a clipping path's own
/// entry is the clip group around its group).
pub(super) clip_of: Vec<Option<usize>>,
/// The clipping path of the clip group being built.
pub(super) clip: Option<usize>,
/// Building a CMYK document's art.
pub(super) cmyk: bool,
}
@@ -72,9 +77,24 @@ impl Builder {
path.bounds()?;
self.shapes.push(po::Shape::new(path, rule, self.shapes.len() as u64));
self.kinds.push(kind);
self.clip_of.push(self.clip);
Some(self.shapes.len() - 1)
}
/// Whether a clip group hides shape `shape` in the region `sources` cover (ascending): the
/// region lies outside one of the clipping paths around the shape.
pub(super) fn hidden(&self, shape: usize, sources: &[usize]) -> bool {
let around = |shape: usize| self.clip_of.get(shape).copied().flatten();
let mut clip = around(shape);
while let Some(c) = clip {
if sources.binary_search(&c).is_err() {
return true;
}
clip = around(c);
}
false
}
pub(super) fn elem(&mut self, n: &Node) -> Option<Elem> {
if !n.visible {
return None;
@@ -93,7 +113,11 @@ impl Builder {
} else {
(None, &children[..])
};
Body::Group { clip, children: rest.iter().filter_map(|c| self.elem(c)).collect() }
let outer = self.clip;
self.clip = clip.or(outer);
let children = rest.iter().filter_map(|c| self.elem(c)).collect();
self.clip = outer;
Body::Group { clip, children }
}
NodeKind::Path { guide: true, .. } => return None,
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
+2 -2
View File
@@ -43,8 +43,8 @@ use generate::generate;
#[cfg(test)]
use series::default_series_color;
pub(crate) use series::{
capture_label_styles, capture_series_object_opacity, capture_series_opacity, capture_series_paints, capture_series_top_paints, paint_targets,
series_object_opacity_differs, shown_paint,
capture_label_anti_alias, capture_label_paragraphs, capture_label_styles, capture_series_object_opacity, capture_series_opacity,
capture_series_paints, capture_series_top_paints, paint_targets, series_object_opacity_differs, shown_paint,
};
#[cfg(test)]
+4
View File
@@ -50,6 +50,10 @@ pub(super) fn parse_csv(csv: &str) -> (Vec<String>, Vec<String>, Vec<Vec<Option<
.map(|l| l.trim_end_matches('\r'))
.filter(|l| !l.trim().is_empty())
.map(|l| {
// A lone `""` line is a single blank value (`to_csv` writes it so the row isn't dropped as empty).
if l.trim() == "\"\"" {
return vec![Cell { text: String::new(), quoted: false }];
}
let tabs = split_unquoted(l, '\t');
let parts = if tabs.len() > 1 { tabs } else { split_unquoted(l, ',') };
parts.into_iter().map(cell).collect()
+12 -8
View File
@@ -2,7 +2,8 @@ use super::axis::{LABEL_SIZE, MAX_CATEGORY_TICKS, MAX_TICK_MARKS, one_line, rada
use super::columns::{Allowance, ColumnArt, column_art, column_designs};
use super::data::fmt_value;
use super::labels::{
Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, filled_lines_on, label_size, label_width, polyline, recolour_text, runs, shadow_of,
Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, filled_lines_on, label_extra_height, label_shift, label_size, label_width, polyline,
recolour_text, runs, shadow_of,
};
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
use super::series::{series_marks, with_series_opacity};
@@ -901,18 +902,21 @@ impl<'a> Plot<'a> {
fn legend_label(&mut self, (x, y): (f64, f64), label: &str) -> Arc<Node> {
let ls = self.ls;
let (dx, dy) = label_shift(&self.g.label_styles, label, self.b.d.setup.system_layout);
let (x, y) = (x + dx, y + dy);
self.b.label(Role::Legend, Point::new(x + 12.0, y + 7.5 + (ls - LABEL_SIZE) * 0.35), label, Justify::Left, false)
}
/// Add Legend Across Top: swatch and label after swatch and label, in rows as wide as the plot, the last row
/// just above it.
fn legend_across_top(&mut self) -> Vec<Arc<Node>> {
let (g, r, ls) = (self.g, self.r, self.ls);
let (g, r, ls, system_layout) = (self.g, self.r, self.ls, self.b.d.setup.system_layout);
let entries: Vec<(usize, String)> = (0..self.legend_series()).map(|s| (s, self.legend_text(s))).filter(|(_, l)| !blank_label(l)).collect();
let mut rows: Vec<Vec<(usize, String, f64)>> = vec![vec![]];
let mut rows: Vec<Vec<(usize, String, f64, f64)>> = vec![vec![]];
let mut used = 0.0;
for (s, label) in entries {
let w = 12.0 + label_width(&g.label_styles, &label) + 12.0;
let w = 12.0 + label_width(&g.label_styles, &label, system_layout) + 12.0;
let h = ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&g.label_styles, &label, system_layout);
// The gap after an entry may run past the plot's edge.
if used + w - 12.0 > r.width() && rows.last().is_some_and(|row| !row.is_empty()) {
rows.push(vec![]);
@@ -920,10 +924,10 @@ impl<'a> Plot<'a> {
}
used += w;
if let Some(row) = rows.last_mut() {
row.push((s, label, w));
row.push((s, label, w, h));
}
}
let height = |row: &[(usize, String, f64)]| ls * 1.8 * row.iter().map(|(_, l, _)| l.split('|').count()).max().unwrap_or(1) as f64;
let height = |row: &[(usize, String, f64, f64)]| row.iter().map(|(.., h)| *h).fold(ls * 1.8, f64::max);
// Above the plot and anything drawn over it (radar and stacked-pie labels).
let top = self.b.out.iter().chain(self.on_top.iter()).filter_map(|n| n.geometric_bounds()).map(|bb| bb.y0).fold(r.y0, f64::min);
let top = self.bars_reach.map_or(top, |b| top.min(b.y0));
@@ -931,7 +935,7 @@ impl<'a> Plot<'a> {
let mut labels = vec![];
for row in &rows {
let mut x = r.x0;
for (s, label, w) in row {
for (s, label, w, _) in row {
self.legend_swatch(*s, (x, y));
labels.push(self.legend_label((x, y), label));
x += w;
@@ -954,7 +958,7 @@ impl<'a> Plot<'a> {
y += ls * 1.8;
continue;
}
y += ls * 1.8 * label.split('|').count() as f64;
y += ls * 1.8 * label.split('|').count() as f64 + label_extra_height(&self.g.label_styles, &label, self.b.d.setup.system_layout);
self.legend_swatch(s, (x, row_y));
labels.push(self.legend_label((x, row_y), &label));
}
+90 -7
View File
@@ -10,7 +10,7 @@ use super::{
pub(super) struct Gen<'a> {
pub(super) d: &'a mut Document,
pub(super) out: Vec<Arc<Node>>,
/// The labels' kept character styles.
/// The labels' kept character styles and paragraph attributes.
pub(super) styles: &'a vectorcraft_doc::LabelStyles,
/// What the column designs may still add.
pub(super) columns: Allowance,
@@ -45,6 +45,34 @@ pub(super) fn label_style(styles: &vectorcraft_doc::LabelStyles, role: Role) ->
st
}
/// The paragraph attributes labels of `role` are set with: the kept ones, else the defaults. The caller sets the
/// alignment.
pub(super) fn label_para(styles: &vectorcraft_doc::LabelStyles, role: Role) -> vectorcraft_doc::ParaStyle {
let mut para = kept_para(styles, role).cloned().unwrap_or_default();
// A file's attributes within the limits the Paragraph controls keep to (they are copied onto every label).
para.keep_spacing_in_range();
para
}
/// The paragraph attributes labels of `role` keep, if any.
fn kept_para(styles: &vectorcraft_doc::LabelStyles, role: Role) -> Option<&vectorcraft_doc::ParaStyle> {
match role {
Role::Value => styles.values_para.as_ref(),
Role::Category => styles.categories_para.as_ref(),
Role::Legend => styles.legend_para.as_ref(),
}
}
/// The anti-aliasing method labels of `role` are drawn with: the kept one, else Sharp.
pub(super) fn label_anti_alias(styles: &vectorcraft_doc::LabelStyles, role: Role) -> vectorcraft_doc::text::TypeAntiAlias {
let kept = match role {
Role::Value => styles.values_anti_alias,
Role::Category => styles.categories_anti_alias,
Role::Legend => styles.legend_anti_alias,
};
kept.unwrap_or_default()
}
/// How big labels of `role` are set: a kept style's size, else 9 pt. The labels' spacing follows it.
pub(super) fn label_size(styles: &vectorcraft_doc::LabelStyles, role: Role) -> f64 {
label_style(styles, role).size
@@ -61,19 +89,39 @@ impl Gen<'_> {
self.path(PathData::from_bezpath(&bp), Paint::None, Paint::solid(Color::BLACK), 0.5)
}
pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc<Node> {
let t = self.text_object(role, at, s, justify);
Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t))))
}
/// Label `s` of `role` set at `at` and laid out, not yet in the document.
fn text_object(&self, role: Role, at: Point, s: &str, justify: Justify) -> TextObject {
let style = label_style(self.styles, role);
let mut t = TextObject::point(at, s, style);
t.para = label_para(self.styles, role);
t.anti_alias = label_anti_alias(self.styles, role);
t.para.justify = justify;
t.system_layout = self.d.setup.system_layout;
refresh_bounds(&mut t);
Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t))))
t
}
/// A category or series label: a `|` in it starts a new line (Add graph labels). `middle`: the lines are centred
/// on `at` (labels beside an axis or in a wedge) instead of running down from it.
pub(super) fn label(&mut self, role: Role, at: Point, s: &str, justify: Justify, middle: bool) -> Arc<Node> {
let lines = s.split('|').count();
let at = if middle { Point::new(at.x, at.y - (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0) } else { at };
self.text(role, at, &s.replace('|', "\n"), justify)
// Default leading puts the first and last baselines this far above and below `at`.
let half = (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0;
let start = if middle { Point::new(at.x, at.y - half) } else { at };
let mut t = self.text_object(role, start, &s.replace('|', "\n"), justify);
// Kept leading or paragraph spacing moves the lines: put the middle of the first and last baselines on `at`. An
// empty line has no baseline: an empty first or last line leaves the label where the default leading puts it.
if middle && kept_para(self.styles, role).is_some() {
let ys: Vec<f64> = t.baselines().map(|(a, _)| a.y).collect();
let ends_set = s.split('|').next().is_some_and(|l| !l.is_empty()) && s.split('|').next_back().is_some_and(|l| !l.is_empty());
let set = s.split('|').filter(|l| !l.is_empty()).count();
if let (Some(first), Some(last), true) = (ys.first(), ys.last(), ends_set && ys.len() == set) {
t.xf = Affine::translate((0.0, half - (first + last) / 2.0)) * t.xf;
}
}
Arc::new(Node::new(self.d.alloc_id(), NodeKind::Text(Box::new(t))))
}
pub(super) fn group(&mut self, name: &str, children: Vec<Arc<Node>>) -> Arc<Node> {
let mut g = Node::group(self.d.alloc_id(), children);
@@ -162,12 +210,47 @@ pub(super) fn shadow_of(d: &mut Document, n: &Node) -> Arc<Node> {
Arc::new(d.reid(&c))
}
/// How wide label `s` is set (its widest line), without adding it to a document.
pub(super) fn label_width(styles: &vectorcraft_doc::LabelStyles, s: &str) -> f64 {
/// The bounds of legend label `s` set from the origin with paragraph attributes `para` and the document's System
/// Layout setting `system_layout`, as [`Gen::text`] sets it, without adding it to a document.
fn legend_label_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str, para: vectorcraft_doc::ParaStyle, system_layout: bool) -> Option<Rect> {
let style = label_style(styles, Role::Legend);
let mut t = TextObject::point(Point::ZERO, &s.replace('|', "\n"), style);
t.para = para;
t.para.justify = Justify::Left;
t.system_layout = system_layout;
refresh_bounds(&mut t);
Node::new(NodeId(0), NodeKind::Text(Box::new(t))).geometric_bounds().map_or(0.0, |b| b.width())
Node::new(NodeId(0), NodeKind::Text(Box::new(t))).geometric_bounds()
}
/// How far label `s` reaches right of where it starts (its widest line and any indent), after the legend moves it right
/// by [`label_shift`], without adding it to a document.
pub(super) fn label_width(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> f64 {
legend_label_bounds(styles, s, label_para(styles, Role::Legend), system_layout)
.map_or(0.0, |b| (b.x1 + label_shift(styles, s, system_layout).0).max(0.0))
}
/// The bounds of legend label `s` set with its kept paragraph attributes and with the defaults, when it has kept ones.
fn kept_and_default_bounds(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> Option<(Rect, Rect)> {
styles.legend_para.as_ref()?;
Some((
legend_label_bounds(styles, s, label_para(styles, Role::Legend), system_layout)?,
legend_label_bounds(styles, s, vectorcraft_doc::ParaStyle::default(), system_layout)?,
))
}
/// How much further left and further up legend label `s` reaches with its kept paragraph attributes than with the
/// defaults (a negative indent or negative spacing), so the legend moves it right and down by that much and it stays
/// clear of its swatch and of the entries before it.
pub(super) fn label_shift(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> (f64, f64) {
kept_and_default_bounds(styles, s, system_layout)
.map_or((0.0, 0.0), |(kept, default)| ((default.x0 - kept.x0).max(0.0), (default.y0 - kept.y0).max(0.0)))
}
/// How much further down legend label `s` reaches with its kept paragraph attributes than with the defaults (more
/// leading, or space before or after), after the legend moves it down by [`label_shift`], so the legend makes room
/// for it.
pub(super) fn label_extra_height(styles: &vectorcraft_doc::LabelStyles, s: &str, system_layout: bool) -> f64 {
kept_and_default_bounds(styles, s, system_layout).map_or(0.0, |(kept, default)| (kept.y1 + (default.y0 - kept.y0).max(0.0) - default.y1).max(0.0))
}
/// A label with nothing to show (empty, or only `|` line breaks).
+59 -12
View File
@@ -1,7 +1,7 @@
use vectorcraft_color::BlendMode;
use super::axis::radar_axis;
use super::labels::{Role, filled_lines_on, label_style};
use super::labels::{Role, filled_lines_on, label_para, label_style};
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad};
// ---------- generation ----------
@@ -406,23 +406,34 @@ fn graph_labels(doc: &Document) -> HashMap<NodeId, (NodeId, Role)> {
out
}
/// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels
/// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or
/// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so
/// they undo together. Returns whether a kept style changed.
pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool {
if ids.is_empty() {
return false;
}
/// Keep the anti-aliasing method `method` given to graph labels `ids` for every label of their kind, as
/// [`capture_label_styles`] keeps a formatting change. Returns whether a kept method changed.
pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], method: vectorcraft_doc::text::TypeAntiAlias) -> bool {
let labels = graph_labels(doc);
if labels.is_empty() {
return false;
}
let mut kinds: Vec<(NodeId, Role)> = ids.iter().filter_map(|id| labels.get(id).copied()).collect();
kinds.sort_by_key(|(g, r)| (g.0, *r as u8));
kinds.dedup();
let mut changed = false;
for (graph, role) in kinds {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
let slot = match role {
Role::Value => &mut spec.label_styles.values_anti_alias,
Role::Category => &mut spec.label_styles.categories_anti_alias,
Role::Legend => &mut spec.label_styles.legend_anti_alias,
};
changed |= *slot != Some(method);
*slot = Some(method);
}
changed
}
/// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels
/// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or
/// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so
/// they undo together. Returns whether a kept style changed.
pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool {
let mut changed = false;
for (graph, role) in label_kinds(doc, ids) {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
let mut style = label_style(&spec.label_styles, role);
change(&mut style);
@@ -437,6 +448,42 @@ pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &
changed
}
/// Keep a paragraph change made to all of the text of graph labels `ids` (Paragraph, on the whole graph or on labels
/// picked with Group Selection) for every label of their kind, as [`capture_label_styles`] does for character
/// formats. Returns whether kept attributes changed, or the error `change` returns for the kept attributes.
pub(crate) fn capture_label_paragraphs(
doc: &mut Document,
ids: &[NodeId],
change: &dyn Fn(&mut vectorcraft_doc::ParaStyle) -> Result<()>,
) -> Result<bool> {
let mut changed = false;
for (graph, role) in label_kinds(doc, ids) {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
let mut para = label_para(&spec.label_styles, role);
change(&mut para)?;
let slot = match role {
Role::Value => &mut spec.label_styles.values_para,
Role::Category => &mut spec.label_styles.categories_para,
Role::Legend => &mut spec.label_styles.legend_para,
};
changed |= slot.as_ref() != Some(&para);
*slot = Some(para);
}
Ok(changed)
}
/// The graphs and kinds of label among `ids`, each once.
fn label_kinds(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role)> {
if ids.is_empty() {
return vec![];
}
let labels = graph_labels(doc);
let mut kinds: Vec<(NodeId, Role)> = ids.iter().filter_map(|id| labels.get(id).copied()).collect();
kinds.sort_by_key(|(g, r)| (g.0, *r as u8));
kinds.dedup();
kinds
}
/// The series a command on graph `id` (of `count` series) applies to: `seriesIndexes`, else, with no `id` param, a
/// selection made only of this graph's series (Group Selection). Empty: the whole graph.
pub(super) fn picked_series(s: &Session, p: &Value, id: NodeId, count: usize, cmd: &str) -> Result<Vec<usize>> {
+288
View File
@@ -4055,6 +4055,45 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() {
assert_eq!(spec(&s, id).label_styles, vectorcraft_doc::LabelStyles::default());
}
/// An anti-aliasing method given to one category label is kept for every category label when the graph is drawn
/// again, through save and open, and undoes with the change.
#[test]
fn a_graph_labels_anti_aliasing_method_survives_it_being_drawn_again() {
use vectorcraft_doc::text::TypeAntiAlias;
let methods = |s: &Session, id: NodeId| -> Vec<(String, TypeAntiAlias)> {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let mut out = vec![];
for g in ["Axes", "Legend"] {
for c in group(&n, g).children().unwrap() {
if let NodeKind::Text(t) = &c.kind {
out.push((t.plain_text(), t.anti_alias));
}
}
}
out
};
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let c = text_id(&s, id, "Axes", "Q2");
s.execute("text.setFormat", &json!({"ids": [c.0], "antiAlias": "strong"})).unwrap();
label_looks(&mut s, id);
let drawn = methods(&s, id);
let method = |t: &str| drawn.iter().find(|(x, _)| x == t).map(|(_, m)| *m).unwrap();
assert_eq!((method("Q1"), method("Q3")), (TypeAntiAlias::Strong, TypeAntiAlias::Strong), "every category label: {drawn:?}");
assert_eq!((method("0"), method("2024")), (TypeAntiAlias::Sharp, TypeAntiAlias::Sharp), "other labels: {drawn:?}");
// One undo takes the data change back, the next the method and the kept method together.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(spec(&s, id).label_styles.categories_anti_alias, None);
s.execute("edit.redo", &json!({})).unwrap();
let path = vectorcraft_testkit::temp_dir("graph-label-anti-alias").join("labels.vectorcraft");
s.execute("document.save", &json!({"path": path})).unwrap();
s.execute("document.open", &json!({"path": path})).unwrap();
assert_eq!(spec(&s, id).label_styles.categories_anti_alias, Some(TypeAntiAlias::Strong));
assert!(serde_json::to_value(GraphSpec::default()).unwrap().get("labelStyles").is_none());
}
/// A stroke given to all of a graph's text without a weight is kept at 1 pt, as `paint.setStroke` keeps it.
#[test]
fn a_stroke_given_to_the_whole_graphs_text_is_kept_at_1_pt() {
@@ -4210,3 +4249,252 @@ fn character_formats_are_kept_and_bigger_labels_space_out() {
fn csv_leading_byte_order_mark_is_ignored() {
assert_eq!(super::parse_csv("\u{feff}1,2\n3,4"), super::parse_csv("1,2\n3,4"));
}
#[test]
fn csv_round_trip_keeps_blank_row_in_single_column_graph() {
let mut g = GraphSpec::default();
g.set_cells(vec![vec![Some(1.0)], vec![None], vec![Some(3.0)]]);
let (_, c, r) = super::parse_csv(&g.to_csv());
assert!(c.is_empty());
assert_eq!(r, g.cells());
}
/// Each generated label's text, paragraph attributes and alignment.
fn label_paras(s: &Session, id: NodeId) -> Vec<(String, vectorcraft_doc::ParaStyle)> {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let mut out = vec![];
for name in ["Axes", "Legend"] {
for c in group(&n, name).children().unwrap() {
if let NodeKind::Text(t) = &c.kind {
out.push((t.plain_text(), t.para.clone()));
}
}
}
out
}
#[test]
fn paragraph_formats_are_kept_when_the_graph_is_drawn_again() {
use vectorcraft_doc::{Composer, ParaDirection, text::Kashida};
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let aligned: Vec<_> = label_paras(&s, id).into_iter().map(|(t, p)| (t, p.justify)).collect();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setFormat", &json!({"composer": "singleLine", "kashida": "long", "direction": "rightToLeft", "wordSpacing": [70, 90, 120]}))
.unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
let paras = label_paras(&s, id);
assert!(!paras.is_empty());
for (text, p) in &paras {
assert_eq!(p.composer, Composer::SingleLine, "{text}");
assert_eq!(p.kashida, Kashida::Long, "{text}");
assert_eq!(p.direction, Some(ParaDirection::RightToLeft), "{text}");
assert_eq!(p.justification.word_spacing, [70.0, 90.0, 120.0], "{text}");
}
// The graph still aligns each label to its place.
assert_eq!(paras.iter().map(|(t, p)| (t.clone(), p.justify)).collect::<Vec<_>>(), aligned);
// One kind of label: only that kind keeps it, also through save and open.
let col = graph(&mut s, "column");
let v = text_id(&s, col, "Axes", "4");
s.execute("select.set", &json!({"ids": [v.0]})).unwrap();
s.execute("text.setFormat", &json!({"composer": "singleLine"})).unwrap();
let path = vectorcraft_testkit::temp_dir("graph-label-paras").join("labels.vectorcraft");
s.execute("document.save", &json!({"path": path})).unwrap();
s.execute("document.open", &json!({"path": path})).unwrap();
s.execute("select.set", &json!({"ids": [col.0]})).unwrap();
s.execute("graph.setData", &json!({"id": col.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
let paras = label_paras(&s, col);
let composer = |t: &str| paras.iter().find(|(x, _)| x == t).unwrap().1.composer;
assert_eq!(composer("0"), Composer::SingleLine, "every value axis number");
assert_eq!(composer("Q1"), Composer::default(), "category labels as they were");
assert_eq!(composer("2024"), Composer::default(), "legend labels as they were");
// Part of a label's text: nothing kept.
let q = text_id(&s, col, "Axes", "Q2");
s.execute("select.set", &json!({"ids": [q.0]})).unwrap();
s.execute("text.setFormat", &json!({"kashida": "short", "start": 0, "end": 1})).unwrap();
s.execute("graph.setData", &json!({"id": col.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
assert!(label_paras(&s, col).iter().all(|(_, p)| p.kashida == Kashida::default()));
// Spacing that would be out of order in the kept attributes is refused, even when it is in order on the label.
let v = text_id(&s, col, "Axes", "4");
s.execute("select.set", &json!({"ids": [col.0]})).unwrap();
s.execute("text.setFormat", &json!({"wordSpacing": [60, 70, 80]})).unwrap();
s.execute("select.set", &json!({"ids": [v.0]})).unwrap();
s.execute("text.setFormat", &json!({"wordSpacing": [80, 100, 133], "start": 0, "end": 1})).unwrap();
assert!(s.execute("text.setFormat", &json!({"wordSpacing": {"min": 90}})).is_err());
let kept = spec(&s, col).label_styles.values_para.unwrap();
assert_eq!(kept.justification.word_spacing, [60.0, 70.0, 80.0]);
}
#[test]
fn a_legend_across_top_spaces_its_labels_by_their_kept_paragraph_settings() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
s.execute("graph.setType", &json!({"legendAcrossTop": true})).unwrap();
let l = text_id(&s, id, "Legend", "2024");
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
s.execute("text.setFormat", &json!({"leftIndent": 40})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "2024")).unwrap();
let label = label.geometric_bounds().unwrap();
let next = series_parts(&s, id, 1).last().unwrap().geometric_bounds().unwrap();
assert!(next.x0 >= label.x1, "the next swatch starts after the indented label: {label:?} {next:?}");
}
#[test]
fn a_centered_label_with_kept_leading_stays_centered_when_the_graph_is_drawn_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",2024,2025\nQ|1,3,2\nQ2,5,4\nQ3,-1,6";
let id = NodeId(
s.execute("graph.create", &json!({"type": "bar", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let middle = |s: &Session| {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let label = group(&n, "Axes").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "Q\n1")).unwrap();
let b = label.geometric_bounds().unwrap();
(b.y0 + b.y1) / 2.0
};
let before = middle(&s);
let l = text_id(&s, id, "Axes", "Q\n1");
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
s.execute("text.setFormat", &json!({"autoLeading": 400, "spaceBefore": 6})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let after = middle(&s);
assert!((after - before).abs() < 0.01, "the two-line category label keeps its middle: {before} {after}");
}
#[test]
fn a_centered_label_with_an_empty_middle_line_and_kept_leading_stays_centered() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",2024,2025\nQ||1,3,2\nQ2,5,4\nQ3,-1,6";
let id = NodeId(
s.execute("graph.create", &json!({"type": "bar", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let middle = |s: &Session| {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let label =
group(&n, "Axes").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "Q\n\n1")).unwrap();
let b = label.geometric_bounds().unwrap();
(b.y0 + b.y1) / 2.0
};
let before = middle(&s);
let l = text_id(&s, id, "Axes", "Q\n\n1");
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
s.execute("text.setFormat", &json!({"autoLeading": 400})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let after = middle(&s);
assert!((after - before).abs() < 0.01, "the three-line category label keeps its middle: {before} {after}");
}
#[test]
fn a_legend_across_top_measures_its_labels_with_system_layout() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("type.systemLayout", &json!({"on": true})).unwrap();
// Each `i` at 2 pt advances a whole point with System Layout, far more than its own width.
let name = "i".repeat(60);
let csv = format!(",{name},2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6");
let id = NodeId(
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute("graph.setType", &json!({"legendAcrossTop": true})).unwrap();
let l = text_id(&s, id, "Legend", &name);
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": 2})).unwrap();
s.execute("text.setFormat", &json!({"leftIndent": 1})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == name)).unwrap();
let label = label.geometric_bounds().unwrap();
let next = series_parts(&s, id, 1).last().unwrap().geometric_bounds().unwrap();
assert!(next.x0 >= label.x1, "the next swatch starts after the label set with System Layout: {label:?} {next:?}");
}
#[test]
fn a_legend_label_with_a_kept_negative_indent_stays_clear_of_its_swatch() {
for across_top in [true, false] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
s.execute("graph.setType", &json!({"legendAcrossTop": across_top})).unwrap();
let l = text_id(&s, id, "Legend", "2025");
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
s.execute("text.setFormat", &json!({"leftIndent": -40})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let bounds = |text: &str| {
let label =
group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap();
label.geometric_bounds().unwrap()
};
let (first, label) = (bounds("2024"), bounds("2025"));
let swatch = series_parts(&s, id, 1).last().unwrap().geometric_bounds().unwrap();
assert!(label.x0 >= swatch.x1, "the label starts after its swatch (across top: {across_top}): {swatch:?} {label:?}");
if across_top {
assert!(swatch.x0 >= first.x1, "the swatch starts after the label before it: {first:?} {swatch:?}");
}
}
}
#[test]
fn a_legend_makes_room_for_the_kept_leading_of_its_labels() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",20|24,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
let id = NodeId(
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let l = text_id(&s, id, "Legend", "20\n24");
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
s.execute("text.setFormat", &json!({"autoLeading": 400})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let bounds = |text: &str| {
let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap();
label.geometric_bounds().unwrap()
};
let (first, next) = (bounds("20\n24"), bounds("2025"));
assert!(next.y0 >= first.y1, "the next legend label starts below the first one: {first:?} {next:?}");
}
#[test]
fn a_legend_label_with_kept_negative_space_before_stays_below_the_entry_above_it() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",2024,20|25\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
let id = NodeId(
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let l = text_id(&s, id, "Legend", "20\n25");
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
s.execute("text.setFormat", &json!({"spaceBefore": -60})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let bounds = |text: &str| {
let label = group(&n, "Legend").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap();
label.geometric_bounds().unwrap()
};
let (first, next) = (bounds("2024"), bounds("20\n25"));
assert!(next.y0 >= first.y1, "the second legend label starts below the first one: {first:?} {next:?}");
}
+48 -2
View File
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Artboard",
["Window", "Artboards"],
None,
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the size of artboard `beside`, 20 pt from that side of it; refused with x, y, width or height), beside?: n (the artboard `side` places it by; default the last)} (default place: right of the last)",
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), guideLabel?: name | \"#rrggbb\" | null (its guide label, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the size of artboard `beside`, 20 pt from that side of it; refused with x, y, width or height), beside?: n (the artboard `side` places it by; default the last)} (default place: right of the last)",
has_doc,
artboard_new
),
@@ -155,7 +155,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Artboard Options…",
["Window", "Artboards"],
None,
"{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}",
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
has_doc,
artboard_set
),
@@ -859,6 +859,22 @@ fn artboard_color(p: &Value, cmd: &str) -> Result<Option<Option<vectorcraft_colo
}
}
/// An artboard command's `guideLabel` param, the color of its own guides: None when absent,
/// `Some(None)` for null (no label), else `Some(Some(label))` for a preset's name exactly as
/// [`LAYER_COLORS`] spells it or `#rrggbb` ([`LayerColor::from_label_text`]). Any other value,
/// such as a preset's index, a name in other letter case or `#rrggbbaa`, is an error.
fn artboard_guide_label(p: &Value, cmd: &str) -> Result<Option<Option<LayerColor>>> {
match p.get("guideLabel") {
None => Ok(None),
Some(Value::Null) => Ok(Some(None)),
Some(v) => v
.as_str()
.and_then(LayerColor::from_label_text)
.map(|c| Some(Some(c)))
.ok_or_else(|| bad(cmd, "`guideLabel` is null, a layer color's name or #rrggbb")),
}
}
/// An artboard command's text param `key`: None when absent or null, else the string. Any other
/// value, such as 5, is an error: "`{key}` must be a string".
fn artboard_str<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<Option<&'a str>> {
@@ -898,6 +914,7 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> {
let last = d0.artboards.last().map(|a| a.rect).unwrap_or(Rect::new(0.0, 0.0, 612.0, 792.0));
let def = Rect::new(last.x1 + 20.0, last.y0, last.x1 + 20.0 + last.width(), last.y1);
let color = artboard_color(p, "artboard.new")?.flatten();
let guide_label = artboard_guide_label(p, "artboard.new")?.flatten();
check_switches(p, &["showCenterMark", "showCrossHairs", "showVideoSafeAreas"], "artboard.new")?;
check_numbers(p, &["x", "y", "width", "height"], "artboard.new")?;
let r = match artboard_side(p, "artboard.new")? {
@@ -932,6 +949,7 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> {
show_video_safe_areas,
video_ruler_pixel_aspect_ratio,
color,
guide_label,
});
Ok(d.artboards.len() - 1)
})?;
@@ -1001,6 +1019,7 @@ struct ArtboardEdit<'a> {
now: Rect,
name: Option<&'a str>,
color: Option<Option<vectorcraft_color::Color>>,
guide_label: Option<Option<LayerColor>>,
lock: Option<bool>,
center_mark: Option<bool>,
cross_hairs: Option<bool>,
@@ -1013,6 +1032,23 @@ struct ArtboardEdit<'a> {
art: Vec<NodeId>,
}
impl ArtboardEdit<'_> {
/// Does the edit change artboard `a` (the one at its index) or the art and guides on it?
fn changes(&self, a: &Artboard) -> bool {
let name = self.name.map(|n| if n.is_empty() { format!("Artboard {}", self.index + 1) } else { n.to_string() });
self.now != a.rect
|| self.transform.is_some()
|| name.is_some_and(|n| n != a.name)
|| self.color.is_some_and(|c| c != a.color)
|| self.guide_label.is_some_and(|c| c != a.guide_label)
|| self.lock.is_some_and(|l| l != a.locked)
|| self.center_mark.is_some_and(|m| m != a.show_center_mark)
|| self.cross_hairs.is_some_and(|c| c != a.show_cross_hairs)
|| self.safe_areas.is_some_and(|v| v != a.show_video_safe_areas)
|| self.pixel_aspect.is_some_and(|r| r != a.video_ruler_pixel_aspect_ratio)
}
}
fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
// One artboard (`index` and its fields), or several (`artboards`, each with its own fields).
let entries: Vec<&Value> = match p.get("artboards") {
@@ -1044,6 +1080,8 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
let was = d.artboards.get(index).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
// The background color: a color sets it, null clears it, absent leaves it as it is.
let color = artboard_color(q, "artboard.setProps")?;
// The guide label likewise; a locked artboard's can change, as its name can.
let guide_label = artboard_guide_label(q, "artboard.setProps")?;
let now = rect_from(q, was);
let lock = q.get("locked").and_then(Value::as_bool);
let (center_mark, cross_hairs) = (q.get("showCenterMark").and_then(Value::as_bool), q.get("showCrossHairs").and_then(Value::as_bool));
@@ -1070,6 +1108,7 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
now,
name: artboard_str(q, "name", "artboard.setProps")?.map(str::trim),
color,
guide_label,
lock,
center_mark,
cross_hairs,
@@ -1082,6 +1121,10 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
art,
});
}
// Nothing to change: no undo step.
if !edits.iter().any(|e| d.artboards.get(e.index).is_none_or(|a| e.changes(a))) {
return if scale_art { Ok(json!({ "scaled": [] })) } else { ok() };
}
// Noted in the journal when art goes along, so a replay transforms the same objects whatever
// the preference is then.
if edits.iter().any(|e| e.transform.is_some()) {
@@ -1102,6 +1145,9 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(c) = e.color {
a.color = c;
}
if let Some(c) = e.guide_label {
a.guide_label = c;
}
if let Some(l) = e.lock {
a.locked = l;
}
+5 -2
View File
@@ -115,7 +115,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rasterize…",
["Object"],
None,
"{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
"{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
has_selection,
rasterize
),
@@ -670,7 +670,9 @@ fn render_pixels(
opts: &vectorcraft_render::RenderOptions,
color: RasterColorModel,
) -> Result<(vectorcraft_render::Rendered, Option<&'static str>)> {
if region.width() * region.height() * scale * scale > MAX_PIXELS || region.width() * scale > 65535.0 || region.height() * scale > 65535.0 {
// No side longer than the renderer draws: it would cut the image off there.
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
if region.width() * region.height() * scale * scale > MAX_PIXELS || region.width() * scale > side || region.height() * scale > side {
return Err(EngineError::Other("image would be too large; lower the resolution".into()));
}
let mut r = vectorcraft_render::Renderer::new();
@@ -1319,6 +1321,7 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result<Value> {
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
});
converted.push(id);
}
+1
View File
@@ -344,6 +344,7 @@ impl DocSettings {
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
})
.collect();
d
+19 -4
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing com Line truncated
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, Line truncated
has_doc,
set_format
),
@@ -786,6 +786,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
}
};
s.edit("Character", |d, _| {
// The paragraph change, for the graph labels to keep.
let mut para_change = None;
let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"));
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
let baseline_shift = num("baselineShift").map(|v| super::typecmd::local_type_value(t, v, (-1296.0, 1296.0), false, C)).transpose()?;
@@ -794,7 +797,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let tcy = (local(tcy_up_down)?, local(tcy_left_right)?);
super::typecmd::style_chars(t, range, |st| chars(st, baseline_shift, h_scale, tcy));
let span = super::typecmd::para_span(range, t);
t.edit_paras(span, |para| {
let paras = |para: &mut vectorcraft_doc::ParaStyle, out_of_order: &mut Option<&'static str>| {
if let Some(v) = num("leftIndent") {
para.left_indent = v.clamp(-MAX_PARA, MAX_PARA);
}
@@ -882,17 +885,27 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = composer {
para.composer = v;
}
});
};
t.edit_paras(span, |para| paras(para, &mut out_of_order));
if let Some(name) = out_of_order {
return Err(bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
return Err(out_of_order_error(name));
}
super::typecmd::refresh_bounds(t);
para_change = Some(paras);
}
// Graph labels keep a change made to all of their text through the graph being drawn again.
if range.is_none() {
let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0));
let scale = num("hScale").map(|v| v.clamp(1.0, 10000.0));
super::graph::capture_label_styles(d, &ids, &|st| chars(st, shift, scale, (tcy_up_down, tcy_left_right)));
if let Some(paras) = para_change {
// The kept attributes are checked too: they may differ from the labels'.
super::graph::capture_label_paragraphs(d, &ids, &|para| {
let mut out_of_order = None;
paras(para, &mut out_of_order);
out_of_order.map_or(Ok(()), |name| Err(out_of_order_error(name)))
})?;
}
}
if let Some(v) = anti_alias {
for id in &ids {
@@ -900,6 +913,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
t.anti_alias = v;
}
}
// Graph labels keep the method through the graph being drawn again.
super::graph::capture_label_anti_alias(d, &ids, v);
}
Ok(())
})?;
+199 -55
View File
@@ -4,7 +4,7 @@ use std::collections::BTreeSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2};
use super::create::anchor_from_json;
@@ -131,11 +131,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Reshape",
[],
None,
"{id, x, y, dx, dy, tol=3, radius?} Reshape tool: grab the path at (x, y) (adding an anchor there unless one is within tol) and drag it by (dx, dy). An open path stretches from the grabbed point to its two ends, which stay in place: each anchor between takes a share of the drag that falls smoothly from 1 at the grabbed point to 0 at the end, by its distance along the path's control polygon. On a closed path, or when radius is given, nearby anchors follow with a smooth falloff over radius, measured along the path (0 or more; default: half the diagonal of the subpath's bounding box)",
"{id, x, y, dx, dy, tol=3, focal?: [[subpath, anchor]…], radius?} Reshape tool: grab the path at (x, y) (adding an anchor there unless one is within tol) and drag it by (dx, dy). The grabbed anchor and the anchors in focal are focal points and move by the whole drag. Anchors that are not direct-selected stay in place (a path selected whole, or not selected, has every anchor selected), and so do an open path's two ends unless they are focal points. A selected anchor between two focal points moves whole; one between a focal point and an anchor that stays takes a share of the drag that falls smoothly from 1 at the focal point to 0 at the anchor that stays, by its distance along the path's control polygon. A closed subpath with every anchor selected moves whole; a subpath with no focal point does not move. With radius, only the grabbed point's subpath changes: anchors follow with a smooth falloff over radius, measured along the path (0 or more), whatever the selection; focal and radius cannot be used together. Without focal (or with focal null) and without radius, the earlier rule applies: the selection does not matter, an open path stretches from the grabbed point to its two ends, and on a closed path the anchors follow with the falloff over half the diagonal of the subpath's bounding box; the Reshape tool always sends focal",
has_doc,
reshape
),
cmd!("path.insertAnchor", "Add Anchor Point", [], None, "{id, subpath?, segment, t: 0..1}", has_doc, insert_anchor),
cmd!(
"path.insertAnchor",
"Add Anchor Point",
[],
None,
"{id, subpath?, segment, t: 0..1} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected",
has_doc,
insert_anchor
),
cmd!(
"path.cutAtAnchors",
"Cut Path at Selected Anchor Points",
@@ -1410,55 +1418,143 @@ fn open_run(mut anchors: Vec<vectorcraft_geom::Anchor>) -> Option<SubPath> {
Some(SubPath::new(anchors, false))
}
/// The share of a Reshape drag that each anchor of an open subpath takes, as `[in handle, anchor,
/// out handle]`. The grabbed anchor takes all of it and the two end anchors take none. For an
/// anchor between the grabbed one and an end, `u` is its distance from that end along the control
/// polygon (anchor, out handle, the next in handle, the next anchor) divided by the grabbed
/// anchor's distance from that end, and its share is `u² (3 - 2u)`. A handle takes the share on
/// the tangent line of that curve at its anchor, so the two handles of a smooth anchor stay in
/// line with it. That share is below 0 or above 1 for a handle long enough beside the span.
fn stretch_weights(anchors: &[Anchor], grabbed: usize) -> Vec<[f64; 3]> {
let last = anchors.len().saturating_sub(1);
/// What an anchor does in a Reshape drag.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stretch {
/// Not selected: it stays in place.
Fixed,
/// Selected: it takes a share of the drag that depends on where it lies between the anchors
/// that stay and the focal points.
Selected,
/// A focal point (the grabbed anchor, or one the Reshape tool highlighted): it moves by the
/// whole drag.
Focal,
}
/// The share of a Reshape drag that each anchor of a subpath takes, as `[in handle, anchor, out
/// handle]`, from what each anchor does (`roles`, one per anchor). A focal point takes all of the
/// drag and an anchor that stays takes none. An open path's end anchors stay unless they are focal
/// points. A selected anchor between two focal points takes all of the drag, and one between two
/// anchors that stay takes none. For a selected anchor between an anchor that stays and a focal
/// point, `u` is its distance from the anchor that stays along the control polygon (anchor, out
/// handle, the next in handle, the next anchor) divided by the focal point's distance from it, and
/// its share is `u² (3 - 2u)`. A handle takes the share on the tangent line of that curve at its
/// anchor, so the two handles of a smooth anchor stay in line with it. That share is below 0 or
/// above 1 for a handle long enough beside the span. A closed subpath with no anchor that stays
/// moves whole when it has a focal point.
fn stretch_weights(anchors: &[Anchor], closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> {
let n = anchors.len();
let mut shares = vec![[0.0; 3]; n];
let role = |i: usize| match roles.get(i) {
Some(Stretch::Selected) if !closed && (i == 0 || i + 1 == n) => Stretch::Fixed,
Some(&r) => r,
None => Stretch::Fixed,
};
// The walk along the subpath starts at an anchor that stays, or else at a focal point, and on a
// closed subpath it comes back round to the same anchor, so every selected anchor lies between
// two anchors that are not selected ones.
let start = if closed { (0..n).find(|&i| role(i) == Stretch::Fixed).or_else(|| (0..n).find(|&i| role(i) == Stretch::Focal)) } else { Some(0) };
let Some(start) = start.filter(|_| n > 0) else { return shares };
let len = if closed { n + 1 } else { n };
let order: Vec<usize> = (0..len).map(|k| (start + k) % n).collect();
// Where each anchor's in handle, point and out handle lie along the control polygon. The in
// handle of the first anchor and the out handle of the last are not part of an open path.
let mut pos: Vec<[f64; 3]> = Vec::with_capacity(anchors.len());
let mut pos: Vec<[f64; 3]> = Vec::with_capacity(len);
let mut run = 0.0;
for (i, a) in anchors.iter().enumerate() {
if let Some(before) = i.checked_sub(1).and_then(|b| anchors.get(b)) {
run += before.h_out.distance(a.h_in);
let mut before: Option<&Anchor> = None;
for (k, a) in order.iter().filter_map(|&i| anchors.get(i)).enumerate() {
if let Some(b) = before {
run += b.h_out.distance(a.h_in);
}
let c_in = run;
if i > 0 {
if k > 0 {
run += a.h_in.distance(a.p);
}
let c = run;
if i < last {
if k + 1 < len {
run += a.p.distance(a.h_out);
}
pos.push([c_in, c, run]);
before = Some(a);
}
let at = pos.get(grabbed).map_or(0.0, |c| c[1]);
let length = pos.last().map_or(0.0, |c| c[1]);
pos.iter()
.enumerate()
.map(|(i, &[c_in, c, c_out])| {
if i == grabbed {
return [1.0; 3];
// The nearest anchor before and after each place in the walk that is not a selected one.
let bound = |k: usize| role(order.get(k).copied().unwrap_or(start)) != Stretch::Selected;
let mut previous = vec![0; len];
let mut last = 0;
for (k, slot) in previous.iter_mut().enumerate() {
if bound(k) {
last = k;
}
*slot = last;
}
let mut next = vec![len - 1; len];
let mut first = len - 1;
for (k, slot) in next.iter_mut().enumerate().rev() {
if bound(k) {
first = k;
}
*slot = first;
}
let at = |k: usize| pos.get(k).map_or(0.0, |c| c[1]);
// The share of the anchor at `k` in the walk, between an anchor that stays at `end` and a
// focal point at `focal` along the walk.
let smooth = |k: usize, end: f64, focal: f64| {
let span = (focal - end).abs();
let Some(&[c_in, c, c_out]) = pos.get(k).filter(|_| span > 0.0 && span.is_finite()) else { return [0.0; 3] };
let along = |c: f64| (c - end).abs() / span;
let u = along(c);
let w = u * u * (3.0 - 2.0 * u);
let slope = 6.0 * u * (1.0 - u);
[w + slope * (along(c_in) - u), w, w + slope * (along(c_out) - u)]
};
for (k, &i) in order.iter().enumerate().take(n) {
let share = match role(i) {
Stretch::Fixed => [0.0; 3],
Stretch::Focal => [1.0; 3],
Stretch::Selected => {
let (kp, kn) = (previous.get(k).copied().unwrap_or(k), next.get(k).copied().unwrap_or(k));
match (role(order.get(kp).copied().unwrap_or(i)), role(order.get(kn).copied().unwrap_or(i))) {
(Stretch::Focal, Stretch::Focal) => [1.0; 3],
(Stretch::Fixed, Stretch::Focal) => smooth(k, at(kp), at(kn)),
(Stretch::Focal, Stretch::Fixed) => smooth(k, at(kn), at(kp)),
_ => [0.0; 3],
}
}
let end = if i < grabbed { 0.0 } else { length };
let span = (at - end).abs();
if i == 0 || i == last || span <= 0.0 || !span.is_finite() {
return [0.0; 3];
}
let along = |c: f64| (c - end).abs() / span;
let u = along(c);
let w = u * u * (3.0 - 2.0 * u);
let slope = 6.0 * u * (1.0 - u);
let shares = [w + slope * (along(c_in) - u), w, w + slope * (along(c_out) - u)];
// A coordinate that isn't finite moves nothing.
if shares.iter().all(|s| s.is_finite()) { shares } else { [0.0; 3] }
})
.collect()
};
// A coordinate that isn't finite moves nothing.
if let Some(s) = shares.get_mut(i)
&& share.iter().all(|s| s.is_finite())
{
*s = share;
}
}
shares
}
/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors and
/// selected segments after it on that subpath one higher, so the selection keeps the same points.
/// A selected segment that the new anchor splits stays selected as its two halves, and the new
/// anchor joins its ends in the anchors that move with it.
fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) {
if let Some(set) = sel.anchors.get_mut(&id) {
// A selected anchor index can name no anchor (`select.anchors` takes any index), so the
// renumbering saturates instead of overflowing.
*set = set.iter().map(|&(s, a)| if s == si && a >= added { (s, a.saturating_add(1)) } else { (s, a) }).collect();
}
let split = added.checked_sub(1);
if sel.segments.get(&id).is_some_and(|set| split.is_some_and(|g| set.contains(&(si, g)))) {
sel.anchors.entry(id).or_default().insert((si, added));
}
if let Some(set) = sel.segments.get_mut(&id) {
*set = set
.iter()
.flat_map(|&(s, g)| match (s == si, Some(g) == split) {
(true, true) => vec![(s, g), (s, g.saturating_add(1))],
(true, false) if g >= added => vec![(s, g.saturating_add(1))],
_ => vec![(s, g)],
})
.collect();
}
}
fn reshape(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1476,39 +1572,86 @@ fn reshape(s: &mut Session, p: &Value) -> Result<Value> {
Some((i, dist)) if dist <= tol => Some(i),
_ => None,
};
// A drag of no length on an anchor moves nothing, so it is not an edit.
if delta == Vec2::ZERO {
// The other focal points the Reshape tool highlighted on this path.
let mut focal: BTreeSet<(usize, usize)> = match p.get("focal") {
None | Some(Value::Null) => BTreeSet::new(),
Some(v) if v.is_array() => super::select::checked_refs(Some(v), "path.reshape")?.into_iter().collect(),
Some(_) => return Err(bad("path.reshape", "`focal` must be an array of [subpath, anchor] pairs")),
};
// An empty `focal` chooses the focal-point rule too.
if radius.is_some() && !matches!(p.get("focal"), None | Some(Value::Null)) {
return Err(bad("path.reshape", "`focal` and `radius` cannot be used together"));
}
// A step that names neither `focal` nor `radius` (as the Reshape tool recorded one before it
// had focal points) keeps that earlier rule: the selection does not matter, an open path
// stretches from the grabbed point to its two ends, and a closed one follows with a falloff
// over the default radius.
let earlier = radius.is_none() && matches!(p.get("focal"), None | Some(Value::Null));
{
let st = s.doc()?;
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
let path = node.path_data().ok_or_else(|| EngineError::Other(format!("object {id} is not a path")))?;
let (si, ..) = path.nearest(at).ok_or_else(|| EngineError::Other("empty path".into()))?;
if path.subpaths.get(si).is_some_and(|sp| near(sp).is_some()) {
return ok();
if let Some((si, ai)) = focal.iter().copied().find(|&(si, ai)| path.subpaths.get(si).is_none_or(|sp| ai >= sp.anchors.len())) {
return Err(bad("path.reshape", format!("`focal` names [{si}, {ai}], which is not an anchor of the path")));
}
// A drag of no length on an anchor moves nothing, so it is not an edit.
if delta == Vec2::ZERO {
let (si, ..) = path.nearest(at).ok_or_else(|| EngineError::Other("empty path".into()))?;
if path.subpaths.get(si).is_some_and(|sp| near(sp).is_some()) {
return ok();
}
}
}
s.edit("Reshape", |d, _| {
s.edit("Reshape", |d, sel| {
let path = path_mut(d, id)?;
let (si, seg, t, _, _) = path.nearest(at).ok_or_else(|| EngineError::Other("empty path".into()))?;
let sp = &mut path.subpaths[si];
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("empty path".into()))?;
let grabbed = match near(sp) {
Some(i) => i,
None => sp.insert_anchor(seg, t),
None => {
let added = sp.insert_anchor(seg, t);
focal = focal.iter().map(|&(s, a)| if s == si && a >= added { (s, a.saturating_add(1)) } else { (s, a) }).collect();
renumber_after_insert(sel, id, si, added);
// On a partly selected path the new anchor is selected too.
if let Some(set) = sel.anchors.get_mut(&id) {
set.insert((si, added));
}
added
}
};
let closed = sp.closed;
if radius.is_none() && !closed {
let weights = stretch_weights(&sp.anchors, grabbed);
for (a, [w_in, w, w_out]) in sp.anchors.iter_mut().zip(weights) {
a.p += delta * w;
a.h_in += delta * w_in;
a.h_out += delta * w_out;
let earlier_closed = earlier && sp.closed;
if radius.is_none() && !earlier_closed {
focal.insert((si, grabbed));
// Anchors that are not direct-selected stay; a path selected whole, or not selected,
// has every anchor selected, and so does every path under the earlier rule.
let selected = sel.anchors.get(&id).filter(|_| !earlier);
for (k, sp) in path.subpaths.iter_mut().enumerate() {
if focal.range((k, 0)..=(k, usize::MAX)).next().is_none() {
continue;
}
let roles: Vec<Stretch> = (0..sp.anchors.len())
.map(|i| match (focal.contains(&(k, i)), selected.is_none_or(|set| set.contains(&(k, i)))) {
(true, _) => Stretch::Focal,
(false, true) => Stretch::Selected,
(false, false) => Stretch::Fixed,
})
.collect();
let weights = stretch_weights(&sp.anchors, sp.closed, &roles);
for (a, [w_in, w, w_out]) in sp.anchors.iter_mut().zip(weights) {
a.p += delta * w;
a.h_in += delta * w_in;
a.h_out += delta * w_out;
}
}
return Ok(());
}
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("empty path".into()))?;
let closed = sp.closed;
// Each anchor's distance along the path from the grabbed one, the shorter way round a
// closed path: the lengths are measured once, as a path can have many anchors.
let pos = sp.anchor_arc_positions();
let total = pos.last().copied().unwrap_or(0.0);
// The default reach is the subpath's size, as before, now measured along it.
// The default reach of the earlier rule: half the diagonal of the subpath's bounding box.
let r = radius.unwrap_or_else(|| {
let mut bp = vectorcraft_geom::BezPath::new();
sp.to_bezpath_into(&mut bp);
@@ -1548,6 +1691,7 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Other("no such segment".into()));
}
let idx = sp.insert_anchor(seg, t);
renumber_after_insert(sel, id, si, idx);
// A path that wasn't selected becomes the selection, its new anchor direct-selected, so
// the point added shows and can be edited at once (#4237).
if !sel.contains(id) {
+10 -6
View File
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Outline Stroke",
["Object", "Path"],
None,
"{} replace stroked paths with filled outlines; a dimension whose lines are outlined, or selected with the art it measures when that art is outlined, becomes a plain group of its art → {ids}",
"{} replace stroked paths with filled outlines; a dimension whose lines are outlined becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines stay as they are, and if the outlined art no longer fits its link it stays where it was, no longer linked → {ids}",
has_selection,
outline_stroke
),
@@ -1074,7 +1074,11 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
let roots = selected_roots(s)?;
let ids = s.edit("Outline Stroke", |d, sel| {
let before = d.clone();
let mut ended = super::dimension::end_links(d, &roots);
// A dimension selected with the art it measures keeps its own lines: it is out of the
// document while the art is outlined.
let lifted = super::dimension::lift(d, &roots);
let kept = !lifted.is_empty();
let ended = super::dimension::end_links(d, &roots);
let brushes = vectorcraft_brush::library(d);
let mut new_sel = vec![];
let mut changed = 0;
@@ -1083,10 +1087,10 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
new_sel.push(id);
changed += n;
}
// A dimension whose source was outlined stays plain: its link no longer fits that art.
ended.retain(|e| e.source_kept(&before, d));
super::dimension::restore_unchanged(d, ended);
if changed == 0 {
super::dimension::put_back(d, lifted);
// A dimension whose source was outlined stays where it was, no longer linked.
super::dimension::restore_unchanged(&before, d, ended);
if changed == 0 || (kept && d.layers == before.layers) {
return Err(EngineError::Other("Outline Stroke: no stroked paths selected".into()));
}
sel.set(new_sel.iter().copied());
@@ -152,6 +152,7 @@ pub(super) const ALLOWED: &[&str] = &[
"edit.findNext",
"edit.findReplace",
"effect.apply",
"effect.deferredStatus",
"effect.duplicate",
"effect.expandAppearance",
"effect.list",
@@ -662,11 +663,13 @@ pub(super) const ALLOWED: &[&str] = &[
];
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
/// preferences, a tool's options, a drag's state or the font names the whole app knows.
/// preferences, a tool's options, a drag's state or the font names the whole app knows, or run
/// plug-ins again.
pub(super) const DENIED: &[&str] = &[
"addon.cleanup.splitText",
"addon.pathtools.movePointsTogether",
"addon.pen.nextSegment",
"effect.refreshDeferred",
"graphicStyle.setOptions",
"object.blend.options",
"object.liquify",
+1 -1
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
has_doc,
setup
),
+4 -2
View File
@@ -76,9 +76,11 @@ fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: b
let mut images = vec![];
for (_, r) in regions {
let area = outset(r, bleed);
// At most MAX_PIXELS, and 65535 pixels a side.
// At most MAX_PIXELS, and no side longer than the renderer draws (rounded up to whole
// pixels below).
let side = area.width().max(area.height()).max(1.0);
let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(65_535.0 / side);
let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0;
let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(longest / side);
if !(scale.is_finite() && scale > 0.0) {
continue;
}
+62 -7
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error)}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, fuelLeft, fuelUsed, hostCalls and the fields above",
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text) and $.includePath the #includepath list; alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine and #engine are refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log en Line truncated
always,
run
),
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Script Console",
[],
None,
"{} the Script Console's lines, oldest first: each run's start, its $.write and $.writeln output, its vc.log entries, its uncaught error as name:line:column: message, its end and a report of its time, host calls and slowest commands; a session keeps at most 2048 lines and 1 MiB of text, dropping the oldest, a line at most 4096 bytes and a script's name in its lines at most 256 bytes, each cut with … (VectorCraft's own limits); line feeds, carriage returns and the two together break lines, other control characters show as their Unicode Control Pictures → {lines: [{run: the run's number in the session, name, kind: start|output|log|error|end|report, text}], droppedLines, truncatedLines} (an end line's text is ended: finished|error|fuel|hostLimit|limit|stopped|internal)",
"{} the Script Console's lines, oldest first: each run's start, its $.write and $.writeln output, its vc.log entries, its uncaught error as name:line:column: message (name: file:line:column: message when it is in another file), its end and a report of its time, host calls and slowest commands; a session keeps at most 2048 lines and 1 MiB of text, dropping the oldest, a line at most 4096 bytes and a script's name in its lines at most 256 bytes, each cut with … (VectorCraft's own limits); line feeds, carriage returns and the two together break lines, other control characters show as their Unicode Control Pictures → {lines: [{run: the run's number in the session, name, kind: start|output|log|error|end|report, text}], droppedLines, truncatedLines} (an end line's text is ended: finished|error|fuel|hostLimit|limit|stopped|internal)",
always,
console_lines
),
@@ -63,6 +63,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
console_clear
),
cmd!(
query "script.listInstalled",
"List Installed Scripts",
[],
None,
"{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
always,
list_installed
),
cmd!(
query "script.check",
"Check Script",
@@ -122,10 +131,9 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
if serde_json::to_vec(&args).map_or(true, |b| b.len() > script::MAX_ARGS_BYTES) {
return Err(param("`args` is larger than 1 MiB"));
}
match p.get("answers") {
None => {}
Some(Value::Object(o)) if o.is_empty() => {}
Some(_) => return Err(param("`answers` must be an empty object: scripts cannot ask questions yet")),
let answers = script::dialogs::parse_answers(p.get("answers")).map_err(param)?;
if s.script_frames && !answers.is_empty() {
return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"));
}
let fuel = max_fuel(p)?;
let text = match (path, source) {
@@ -153,7 +161,8 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
_ => return Err(param("give exactly one of `path` and `source`")),
};
let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string());
s.script_start(script::Request { name: name.clone(), source: text, args, fuel })?;
let request = script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), source: text, args, fuel, answers };
let name = s.script_start(request)?;
if s.script_frames {
return Ok(json!({"running": true, "name": name}));
}
@@ -172,6 +181,52 @@ fn console_clear(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({"cleared": s.clear_script_console()}))
}
/// The error for a script that File › Scripts listed and that [`script::folder::read`] no longer
/// reads.
pub const NOT_LISTED: &str = "the script is no longer in the Scripts folder";
impl Session {
/// Have File › Scripts and `script.listInstalled` list the scripts of the folder `dir`. The
/// folder is only read, and never made.
pub fn attach_scripts_dir(&mut self, dir: std::path::PathBuf) {
self.scripts_dir = Some(dir);
}
/// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders.
pub fn scripts_dir(&self) -> Option<&std::path::Path> {
self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
}
/// The text of the script at `path`, which a listing of the Scripts folder gave
/// ([`script::folder::read`]), checked as `script.run` checks a file's.
pub fn installed_script(&self, path: &str) -> Result<String> {
let root = self.scripts_dir().ok_or_else(|| EngineError::Other(NOT_LISTED.to_string()))?;
crate::file_access::check_read(path).map_err(EngineError::Other)?;
// One byte more than a script may have shows that the file is too large.
let bytes = script::folder::read(root, std::path::Path::new(path), script::MAX_SOURCE_BYTES + 1)
.ok_or_else(|| EngineError::Other(NOT_LISTED.to_string()))?;
if bytes.len() > script::MAX_SOURCE_BYTES {
return Err(EngineError::Other(TOO_LARGE.to_string()));
}
script_text(&bytes)
}
}
fn list_installed(s: &mut Session, _: &Value) -> Result<Value> {
let Some(root) = s.scripts_dir() else {
return Ok(json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}));
};
let folder = root.to_string_lossy();
crate::file_access::check_read(&folder).map_err(EngineError::Other)?;
let listing = script::folder::list(root);
let scripts: Vec<Value> = listing
.scripts()
.into_iter()
.map(|(folders, label, path)| json!({"path": path.to_string_lossy(), "label": label, "folders": folders}))
.collect();
Ok(json!({"folder": folder, "scripts": scripts, "truncated": listing.truncated, "unreadable": listing.unreadable}))
}
/// The folder a script is in, which its included files are read from.
struct Folder {
dir: std::path::PathBuf,
+13 -1
View File
@@ -252,6 +252,18 @@ pub(crate) fn selectable_ids(d: &Document, iso: Option<NodeId>) -> BTreeSet<Node
/// Whether [`walk_selectable`] visits `id`, read from the objects that hold it instead of a walk of
/// the document. `locks` is the document's [`Document::locked_artboards`].
pub(crate) fn is_selectable(d: &Document, iso: Option<NodeId>, locks: &LockedArtboards, id: NodeId) -> bool {
is_selectable_within(d, iso, Some(locks), id)
}
/// [`is_selectable`] without the locked artboards, for an edit's new selection: after the edit,
/// the session takes the art on a locked artboard out of the selection, except the new art the
/// edit made.
pub(crate) fn is_selectable_on_any_artboard(d: &Document, iso: Option<NodeId>, id: NodeId) -> bool {
is_selectable_within(d, iso, None, id)
}
/// [`is_selectable`], leaving out the locked artboards when `locks` is `None`.
fn is_selectable_within(d: &Document, iso: Option<NodeId>, locks: Option<&LockedArtboards>, id: NodeId) -> bool {
let Some(a) = d.ancestry(id) else { return false };
if !a.iter().all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template())) {
return false;
@@ -262,7 +274,7 @@ pub(crate) fn is_selectable(d: &Document, iso: Option<NodeId>, locks: &LockedArt
None => {
// The object Select All takes: the outermost one that is not a layer.
let top = a.iter().filter_map(|i| d.node(*i)).find(|n| !n.is_layer());
top.is_some_and(|t| locks.is_empty() || !locks.holds(t))
top.is_some_and(|t| locks.is_none_or(|l| l.is_empty() || !l.holds(t)))
}
}
}
+63
View File
@@ -158,6 +158,7 @@ pub const BUILTIN: &[BuiltinSymbolLibrary] = &[
BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes },
BuiltinSymbolLibrary { id: "ui-frames", name: "UI Frames", make: ui_frames },
BuiltinSymbolLibrary { id: "map-markers", name: "Map Markers", make: map_markers },
BuiltinSymbolLibrary { id: "inventory-icons", name: "Inventory Icons", make: inventory_icons },
];
/// Built-in library `id`, made once.
@@ -249,6 +250,68 @@ fn map_markers() -> SymbolLibrary {
SymbolLibrary { name: "Map Markers".into(), doc }
}
/// Inventory Icons: sword, shield, potion, key and gem for loot/RPG art (original, no 9-slice).
fn inventory_icons() -> SymbolLibrary {
let c = Point::ZERO;
let sword = [
(0.0, -22.0),
(3.0, -10.0),
(3.0, 6.0),
(8.0, 8.0),
(8.0, 12.0),
(3.0, 12.0),
(3.0, 20.0),
(-3.0, 20.0),
(-3.0, 12.0),
(-8.0, 12.0),
(-8.0, 8.0),
(-3.0, 6.0),
(-3.0, -10.0),
];
let shield = [(0.0, -20.0), (16.0, -12.0), (14.0, 8.0), (0.0, 20.0), (-14.0, 8.0), (-16.0, -12.0)];
let potion =
[(-4.0, -20.0), (4.0, -20.0), (4.0, -12.0), (10.0, -6.0), (12.0, 6.0), (8.0, 18.0), (-8.0, 18.0), (-12.0, 6.0), (-10.0, -6.0), (-4.0, -12.0)];
let key = [
(-4.0, -18.0),
(4.0, -18.0),
(6.0, -14.0),
(6.0, -8.0),
(4.0, -6.0),
(4.0, 16.0),
(8.0, 16.0),
(8.0, 20.0),
(-2.0, 20.0),
(-2.0, 12.0),
(0.0, 12.0),
(0.0, -6.0),
(-4.0, -8.0),
(-6.0, -14.0),
];
let sword: Vec<Point> = sword.iter().map(|&(x, y)| Point::new(x, y)).collect();
let shield: Vec<Point> = shield.iter().map(|&(x, y)| Point::new(x, y)).collect();
let potion: Vec<Point> = potion.iter().map(|&(x, y)| Point::new(x, y)).collect();
let key: Vec<Point> = key.iter().map(|&(x, y)| Point::new(x, y)).collect();
let icons = [
("Sword", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&sword, true)), "#95a5a6"),
("Shield", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&shield, true)), "#3498db"),
("Potion", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&potion, true)), "#9b59b6"),
("Key", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&key, true)), "#f1c40f"),
("Gem", shapes::polygon(c, 16.0, 6, 0.0), "#1abc9c"),
];
let mut doc = Document::new(100.0, 100.0);
for (name, path, hex) in icons {
let fill = Color::from_hex(hex).unwrap_or(Color::BLACK);
let edge = fill.lerp(&Color::BLACK, 0.35);
let id = doc.alloc_id();
let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.25));
let Ok((art, size, _)) = normalize(art) else { continue };
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
set_natural_size(&mut doc, name, Some(size));
}
doc.title = "Inventory Icons".into();
SymbolLibrary { name: "Inventory Icons".into(), doc }
}
/// An instance of symbol `name` (what the resource gathering follows).
fn instance(name: &str) -> Node {
Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })
+31 -11
View File
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, 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_range_style
),
@@ -1087,12 +1087,16 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
}
/// The em a laid-out glyph's kerning and tracking are measured in, in text space: the size it
/// was shaped at (superscript, small caps and Shrink Text to Fit included).
/// was shaped at (superscript, small caps and Shrink Text to Fit included), in horizontal type
/// as its Horizontal Scale draws it ([`vectorcraft_text::spacing_scale`]).
fn glyph_em(db: &vectorcraft_text::FontDb, t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option<f64> {
let face = db.face_by_id(g.font_id)?;
let h_scale = edit::slice_runs(&t.runs, g.byte, g.byte + g.len).first()?.style.h_scale / 100.0;
let runs = edit::slice_runs(&t.runs, g.byte, g.byte + g.len);
let style = &runs.first()?.style;
// The glyph's own scale takes in the Horizontal Scale.
let h_scale = style.h_scale / 100.0;
let [a, b, ..] = g.xf.as_coeffs();
Some(a.hypot(b) * face.units_per_em() / h_scale).filter(|em| em.is_finite() && *em > 0.0)
Some(a.hypot(b) * face.units_per_em() / h_scale * vectorcraft_text::spacing_scale(style, t.vertical)).filter(|em| em.is_finite() && *em > 0.0)
}
/// The current pair correction in thousandths of an em, including an automatic correction.
@@ -1276,19 +1280,25 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> {
// out (overflowing text) is shaped alone in its writing direction, with the rest of its grapheme
// in the grapheme's own styles.
let plain = t.plain_text();
let unchosen = holder.as_ref().filter(|_| !styled).and_then(|_| {
let mut probe = t.clone();
edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None);
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe);
own_glyph(&plain, &lay, ch, &bytes, &face).unwrap_or_else(|| shaped_alone(&probe, ch, &bytes, &face).0)
});
let mut probe = t.clone();
edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None);
let probe_lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe);
let unchosen = holder
.as_ref()
.filter(|_| !styled)
.and_then(|_| own_glyph(&plain, &probe_lay, ch, &bytes, &face).unwrap_or_else(|| shaped_alone(&probe, ch, &bytes, &face).0));
let substituted = unchosen.is_some_and(|g| g != default);
let choice = match gid.filter(|g| *g != default || substituted) {
None => None,
Some(g) if g == default || face.alternates(ch).iter().any(|a| a.gid == g) => Some(face.choice(ch, g)),
Some(g) => return Err(bad(C, format!("glyph {g} is not an alternate of {ch} in {} {}", face.family, face.style))),
};
let drawn = choice.as_ref().map_or(unchosen.unwrap_or(default), |c| c.gid);
// Without a choice, the glyph drawn in whatever face draws the character, as
// `text.glyphAlternates` reports it (a fallback face's glyph, the capital of All Caps).
let drawn = match &choice {
Some(c) => c.gid,
None => drawn_glyph(&plain, &probe_lay, ch, &bytes, &face).or_else(|| shaped_alone(&probe, ch, &bytes, &face).1).unwrap_or(default),
};
// The run holding the character. The request changes nothing when the choice is the one the
// character's run holds and that run holds the character alone; otherwise the edit splits the
// run, so that the following text does not take the character into a ligature.
@@ -1311,6 +1321,16 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> {
}
}
if held == choice && (choice.is_none() || alone) {
// The text is left as it is, so the glyph is the one the unchanged text draws. The probe
// splits a run that holds an earlier character's choice, and the split can break a ligature
// that takes in this character.
let drawn = match &choice {
None if probe.runs != t.runs => {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
drawn_glyph(&plain, &lay, ch, &bytes, &face).or_else(|| shaped_alone(&t, ch, &bytes, &face).1).unwrap_or(default)
}
_ => drawn,
};
return Ok(json!({"id": id.0, "start": bytes.start, "end": bytes.end, "gid": drawn}));
}
s.edit("Glyphs", |d, _| {
+4 -1
View File
@@ -596,6 +596,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
if texts.is_empty() {
return Err(EngineError::Other("Create Outlines: select text objects".into()));
}
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();
let mut out = vec![];
@@ -691,7 +692,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
new_sel.push(gid);
}
}
super::dimension::restore_unchanged(d, ended);
if let Some(before) = &before {
super::dimension::restore_unchanged(before, d, ended);
}
// Outlined frames of threaded text leave their threads with the text they show.
super::threads::leave_threads(d, &threaded);
sel.set(new_sel);
+4
View File
@@ -110,6 +110,9 @@ pub struct DocState {
/// paths the document links to are looked at within them later too, when the Links panel
/// asks about a link outside any caller's scope.
pub opened_by: Option<Arc<file_access::AutomationRoots>>,
/// The live-effect plug-in stages deferred while the document is drawn on screen, and the time
/// budget of its first view ([`vectorcraft_plugins::deferred`]). Not saved.
pub plugin_effects: vectorcraft_plugins::deferred::Deferrals,
/// What [`DocState::any_empty_artboards`] last measured. Not saved.
empty_artboards: std::cell::RefCell<EmptyArtboards>,
/// What [`DocState::any_art_to_fit`] last measured. Not saved.
@@ -326,6 +329,7 @@ impl DocState {
last_perspective: None,
opened_by: file_access::current(),
empty_artboards: Default::default(),
plugin_effects: Default::default(),
art_to_fit: Default::default(),
}
}
+85
View File
@@ -23,6 +23,9 @@
//! A path is checked, then opened: a process that can change the folders in between (swapping in
//! a link) can still win that race. The roots keep an agent to the files it was given; they don't
//! guard against other programs on the computer.
//!
//! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`)
//! are read from, inside the roots.
use std::cell::RefCell;
use std::ffi::OsString;
@@ -347,6 +350,88 @@ fn windows_name_refusal(path: &str) -> Option<&'static str> {
})
}
/// The folders a running script's own files are read from: the files its `#include` lines name and
/// the files it passes to `$.evalFile` (`Scope::Script`'s reads). VectorCraft's own rules: a script
/// run from a file may read inside that file's folder and the folders below it, and a script given as
/// text may read none. A path is refused when it has a `..` component, a Windows device name or
/// stream, or names a computer on the network, or when it leads (through its links, junctions
/// included) out of every granted folder. The automation roots ([`check_read`]) apply as well.
///
/// The file opened is the path with its links followed, and after reading, the path is followed
/// again and must still lead to the same place: a process that changes the folders twice in between
/// can still win that race.
#[derive(Clone, Debug, Default)]
pub(crate) struct ScriptScope {
/// The granted folders, made absolute with their links followed.
roots: Vec<PathBuf>,
}
/// Why a script's file was not read.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ScriptRead {
/// There is no such file.
Missing,
/// The scope does not let the script read it.
Refused,
/// The file has more than the bytes asked for.
TooLarge,
/// The file system gave this error.
Failed(String),
}
impl ScriptScope {
/// The scope of a script run from a file in folder `dir`: that folder.
pub(crate) fn of_folder(dir: &Path) -> Self {
Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() }
}
/// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or
/// stream, or a computer on the network?
fn refused_by_name(path: &Path) -> bool {
let text = path.to_string_lossy();
text.contains('\0')
|| path.components().any(|c| c == Component::ParentDir)
|| (cfg!(windows) && (windows_name_refusal(&text).is_some() || network_path(&text)))
}
/// The real path of the file at `path` and its first `max` bytes, at most.
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
use std::io::Read;
if self.roots.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
return Err(ScriptRead::Refused);
}
let real = match std::fs::canonicalize(path) {
Ok(real) => real,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
// A link whose target is missing is there all the same: it is not followed.
return Err(if std::fs::symlink_metadata(path).is_ok() { ScriptRead::Refused } else { ScriptRead::Missing });
}
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
};
if !self.roots.iter().any(|r| inside(&real, r)) {
return Err(ScriptRead::Refused);
}
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?;
if !meta.is_file() {
return Err(ScriptRead::Missing);
}
if meta.len() > max as u64 {
return Err(ScriptRead::TooLarge);
}
let mut bytes = Vec::new();
// One byte more than asked for shows a file that grew while it was read.
file.take(max as u64 + 1).read_to_end(&mut bytes).map_err(|e| ScriptRead::Failed(e.to_string()))?;
if bytes.len() > max {
return Err(ScriptRead::TooLarge);
}
if std::fs::canonicalize(path).ok().as_ref() != Some(&real) {
return Err(ScriptRead::Refused);
}
Ok((real, bytes))
}
}
#[cfg(test)]
mod tests {
use super::*;
+5 -1
View File
@@ -133,7 +133,8 @@ pub fn document(s: &Session) -> Value {
document_opts(s, SummaryOpts::default())
}
/// An artboard's name and rectangle, its background color (`#rrggbb`) when it has one,
/// An artboard's name and rectangle, its background color (`#rrggbb`) when it has one, its guide
/// label (a layer color's name or `#rrggbb`) when it has one,
/// `locked: true` when it is locked, `showCenterMark: true`, `showCrossHairs: true` and
/// `showVideoSafeAreas: true` when it shows them, and `videoRulerPixelAspectRatio` when it isn't 1.
fn artboard_summary(a: &vectorcraft_doc::Artboard) -> Value {
@@ -141,6 +142,9 @@ fn artboard_summary(a: &vectorcraft_doc::Artboard) -> Value {
if let Some(c) = a.color {
v["color"] = json!(c.to_hex());
}
if let Some(c) = a.guide_label {
v["guideLabel"] = json!(c.label_text());
}
for (key, on) in [
("locked", a.locked),
("showCenterMark", a.show_center_mark),
+3
View File
@@ -168,6 +168,9 @@ pub struct Session {
/// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process
/// ([`Session::attach_plugin_store`]).
plugin_dir: Option<std::path::PathBuf>,
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
/// ([`Session::attach_scripts_dir`]).
scripts_dir: Option<std::path::PathBuf>,
/// The plug-in ids whose grant in the plug-in store should be gone but could not be removed:
/// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful
/// [`Session::store_grant`] for the id takes it out.
+1 -1
View File
@@ -207,7 +207,7 @@ impl Console {
/// `c` as the console shows it: a control character as its Control Picture, a line or paragraph
/// separator as U+2424, anything else as it is.
fn shown(c: char) -> char {
pub(crate) fn shown(c: char) -> char {
match c {
'\u{0}'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'),
'\u{7f}' => '\u{2421}',
+364
View File
@@ -0,0 +1,364 @@
//! `alert(message[, title, errorIcon])`, `confirm(message[, noAsDflt, title])` and
//! `prompt(message, preset[, title])`: the dialogs a script opens while it runs.
//!
//! A message and a preset arrive as the string `String(value)` gives, a title the same way unless
//! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the
//! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and
//! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel.
//!
//! In the app the run waits at the call for the person's answer, and spends no fuel while it
//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with
//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no
//! answer left, or with the next answer for another kind of dialog, ends the run. The report's
//! `dialogs` lists each dialog and its answer.
//!
//! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`],
//! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and
//! [`MAX_RECORD_BYTES`].
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError};
use super::{Host, console};
/// The most bytes (UTF-8) of a dialog's message.
pub const MAX_MESSAGE_BYTES: usize = 16 << 10;
/// The most bytes (UTF-8) of a dialog's title.
pub const MAX_TITLE_BYTES: usize = 256;
/// The most bytes (UTF-8) of a prompt's preset and of the text it returns.
pub const MAX_PROMPT_BYTES: usize = 16 << 10;
/// The most answers `script.run` takes.
pub const MAX_ANSWERS: usize = 10_000;
/// The most bytes of `answers`, as JSON.
pub const MAX_ANSWERS_BYTES: usize = 1 << 20;
/// The most dialogs a report lists.
pub const MAX_RECORDS: usize = 10_000;
/// The most bytes of the dialogs a report lists, as JSON.
pub const MAX_RECORD_BYTES: usize = 1 << 20;
/// A dialog's title when the script gives none, in English; the app translates it when it shows it.
pub const DEFAULT_TITLE: &str = "Script Alert";
/// Which dialog a script opened.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DialogKind {
Alert,
Confirm,
Prompt,
}
impl DialogKind {
/// The function's name, which is also the `kind` of an answer and of a report's dialog.
pub fn id(self) -> &'static str {
match self {
Self::Alert => "alert",
Self::Confirm => "confirm",
Self::Prompt => "prompt",
}
}
}
/// A dialog a script opened, which waits for its answer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScriptDialog {
pub kind: DialogKind,
pub message: String,
/// `None`: the script gave no title ([`DEFAULT_TITLE`]).
pub title: Option<String>,
/// `alert`: show the error icon.
pub error_icon: bool,
/// `confirm`: No is the default button.
pub no_as_default: bool,
/// `prompt`: the text its field starts with.
pub preset: String,
}
/// The answer to a [`ScriptDialog`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DialogAnswer {
/// OK, for `alert`.
Ok,
/// Yes (`true`) or No, for `confirm`.
Confirm(bool),
/// OK with the field's text, or Cancel (`None`), for `prompt`.
Prompt(Option<String>),
}
impl DialogAnswer {
pub fn kind(&self) -> DialogKind {
match self {
Self::Ok => DialogKind::Alert,
Self::Confirm(_) => DialogKind::Confirm,
Self::Prompt(_) => DialogKind::Prompt,
}
}
/// What the function returns.
fn data(&self) -> Data {
match self {
Self::Ok => Data::Undefined,
Self::Confirm(b) => Data::Bool(*b),
Self::Prompt(Some(t)) => Data::String(t.clone()),
Self::Prompt(None) => Data::Null,
}
}
/// The answer as a report gives it: `"ok"`, a boolean, a string or `null`.
fn json(&self) -> Value {
match self {
Self::Ok => json!("ok"),
Self::Confirm(b) => json!(b),
Self::Prompt(t) => json!(t),
}
}
}
/// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together
/// is a line break; every other control character, and with `lines` false every line break too,
/// shows as its Unicode Control Picture, as the Script Console shows it.
pub fn shown_text(text: &str, lines: bool) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\r' if lines => {
chars.next_if_eq(&'\n');
out.push('\n');
}
'\n' if lines => out.push('\n'),
c => out.push(console::shown(c)),
}
}
out
}
/// The longest start of `text` that is at most `max` bytes, cut at a character boundary.
pub fn cut_to(text: &str, max: usize) -> &str {
if text.len() <= max {
return text;
}
let mut end = max;
while !text.is_char_boundary(end) {
end -= 1;
}
text.get(..end).unwrap_or_default()
}
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter
/// took before dialogs existed, is an empty list.
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
let list = match v {
None => return Ok(Vec::new()),
Some(Value::Object(o)) if o.is_empty() => return Ok(Vec::new()),
Some(Value::Array(a)) => a,
Some(_) => return Err("`answers` must be a list of answers".into()),
};
if list.len() > MAX_ANSWERS {
return Err(format!("`answers` has more than {MAX_ANSWERS} answers"));
}
if serde_json::to_vec(list).map_or(true, |b| b.len() > MAX_ANSWERS_BYTES) {
return Err("`answers` is larger than 1 MiB".into());
}
list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect()
}
fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") };
if o.len() != 2 || !o.contains_key("value") {
return Err("must have exactly `kind` and `value`");
}
match (o.get("kind").and_then(Value::as_str), &o["value"]) {
(Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok),
(Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""),
(Some("confirm"), Value::Bool(b)) => Ok(DialogAnswer::Confirm(*b)),
(Some("confirm"), _) => Err("is a confirm's answer, whose `value` must be true or false"),
(Some("prompt"), Value::Null) => Ok(DialogAnswer::Prompt(None)),
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
_ => Err("must have `kind` alert, confirm or prompt"),
}
}
/// The dialogs of one run: the answers left for a run with nobody to ask, the dialog that waits
/// for the person's answer, and the list the report gives.
pub(crate) struct Dialogs {
/// Answers come from the person, not from `answers`.
framed: bool,
/// The realm's [`Realm::wait_flag`].
can_wait: Rc<Cell<bool>>,
answers: RefCell<VecDeque<DialogAnswer>>,
waiting: RefCell<Option<ScriptDialog>>,
/// The error that ended the run when an answer could not reach the script.
failed: RefCell<Option<RunError>>,
records: RefCell<Vec<Value>>,
record_bytes: Cell<usize>,
count: Cell<u64>,
truncated: Cell<bool>,
}
impl Dialogs {
pub(crate) fn new(framed: bool, realm: &Realm, answers: Vec<DialogAnswer>) -> Self {
Self {
framed,
can_wait: realm.wait_flag(),
answers: RefCell::new(answers.into()),
waiting: RefCell::default(),
failed: RefCell::default(),
records: RefCell::default(),
record_bytes: Cell::new(0),
count: Cell::new(0),
truncated: Cell::new(false),
}
}
/// The dialog that waits for its answer.
pub(crate) fn waiting(&self) -> Option<ScriptDialog> {
self.waiting.borrow().clone()
}
pub(crate) fn is_waiting(&self) -> bool {
self.waiting.borrow().is_some()
}
/// The error that ended the run when its answer could not reach the script.
pub(crate) fn take_failure(&self) -> Option<RunError> {
self.failed.borrow_mut().take()
}
/// How many of `answers` the run did not use.
pub(crate) fn unused(&self) -> usize {
self.answers.borrow().len()
}
/// Gives the waiting dialog `answer`, which must be for its kind and, for a prompt, at most
/// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits.
pub(crate) fn answer(&self, realm: &mut Realm, answer: DialogAnswer) -> bool {
let fits = match &answer {
DialogAnswer::Prompt(Some(t)) => t.len() <= MAX_PROMPT_BYTES,
_ => true,
};
let mut waiting = self.waiting.borrow_mut();
let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false };
self.record(d, answer.json());
*waiting = None;
if let Err(e) = realm.answer(answer.data()) {
*self.failed.borrow_mut() = Some(e);
}
true
}
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`.
pub(crate) fn stopped(&self) {
if let Some(d) = self.waiting.borrow_mut().take() {
self.record(&d, json!("stop"));
}
}
fn record(&self, d: &ScriptDialog, answer: Value) {
self.count.set(self.count.get().saturating_add(1));
let mut r = Map::new();
r.insert("kind".into(), json!(d.kind.id()));
r.insert("message".into(), json!(d.message));
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
match d.kind {
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
};
r.insert("answer".into(), answer);
let r = Value::Object(r);
let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len());
let mut records = self.records.borrow_mut();
if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
self.truncated.set(true);
return;
}
self.record_bytes.set(self.record_bytes.get() + bytes);
records.push(r);
}
/// Adds `dialogs`, `dialogCount` and `dialogsTruncated` to a report.
pub(crate) fn report(&self, report: &mut Map<String, Value>) {
report.insert("dialogs".into(), Value::Array(self.records.borrow().clone()));
report.insert("dialogCount".into(), json!(self.count.get()));
report.insert("dialogsTruncated".into(), json!(self.truncated.get()));
}
}
/// Adds `alert`, `confirm` and `prompt` to the realm.
pub(super) fn install(realm: &mut Realm, host: &Rc<Host>) -> Result<(), RunError> {
use Arg::{Bool, Text, TextOrUndefined};
let call = |kind: DialogKind| -> HostFunction {
let h = host.clone();
Rc::new(move |args| open(&h, kind, &args))
};
realm.define_host_function("alert", vec![Text, TextOrUndefined, Bool], call(DialogKind::Alert))?;
realm.define_host_function("confirm", vec![Text, Bool, TextOrUndefined], call(DialogKind::Confirm))?;
realm.define_host_function("prompt", vec![Text, Text, TextOrUndefined], call(DialogKind::Prompt))
}
fn text(args: &[Data], i: usize) -> Option<String> {
match args.get(i) {
Some(Data::String(s)) => Some(s.clone()),
_ => None,
}
}
fn flag(args: &[Data], i: usize) -> bool {
matches!(args.get(i), Some(Data::Bool(true)))
}
/// A call of `alert`, `confirm` or `prompt`.
fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError> {
let name = kind.id();
host.charge_call(args.iter().map(super::data_size).sum())?;
let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) };
let (title, error_icon, no_as_default, preset) = match kind {
DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()),
DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()),
DialogKind::Prompt => {
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
(text(args, 2), false, false, preset)
}
};
if message.len() > MAX_MESSAGE_BYTES {
return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB")));
}
if title.as_ref().is_some_and(|t| t.len() > MAX_TITLE_BYTES) {
return Err(HostError::Range(format!("{name}: the title is longer than 256 bytes")));
}
if preset.len() > MAX_PROMPT_BYTES {
return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB")));
}
let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset };
let d = &host.dialogs;
if d.framed {
if !d.can_wait.get() {
return Err(HostError::Error(format!(
"{name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code"
)));
}
*d.waiting.borrow_mut() = Some(dialog);
return Err(HostError::Wait);
}
let next = d.answers.borrow_mut().pop_front();
match next {
Some(a) if a.kind() == kind => {
d.record(&dialog, a.json());
Ok(a.data())
}
Some(a) => {
d.record(&dialog, json!("missing"));
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id())))
}
None => {
d.record(&dialog, json!("missing"));
Err(HostError::Abort(format!("{name}: `answers` has no answer left for this dialog")))
}
}
}
+302
View File
@@ -0,0 +1,302 @@
//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a
//! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]).
//!
//! A listing reads names and file types only, never a script's text. It follows no link: a symbolic
//! link or a Windows junction is left out, whether it is a file, a folder or the Scripts folder
//! itself, so a listed script is a plain file in plain folders under the Scripts folder. Names that
//! start with a dot, files and folders Windows marks hidden or system, names that are not Unicode
//! and names longer than [`MAX_NAME_BYTES`] are left out too, and so is a folder with no script in
//! it.
//!
//! The values here are VectorCraft's own limits: [`MAX_ENTRIES`], [`MAX_SCRIPTS`], [`MAX_FOLDERS`],
//! [`MAX_DEPTH`], [`MAX_NAME_BYTES`], [`MAX_LABEL_CHARS`] and [`MAX_SCAN`]. A listing that reaches
//! one of them, or that cannot read a subfolder or an entry of a folder, keeps what it found and
//! says so ([`Listing::truncated`]).
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::time::Duration;
use crate::cmd::scripts::runs;
/// The most folder entries one listing looks at, in the Scripts folder and its subfolders together.
pub const MAX_ENTRIES: usize = 2048;
/// The most scripts one listing holds.
pub const MAX_SCRIPTS: usize = 512;
/// The most subfolders one listing reads.
pub const MAX_FOLDERS: usize = 128;
/// How many levels of subfolders a listing reads below the Scripts folder.
pub const MAX_DEPTH: usize = 4;
/// The longest file or folder name a listing takes, in UTF-8 bytes.
pub const MAX_NAME_BYTES: usize = 255;
/// The most characters of a label; a longer one ends in `…`.
pub const MAX_LABEL_CHARS: usize = 128;
/// How long one listing may take before it stops with what it found.
pub const MAX_SCAN: Duration = Duration::from_millis(250);
/// The limits of one listing.
#[derive(Clone, Copy, Debug)]
pub struct Limits {
pub entries: usize,
pub scripts: usize,
pub folders: usize,
pub depth: usize,
pub time: Duration,
}
impl Default for Limits {
fn default() -> Self {
Limits { entries: MAX_ENTRIES, scripts: MAX_SCRIPTS, folders: MAX_FOLDERS, depth: MAX_DEPTH, time: MAX_SCAN }
}
}
/// One row of a listing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Entry {
/// A script: its label (the file name without its extension) and the file's path as the folder
/// gave it.
Script { label: String, path: PathBuf },
/// A subfolder with at least one script in it or below it: its label (the folder's name) and
/// its rows.
Folder { label: String, entries: Vec<Entry> },
}
/// What a Scripts folder holds.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Listing {
/// The rows of the folder itself, sorted ([`list_with`]).
pub entries: Vec<Entry>,
/// Some scripts may be missing: a limit was reached or a subfolder could not be read.
pub truncated: bool,
/// The folder is there and could not be read, or is a link.
pub unreadable: bool,
}
impl Listing {
/// Every script with the labels of the folders it is in, in menu order.
pub fn scripts(&self) -> Vec<(Vec<&str>, &str, &Path)> {
fn walk<'a>(entries: &'a [Entry], folders: &mut Vec<&'a str>, out: &mut Vec<(Vec<&'a str>, &'a str, &'a Path)>) {
for e in entries {
match e {
Entry::Script { label, path } => out.push((folders.clone(), label, path)),
Entry::Folder { label, entries } => {
folders.push(label);
walk(entries, folders, out);
folders.pop();
}
}
}
}
let mut out = vec![];
walk(&self.entries, &mut vec![], &mut out);
out
}
}
/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives
/// an empty listing.
pub fn list(root: &Path) -> Listing {
let start = std::time::Instant::now();
list_with(root, &Limits::default(), &mut || start.elapsed())
}
/// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken.
/// Each level is sorted by label without regard to case, then by label, then by file name, with
/// scripts and subfolders mixed. Two rows of one level never share a label unless both were cut:
/// a script whose label another row has shows its whole file name.
pub fn list_with(root: &Path, limits: &Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing {
let unreadable = Listing { unreadable: true, ..Listing::default() };
match std::fs::symlink_metadata(root) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(),
Err(_) => return unreadable,
Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable,
Ok(_) => {}
}
// Paths leave as text (menu params, `script.listInstalled`).
if root.to_str().is_none() {
return unreadable;
}
let mut scan = Scan { limits, elapsed, visited: 0, scripts: 0, folders: 0, truncated: false, stopped: false };
match scan.level(root, 0) {
Some(entries) => Listing { entries, truncated: scan.truncated, unreadable: false },
None => unreadable,
}
}
/// A script or subfolder found in one folder, before the subfolders are read.
struct Found {
name: String,
label: String,
folder: bool,
}
struct Scan<'a> {
limits: &'a Limits,
elapsed: &'a mut dyn FnMut() -> Duration,
visited: usize,
scripts: usize,
folders: usize,
truncated: bool,
/// The entry or time limit was reached: nothing more is read.
stopped: bool,
}
impl Scan<'_> {
/// The rows of the folder `dir`, which is `depth` levels below the Scripts folder; `None` when
/// it cannot be read.
fn level(&mut self, dir: &Path, depth: usize) -> Option<Vec<Entry>> {
let mut found: Vec<Found> = vec![];
for entry in std::fs::read_dir(dir).ok()? {
if self.visited >= self.limits.entries || (self.elapsed)() > self.limits.time {
(self.truncated, self.stopped) = (true, true);
break;
}
self.visited += 1;
let Ok(entry) = entry else {
self.truncated = true;
continue;
};
let Ok(name) = entry.file_name().into_string() else { continue };
let Ok(kind) = entry.file_type() else {
self.truncated = true;
continue;
};
if name.len() > MAX_NAME_BYTES || name.starts_with('.') || kind.is_symlink() || hidden(&entry) {
continue;
}
if kind.is_dir() {
found.push(Found { label: shown(&name), name, folder: true });
} else if kind.is_file() && runs(&name) {
if self.scripts >= self.limits.scripts {
self.truncated = true;
continue;
}
self.scripts += 1;
let stem = name.rsplit_once('.').map_or(name.as_str(), |(stem, _)| stem);
found.push(Found { label: shown(stem), name, folder: false });
}
}
// A script whose label another row of this folder has shows its whole file name, until no
// label is shared. Each pass gives at least one more script its whole file name, and names
// are unique within a folder, so this ends within `found.len()` passes.
loop {
let mut count = std::collections::HashMap::<String, usize>::new();
for f in &found {
*count.entry(f.label.clone()).or_default() += 1;
}
let mut renamed = false;
for f in found.iter_mut().filter(|f| !f.folder) {
if count.get(&f.label).is_some_and(|n| *n > 1) {
let whole = shown(&f.name);
if f.label != whole {
f.label = whole;
renamed = true;
}
}
}
if !renamed {
break;
}
}
found.sort_by(|a, b| (a.label.to_lowercase(), &a.label, &a.name).cmp(&(b.label.to_lowercase(), &b.label, &b.name)));
let mut out = Vec::with_capacity(found.len());
for f in found {
let path = dir.join(&f.name);
if !f.folder {
out.push(Entry::Script { label: f.label, path });
continue;
}
if self.stopped {
continue;
}
if depth >= self.limits.depth || self.folders >= self.limits.folders {
self.truncated = true;
continue;
}
self.folders += 1;
match self.level(&path, depth + 1) {
Some(entries) if entries.is_empty() => {}
Some(entries) => out.push(Entry::Folder { label: f.label, entries }),
None => self.truncated = true,
}
}
Some(out)
}
}
/// `name` as a menu shows it: control and bidirectional formatting characters written as escapes,
/// and at most [`MAX_LABEL_CHARS`] characters.
fn shown(name: &str) -> String {
vectorcraft_plugins::permissions::display_text(name, MAX_LABEL_CHARS)
}
/// Does Windows mark `entry` hidden or system?
fn hidden(entry: &std::fs::DirEntry) -> bool {
entry.metadata().is_ok_and(|m| hidden_meta(&m))
}
/// Does Windows mark the file or folder of `m` hidden or system?
#[cfg(windows)]
fn hidden_meta(m: &std::fs::Metadata) -> bool {
use std::os::windows::fs::MetadataExt as _;
const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4;
m.file_attributes() & HIDDEN_OR_SYSTEM != 0
}
/// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name.
#[cfg(not(windows))]
fn hidden_meta(_: &std::fs::Metadata) -> bool {
false
}
/// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows
/// marks hidden or system, which a listing leaves out.
fn plain(path: &Path, folder: bool, shown: bool) -> bool {
std::fs::symlink_metadata(path)
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
}
/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most
/// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there
/// and none is a link, and neither the file nor a folder below `root` is marked hidden or system?
pub fn holds(root: &Path, path: &Path) -> bool {
let Ok(rest) = path.strip_prefix(root) else { return false };
let names: Option<Vec<&str>> = rest
.components()
.map(|c| match c {
Component::Normal(name) => name.to_str().filter(|n| !n.starts_with('.') && n.len() <= MAX_NAME_BYTES),
_ => None,
})
.collect();
let Some(names) = names else { return false };
let Some((file, folders)) = names.split_last() else { return false };
if folders.len() > MAX_DEPTH || !runs(file) || !plain(root, true, false) {
return false;
}
let mut at = root.to_path_buf();
for folder in folders {
at.push(folder);
if !plain(&at, true, true) {
return false;
}
}
at.push(file);
plain(&at, false, true)
}
/// The first `max` bytes of the script at `path`, or `None` when [`holds`] does not hold for it
/// before the read and again after it, or it cannot be read. The two checks leave no time in which
/// a link stood in for the file or one of its folders for the whole read; a program that swaps one
/// in and back out between a check and the open can still have another file read.
pub fn read(root: &Path, path: &Path, max: usize) -> Option<Vec<u8>> {
if !holds(root, path) {
return None;
}
let file = std::fs::File::open(path).ok()?;
if !file.metadata().is_ok_and(|m| m.is_file()) {
return None;
}
let mut bytes = vec![];
file.take(max as u64).read_to_end(&mut bytes).ok()?;
holds(root, path).then_some(bytes)
}
+442
View File
@@ -0,0 +1,442 @@
//! A script's preprocessor lines, read before it runs, as the public guide lists them
//! (<https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/>):
//! `#include` and `//@include` put the text of another file in place of the line, `#includepath`
//! sets the folders `#include` looks in, `#script` names the run, `#strict on` turns on the checks
//! of `$.strict` (<https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/>:
//! a write to a read-only property is a runtime error, and objects that take no new properties
//! refuse them), and `#target` and `#strict off` are accepted. The same lines are read in a file
//! `$.evalFile` runs.
//!
//! VectorCraft's own rules:
//!
//! - A line counts only at the start of a line (blanks before it), outside strings and comments, as
//! the lexer reads it, and each file must be a whole script on its own.
//! - An included file is looked for beside the file that includes it, then in each `#includepath`
//! folder in turn (a relative one is relative to that same file's folder), then in each folder of
//! the `JSINCLUDE` environment variable. A later `#includepath` replaces the list.
//! - Files are read through the script's [`ScriptScope`]: a refused path ends the run, except a
//! `JSINCLUDE` folder outside the scope, which is passed over.
//! - `#target` takes any value and changes nothing. `#targetengine` and `#engine` are refused as
//! unsupported, and any other `#name` as unknown; `//@name` with another name stays a comment.
//! - The last `#strict on` or `#strict off` of the script and the files it includes sets the checks
//! for the whole run; without one they are off. A write to a property that has only a getter is
//! checked as a read-only one, the objects that take no new properties are those that are not
//! extensible (`Object.preventExtensions`, `Object.seal`, `Object.freeze`), and the rest of ES5
//! strict mode is left to `'use strict'`. Code that `eval` and `Function` compile takes the
//! checks of the code that compiles it; a file `$.evalFile` runs takes its own `#strict` line if
//! it has one, and otherwise the caller's.
//! - A run reads at most [`MAX_DEPTH`] levels of nested files, [`MAX_FILES`] files,
//! [`MAX_TOTAL_BYTES`] of source in all (the script's own included) and 8 MiB a file, and looks up
//! at most [`MAX_PROBES`] paths. A file may be included again once its earlier inclusion has
//! ended; one that includes itself, directly or not, is an error.
//!
//! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of
//! the file it is in.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use vectorcraft_js::{DirectiveName, Options};
use crate::file_access::{ScriptRead, ScriptScope};
/// The most files nested inside each other, below the script.
pub const MAX_DEPTH: usize = 16;
/// The most files a run includes or evaluates.
pub const MAX_FILES: usize = 64;
/// The most bytes of source a run reads, its own included.
pub const MAX_TOTAL_BYTES: usize = 32 << 20;
/// The most paths a run looks up for its files.
pub const MAX_PROBES: usize = 1024;
/// The longest value a preprocessor line may have, in bytes.
const MAX_VALUE_BYTES: usize = 4096;
/// Where the lines of an expanded source came from: file 0 is the file expanded, the others the
/// files it included.
#[derive(Clone, Debug, Default)]
pub(crate) struct SourceMap {
files: Vec<Arc<str>>,
segments: Vec<Segment>,
}
/// From line `out_line` of the expanded source on, the lines are those of file `file` from line
/// `line`; on `out_line` itself the columns are `shift` units further right.
#[derive(Clone, Copy, Debug)]
struct Segment {
out_line: u32,
file: usize,
line: u32,
shift: u32,
}
impl SourceMap {
/// Line `line`, column `column` of the expanded source → the file it is in (its index and name)
/// and the line and column there.
pub(crate) fn locate(&self, line: u32, column: u32) -> (usize, Arc<str>, u32, u32) {
let at = self.segments.partition_point(|s| s.out_line <= line);
let Some(seg) = at.checked_sub(1).and_then(|i| self.segments.get(i)) else {
return (0, self.files.first().cloned().unwrap_or_else(|| Arc::from("")), line, column);
};
let column = if line == seg.out_line { column.saturating_sub(seg.shift).max(1) } else { column };
let name = self.files.get(seg.file).cloned().unwrap_or_else(|| Arc::from(""));
(seg.file, name, seg.line.saturating_add(line - seg.out_line), column)
}
}
/// How a preprocessor failure ends the run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum FailKind {
/// A line that is not a valid preprocessor line, or a file that is not a valid script.
Syntax,
/// A file that is missing, refused or unreadable, or a cycle.
Error,
/// One of the run's limits.
Limit,
}
/// A preprocessor failure, at line `line`, column `column` of the file `file` (index `index` of
/// the expansion's [`SourceMap`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Failure {
pub kind: FailKind,
pub message: String,
pub index: usize,
pub file: Arc<str>,
pub line: u32,
pub column: u32,
}
/// A source with its preprocessor lines read: the text to run, where its lines came from, the
/// name its `#script` line gave, and what its last `#strict` line set (`None` without one).
pub(crate) struct Expanded {
pub source: String,
pub map: SourceMap,
pub name: Option<String>,
pub strict: Option<bool>,
}
/// A file being run: its name for people and the folder its relative paths start from (none for a
/// script given as text).
struct Frame {
shown: Arc<str>,
dir: Option<PathBuf>,
}
/// The files of one run: its scope, the `#includepath` list, what it has read and the files open
/// now, innermost last.
pub(crate) struct Files {
scope: ScriptScope,
jsinclude: Vec<PathBuf>,
include_path: Vec<String>,
files: usize,
bytes: usize,
probes: usize,
/// The real paths of the files open now, for cycles.
chain: Vec<PathBuf>,
/// How many of them are below the script.
levels: usize,
/// The files `$.evalFile` is running, the script first.
frames: Vec<Frame>,
}
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
/// whether its last unit is a carriage return, and what the last `#strict` line so far set.
struct Out {
units: Vec<u16>,
line: u32,
column: u32,
after_cr: bool,
map: SourceMap,
strict: Option<bool>,
}
impl Out {
fn emit(&mut self, text: &[u16]) {
for &u in text {
match u {
0x0A if self.after_cr => self.column = 0,
0x0A | 0x0D | 0x2028 | 0x2029 => {
self.line = self.line.saturating_add(1);
self.column = 0;
}
_ => self.column = self.column.saturating_add(1),
}
self.after_cr = u == 0x0D;
}
self.units.extend_from_slice(text);
}
/// The lines from here on come from file `file`, from its line `line`.
fn begin(&mut self, file: usize, line: u32) {
self.map.segments.push(Segment { out_line: self.line, file, line, shift: self.column });
}
/// Ends the line the output is on, unless it has just ended.
fn end_line(&mut self) {
if self.after_cr || !matches!(self.units.last(), Some(0x0A | 0x2028 | 0x2029)) {
self.emit(&[0x0A]);
}
}
}
/// A file's text read as a script: a byte order mark is left out, and compiled scripts and bytes
/// that are not UTF-8 are refused.
fn decode(bytes: &[u8], value: &str) -> Result<String, String> {
if bytes.starts_with(b"@JSXBIN@") {
return Err(format!("script file is compiled: {value}"));
}
let text = std::str::from_utf8(bytes).map_err(|_| format!("script file is not UTF-8 text: {value}"))?;
Ok(text.strip_prefix('\u{feff}').unwrap_or(text).to_string())
}
/// `value` without the single or double quotes around it, or `None` when a quote is not closed.
fn unquote(value: &str) -> Option<&str> {
match value.chars().next() {
Some(q @ ('"' | '\'')) => value.get(1..).and_then(|v| v.strip_suffix(q)),
_ => Some(value),
}
}
/// The folder the file at `path` is in, without Windows' `\\?\` prefix: under that prefix `..` and
/// `/` in the names joined to it would be read as plain characters.
fn folder_of(path: &Path) -> Option<PathBuf> {
path.parent().map(|p| crate::cmd::findfiles::plain(p.to_path_buf()))
}
/// Does the path `p` have a `..` name, with `/` or `\` between names?
fn has_parent(p: &str) -> bool {
p.split(['/', '\\']).any(|name| name == "..")
}
/// A real path as people read it.
fn display(path: &Path) -> Arc<str> {
Arc::from(crate::cmd::findfiles::plain(path.to_path_buf()).to_string_lossy().as_ref())
}
impl Files {
/// The files of a run of the script at `path` (`None` for a script given as text), with the
/// `JSINCLUDE` folders `jsinclude`.
pub(crate) fn new(path: Option<&str>, jsinclude: Vec<PathBuf>) -> Self {
let real = path.and_then(|p| std::fs::canonicalize(p).ok());
let dir = real.as_deref().and_then(folder_of);
Self {
scope: dir.as_deref().map(ScriptScope::of_folder).unwrap_or_default(),
jsinclude,
include_path: Vec::new(),
files: 0,
bytes: 0,
probes: 0,
chain: real.into_iter().collect(),
levels: 0,
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
}
}
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
pub(crate) fn jsinclude_env() -> Vec<PathBuf> {
#[cfg(test)]
if let Some(list) = super::TEST_JSINCLUDE.with(|t| t.borrow().clone()) {
return list;
}
std::env::var("JSINCLUDE").map(|v| v.split(';').map(str::trim).filter(|p| !p.is_empty()).map(PathBuf::from).collect()).unwrap_or_default()
}
/// The file being run now, as `$.fileName` gives it (empty for a script given as text).
pub(crate) fn file_name(&self) -> String {
self.frames.last().map(|f| f.shown.to_string()).unwrap_or_default()
}
/// The `#includepath` list, as `$.includePath` gives it.
pub(crate) fn include_path(&self) -> String {
self.include_path.join(";")
}
/// The script's own text, `text`, with its preprocessor lines read.
pub(crate) fn expand_script(&mut self, text: &str) -> Result<Expanded, Failure> {
self.bytes = self.bytes.saturating_add(text.len());
let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
let dir = self.frames.first().and_then(|f| f.dir.clone());
self.expand(shown, dir, text, true)
}
/// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its
/// preprocessor lines read. It becomes the file being run until [`Files::end_eval`].
pub(crate) fn eval_file(&mut self, path: &str) -> Result<Expanded, Failure> {
let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 };
let dir = self.frames.last().and_then(|f| f.dir.clone());
let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?;
let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?;
let shown = display(&real);
self.chain.push(real.clone());
self.levels += 1;
self.frames.push(Frame { shown: shown.clone(), dir: folder_of(&real) });
let r = self.expand(shown, folder_of(&real), &text, false);
if r.is_err() {
self.end_eval();
}
r
}
/// The file `$.evalFile` ran has ended.
pub(crate) fn end_eval(&mut self) {
if self.frames.len() > 1 {
self.frames.pop();
self.chain.pop();
self.levels = self.levels.saturating_sub(1);
}
}
/// Checks a file read at `real` against the run's limits and the files open now, and decodes
/// it. `value` is the path as the script wrote it.
fn admit(&mut self, real: &Path, bytes: Vec<u8>, value: &str) -> Result<String, (FailKind, String)> {
if self.chain.iter().any(|p| p == real) {
return Err((FailKind::Error, format!("include cycle: {value}")));
}
if self.levels >= MAX_DEPTH {
return Err((FailKind::Limit, format!("include depth limit ({MAX_DEPTH}) reached")));
}
if self.files >= MAX_FILES {
return Err((FailKind::Limit, format!("include file limit ({MAX_FILES}) reached")));
}
if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES {
return Err((FailKind::Limit, "script source limit reached (32 MiB)".to_string()));
}
self.files += 1;
self.bytes += bytes.len();
decode(&bytes, value).map_err(|m| (FailKind::Error, m))
}
/// Finds and reads the file `value` names, from the file in folder `dir`; with `search`, also in
/// the `#includepath` and `JSINCLUDE` folders.
fn open(&mut self, value: &str, dir: Option<&Path>, search: bool) -> Result<(PathBuf, Vec<u8>), (FailKind, String)> {
let path = Path::new(value);
let refused = || (FailKind::Error, format!("script file read refused: {value}"));
// A script given as text has no folder, and so no file it may read.
let Some(dir) = dir.filter(|_| !has_parent(value)) else { return Err(refused()) };
// Each candidate, and whether the scope's refusal passes it over.
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), false)];
if search && !path.is_absolute() {
candidates.extend(self.include_path.iter().map(|p| ((!has_parent(p)).then(|| dir.join(p).join(path)), false)));
candidates.extend(self.jsinclude.iter().filter(|p| p.is_absolute()).map(|p| (Some(p.join(path)), true)));
}
for (candidate, passed_over_when_refused) in candidates {
let Some(candidate) = candidate else { return Err(refused()) };
self.probes += 1;
if self.probes > MAX_PROBES {
return Err((FailKind::Limit, format!("include search limit ({MAX_PROBES} paths) reached")));
}
match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) {
Ok(found) => return Ok(found),
Err(ScriptRead::Missing) => {}
Err(ScriptRead::Refused) if passed_over_when_refused => {}
Err(ScriptRead::Refused) => return Err(refused()),
Err(ScriptRead::TooLarge) => return Err((FailKind::Limit, format!("script file is too large: {value}"))),
Err(ScriptRead::Failed(e)) => return Err((FailKind::Error, format!("cannot read script file {value}: {e}"))),
}
}
Err((FailKind::Error, format!("include file not found: {value}")))
}
/// `text`, the file `shown` in folder `dir`, with its preprocessor lines read. With `script`,
/// its `#script` line names the run.
fn expand(&mut self, shown: Arc<str>, dir: Option<PathBuf>, text: &str, script: bool) -> Result<Expanded, Failure> {
let mut out = Out { units: Vec::with_capacity(text.len()), line: 1, column: 0, after_cr: false, map: SourceMap::default(), strict: None };
let mut name = None;
self.file(&mut out, shown, dir.as_deref(), text, script, &mut name)?;
let source = String::from_utf16(&out.units).map_err(|_| Failure {
kind: FailKind::Syntax,
message: "the script is not valid text".into(),
index: 0,
file: out.map.files.first().cloned().unwrap_or_else(|| Arc::from("")),
line: 0,
column: 0,
})?;
Ok(Expanded { source, map: out.map, name, strict: out.strict })
}
/// Adds file `shown` (in folder `dir`, with text `text`) to `out`, its included files in place
/// of their lines.
fn file(
&mut self,
out: &mut Out,
shown: Arc<str>,
dir: Option<&Path>,
text: &str,
script: bool,
name: &mut Option<String>,
) -> Result<(), Failure> {
let index = out.map.files.len();
out.map.files.push(shown.clone());
let units: Vec<u16> = text.encode_utf16().collect();
out.begin(index, 1);
// A source with neither `#` nor `@` has no preprocessor line.
if !units.iter().any(|&u| u == u16::from(b'#') || u == u16::from(b'@')) {
out.emit(&units);
return Ok(());
}
let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column };
let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() };
let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?;
let mut cursor = 0usize;
for d in &program.directives {
let (start, end) = (d.span.start as usize, d.span.end as usize);
let line_start =
units.get(..start).and_then(|u| u.iter().rposition(|&c| matches!(c, 0x0A | 0x0D | 0x2028 | 0x2029))).map_or(0, |i| i + 1);
let column = u32::try_from(start - line_start + 1).unwrap_or(u32::MAX);
let at = |kind, message: String| fail(kind, message, d.line, column);
out.emit(units.get(cursor..start).unwrap_or_default());
cursor = end;
let label = format!("{}{}", d.form, d.name);
if d.value.len() > MAX_VALUE_BYTES {
return Err(at(FailKind::Syntax, format!("the value of {label} is too long")));
}
let value = unquote(&d.value).ok_or_else(|| at(FailKind::Syntax, format!("unterminated quote in {label}")))?;
match d.known {
Some(DirectiveName::Include) => {
if value.is_empty() {
return Err(at(FailKind::Syntax, format!("{label} needs a file name")));
}
let (real, bytes) = self.open(value, dir, true).map_err(|(kind, message)| at(kind, message))?;
let included = self.admit(&real, bytes, value).map_err(|(kind, message)| at(kind, message))?;
self.chain.push(real.clone());
self.levels += 1;
let r = self.file(out, display(&real), folder_of(&real).as_deref(), &included, false, name);
self.chain.pop();
self.levels -= 1;
r?;
out.end_line();
out.begin(index, d.line);
}
Some(DirectiveName::IncludePath) => {
self.include_path = value.split(';').map(str::trim).filter(|p| !p.is_empty()).map(str::to_string).collect();
}
Some(DirectiveName::Script) => {
if value.is_empty() {
return Err(at(FailKind::Syntax, format!("{label} needs a name")));
}
if script && index == 0 {
*name = Some(value.to_string());
}
}
Some(DirectiveName::Target) => {
if value.is_empty() {
return Err(at(FailKind::Syntax, format!("{label} needs a value")));
}
}
Some(DirectiveName::Strict) => match value.to_ascii_lowercase().as_str() {
"off" => out.strict = Some(false),
"on" => out.strict = Some(true),
_ => return Err(at(FailKind::Syntax, format!("{label} takes on or off"))),
},
Some(DirectiveName::TargetEngine) => return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}"))),
None if d.name.eq_ignore_ascii_case("engine") => {
return Err(at(FailKind::Syntax, format!("unsupported script directive: {label}")));
}
None => return Err(at(FailKind::Syntax, format!("unknown script directive: {label}"))),
}
}
out.emit(units.get(cursor..).unwrap_or_default());
Ok(())
}
}
+255 -33
View File
@@ -23,12 +23,24 @@
//! and the 64 levels, 16 MiB and 1,048,576 entries of [`vectorcraft_js::DataLimits`]'s default,
//! and the console's ([`console`]).
//!
//! Before a run starts, its preprocessor lines are read ([`include`]): included files take the
//! place of their lines, and an error in one is reported at its own file, line and column.
//! `$.evalFile(path)` runs another file in the same global environment and gives its last value,
//! `$.fileName` is the file being run and `$.includePath` the `#includepath` list.
//!
//! A run writes to the Script Console with `$.write` and `$.writeln`, and `vc.log` adds a line
//! there too. The session's console gets a start line, the run's output, its uncaught error, an end
//! line and a report line; the run's report holds its own output and error, its time, its host
//! calls by kind and its slowest commands.
//!
//! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the
//! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`.
pub mod console;
pub mod dialogs;
pub mod include;
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -44,6 +56,8 @@ use crate::{
Clipboard, DocState, DrawMode, EngineError, Journal, NodeId, PaintDefaults, Result, Session, cmd, command_specs, guard, waits_for_tool_edit,
};
pub mod folder;
/// The most bytes of source a run takes, as a file or as `source`.
pub const MAX_SOURCE_BYTES: usize = 8 << 20;
/// The instructions a run may execute when `maxFuel` is left out.
@@ -80,7 +94,7 @@ const MAX_BRIDGE_BYTES: u64 = 4 << 30;
/// The version `vc.api.version` gives.
pub const API_VERSION: &str = "1.0";
/// The features `vc.api.has` knows.
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console"];
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs"];
/// The most commands a run's report lists in `slowestCommands`.
pub const SLOWEST_COMMANDS: usize = 5;
@@ -131,10 +145,16 @@ pub(crate) fn refused_text(id: &str) -> String {
/// A request to run a script.
pub(crate) struct Request {
/// The run's name; unless `name_given`, a `#script` line in the script replaces it.
pub name: String,
pub name_given: bool,
/// The file the script was read from, which its included files are read beside.
pub file: Option<String>,
pub source: String,
pub args: Map<String, Value>,
pub fuel: u64,
/// The answers to the dialogs of a run with nobody to ask, in order.
pub answers: Vec<DialogAnswer>,
}
thread_local! {
@@ -468,8 +488,24 @@ struct Host {
commands: RefCell<HashMap<&'static str, (u64, u128, u128)>>,
/// The time the run's slices took, in nanoseconds.
run_nanos: Cell<u128>,
/// `alert`, `confirm` and `prompt`: their answers and the list the report gives.
dialogs: dialogs::Dialogs,
/// The files the run reads: its includes and `$.evalFile`'s.
files: RefCell<include::Files>,
/// Where the lines of the script's expanded source came from.
script_map: RefCell<include::SourceMap>,
/// The same for each source `$.evalFile` gave, in order.
eval_maps: RefCell<Vec<include::SourceMap>>,
/// The last error `$.evalFile` raised for a file it could not run, with the file, line and
/// column that error is at.
eval_failure: RefCell<Option<EvalFailure>>,
/// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one).
eval_strict: Cell<Option<bool>>,
}
/// An error `$.evalFile` raised, as thrown, and the file, line and column it is at.
type EvalFailure = (String, Arc<str>, u32, u32);
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
#[derive(Default)]
struct Counts {
@@ -899,6 +935,8 @@ fn each_line(text: &str, mut done: impl FnMut(String, bool)) {
/// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)`
/// gives them, one after another, and `$.writeln(...values)` does the same and ends the line.
/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file
/// being run and `$.includePath` the `#includepath` list.
fn dollar_object(host: &Rc<Host>) -> Vec<(String, HostItem)> {
let writer = |end: bool| {
let h = host.clone();
@@ -910,7 +948,73 @@ fn dollar_object(host: &Rc<Host>) -> Vec<(String, HostItem)> {
Ok(Data::Undefined)
}))
};
vec![("write".into(), writer(false)), ("writeln".into(), writer(true))]
let getter = |read: fn(&include::Files) -> String| {
let h = host.clone();
HostItem::Getter(function(move |_| {
let text = read(&h.files.borrow());
h.charge_call(text.len() as u64 + 2)?;
Ok(Data::String(text))
}))
};
let eval_file = {
let h = host.clone();
let end = host.clone();
let strict = host.clone();
HostItem::Evaluator {
source: function(move |a| eval_file(&h, a)),
end: Rc::new(move || end.files.borrow_mut().end_eval()),
strict_writes: Rc::new(move || strict.eval_strict.get()),
}
};
vec![
("write".into(), writer(false)),
("writeln".into(), writer(true)),
("evalFile".into(), eval_file),
("fileName".into(), getter(include::Files::file_name)),
("includePath".into(), getter(include::Files::include_path)),
]
}
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
/// run, with its preprocessor lines read, which the interpreter then runs. `timeout`, in
/// milliseconds, is taken and not waited on: the file is read at once.
fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError> {
let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else {
return Err(HostError::Type(EVAL_NO_PATH.to_string()));
};
match args.get(1) {
None | Some(Data::Undefined) => {}
Some(Data::Number(ms)) if ms.is_finite() && *ms >= 0.0 => {}
Some(Data::Number(_)) => return Err(HostError::Range(EVAL_TIMEOUT.to_string())),
Some(_) => return Err(HostError::Type(EVAL_TIMEOUT.to_string())),
}
if args.len() > 2 {
return Err(HostError::Type(EVAL_ARGUMENTS.to_string()));
}
host.charge_call(path.len() as u64 + 2)?;
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
if f.line > 0 {
*host.eval_failure.borrow_mut() = Some((message.clone(), f.file.clone(), f.line, f.column));
}
match f.kind {
include::FailKind::Limit => HostError::Abort(message),
include::FailKind::Syntax => HostError::Syntax(message),
include::FailKind::Error => HostError::Error(message),
}
})?;
// A file without preprocessor lines is parsed here first, so its syntax error names its place.
let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() };
if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) {
host.files.borrow_mut().end_eval();
let (_, file, line, column) = expanded.map.locate(e.line, e.column);
let message = format!("{file}:{line}:{column}: {}", e.message);
*host.eval_failure.borrow_mut() = Some((message.clone(), file, line, column));
return Err(HostError::Syntax(message));
}
host.eval_maps.borrow_mut().push(expanded.map);
host.eval_strict.set(expanded.strict);
Ok(Data::String(expanded.source))
}
fn function(f: impl Fn(Vec<Data>) -> std::result::Result<Data, HostError> + 'static) -> HostFunction {
@@ -974,21 +1078,67 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
}
/// `message`, with what to do about a failure that comes from a script written for another program.
fn explained(kind: &RunErrorKind, message: &str, source: &str, line: u32) -> String {
const HOST_OBJECTS: &[&str] = &["app", "alert", "confirm", "prompt", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"];
fn explained(kind: &RunErrorKind, message: &str) -> String {
const HOST_OBJECTS: &[&str] = &["app", "File", "Folder", "Window", "BridgeTalk", "activeDocument", "documents"];
let names_host_object =
message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o)));
let directive =
*kind == RunErrorKind::Syntax && line > 0 && source.lines().nth(line as usize - 1).is_some_and(|l| l.trim_start().starts_with('#'));
if *kind == RunErrorKind::Thrown && names_host_object {
format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)")
} else if directive {
format!("{message} (preprocessor lines such as `#target` and `#include` are not read yet)")
} else {
message.to_string()
}
}
/// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own.
fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
let (kind, message) = match f.kind {
include::FailKind::Syntax if f.line > 0 => {
(RunErrorKind::Syntax, format!("SyntaxError: {} (line {}, column {})", f.message, f.line, f.column))
}
include::FailKind::Syntax => (RunErrorKind::Syntax, format!("SyntaxError: {}", f.message)),
include::FailKind::Error => (RunErrorKind::Thrown, format!("Error: {}", f.message)),
include::FailKind::Limit => (RunErrorKind::Limit(LimitKind::Host), f.message),
};
let file = (f.index > 0).then_some(f.file);
(RunError { kind, message, line: f.line, column: f.column }, file)
}
/// `e`, which the realm raised in source `tag` ([`Realm::error_source`]), at the line and column of
/// the file it is in, with that file's name unless it is the script's own.
fn located(host: &Host, tag: u32, e: &RunError) -> (RunError, Option<Arc<str>>) {
let map = |m: &include::SourceMap, own: bool| {
let (index, file, line, column) = m.locate(e.line, e.column);
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
(RunError { kind: e.kind.clone(), message, line, column }, (!own || index > 0).then_some(file))
};
// An error `$.evalFile` raised for a file it could not run is at that file's place.
if let Some((_, file, line, column)) = host.eval_failure.borrow().as_ref().filter(|(thrown, ..)| e.message.contains(thrown.as_str())) {
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, *line, *column) } else { e.message.clone() };
return (RunError { kind: e.kind.clone(), message, line: *line, column: *column }, Some(file.clone()));
}
if e.line == 0 {
return (e.clone(), None);
}
match tag {
0 => map(&host.script_map.borrow(), true),
n if n != vectorcraft_js::UNKNOWN_SOURCE => match host.eval_maps.borrow().get(n as usize - 1) {
Some(m) => map(m, false),
None => (e.clone(), None),
},
_ => (e.clone(), None),
}
}
/// A syntax error's `message`, which ends with its place `(line L, column C)`, with the place
/// given as `line`, `column`.
fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u32) -> String {
let old = format!(" (line {old_line}, column {old_column})");
match message.strip_suffix(&old) {
Some(m) => format!("{m} (line {line}, column {column})"),
None => message.to_string(),
}
}
impl Session {
/// Is a script running? While one is, the commands that change anything are refused.
pub fn script_running(&self) -> bool {
@@ -1031,6 +1181,23 @@ impl Session {
!self.script_stop.is_set() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.waiting.get())).unwrap_or(false)
}
/// The dialog (`alert`, `confirm` or `prompt`) the running script waits at for the person's
/// answer. A run asked to stop no longer waits: the next [`Session::script_pump`] ends it.
pub fn script_dialog(&self) -> Option<ScriptDialog> {
if self.script_stop.is_set() {
return None;
}
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting())).flatten()
}
/// Gives the dialog the running script waits at its answer; the next [`Session::script_pump`]
/// goes on from the call. → false when nothing waits, the answer is for another kind of
/// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`].
pub fn script_answer(&mut self, answer: DialogAnswer) -> bool {
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false };
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
}
/// The name of the running script.
pub fn script_name(&self) -> Option<String> {
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone()))
@@ -1091,8 +1258,8 @@ impl Session {
Ok(())
}
/// Begins a run of `request`.
pub(crate) fn script_start(&mut self, request: Request) -> Result<()> {
/// Begins a run of `request`. → the run's name.
pub(crate) fn script_start(&mut self, request: Request) -> Result<String> {
self.settle_for_script()?;
// In a build where a fault ends the program, every unsaved document has a copy first.
if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() {
@@ -1103,8 +1270,14 @@ impl Session {
self.script_high_water.retain(|uid, _| open.contains(uid));
self.script_stop.clear();
self.script_report = None;
let mut files = include::Files::new(request.file.as_deref(), include::Files::jsinclude_env());
let expanded = files.expand_script(&request.source);
let name = match &expanded {
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
_ => request.name,
};
let limits = Limits { fuel: request.fuel, heap_bytes: HEAP_BYTES, ..Limits::default() };
let options = Options { max_source_units: MAX_SOURCE_BYTES.saturating_mul(2), ..Options::default() };
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() };
let mut realm = Realm::with_options(options, limits);
realm.share_interrupt(&self.script_stop);
realm.set_data_limits(DataLimits::default());
@@ -1126,34 +1299,49 @@ impl Session {
log_bytes: Cell::new(0),
written: RefCell::new(Vec::new()),
run: self.script_runs,
name: console::line_name(&request.name),
name: console::line_name(&name),
console: RefCell::default(),
pending: RefCell::default(),
counts: Counts::default(),
commands: RefCell::default(),
run_nanos: Cell::new(0),
dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers),
files: RefCell::new(files),
script_map: RefCell::default(),
eval_maps: RefCell::default(),
eval_failure: RefCell::default(),
eval_strict: Cell::new(None),
});
let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0))
.map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?;
let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry: console::Entry::Start };
self.script_console.push(line, false);
let started = realm
.define_host_object("vc", vc_object(&host, args))
.and_then(|()| realm.define_host_object("$", dollar_object(&host)))
.and_then(|()| realm.start(&request.source));
if let Err(e) = started {
let mut report = failure_report(&request.name, &e, &request.source, &host, 0, 0);
let started = match expanded {
Err(f) => Err(preprocessor_error(f)),
Ok(expanded) => {
*host.script_map.borrow_mut() = expanded.map;
realm.set_strict_writes(expanded.strict == Some(true));
realm
.define_host_object("vc", vc_object(&host, args))
.and_then(|()| realm.define_host_object("$", dollar_object(&host)))
.and_then(|()| dialogs::install(&mut realm, &host))
.and_then(|()| realm.start(&expanded.source))
.map_err(|e| located(&host, realm.error_source(), &e))
}
};
if let Err((e, file)) = started {
let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0);
close_run(self, &host, &mut report, ending(&e.kind));
let message = failure_text(&report);
self.script_report = Some(report);
return Err(EngineError::Other(message));
}
let scope = crate::file_access::ScopeHandle::capture();
let job = Job { realm, host, world: World::working(self), start_uids: open, name: request.name, scope };
let job = Job { realm, host, world: World::working(self), start_uids: open, name: name.clone(), scope };
let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
JOBS.with(|jobs| jobs.borrow_mut().insert(id, job));
self.script_key = Some(JobKey(id));
Ok(())
Ok(name)
}
/// Advances the running script by one slice. `None` while it is still running; otherwise the
@@ -1163,11 +1351,20 @@ impl Session {
let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else {
return Some(Err(EngineError::Other(JOB_GONE.to_string())));
};
if job.host.waiting.get() && !self.script_stop.is_set() {
if let Some(e) = job.host.dialogs.take_failure() {
return Some(self.script_failed(job, &e));
}
if (job.host.waiting.get() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() {
JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job));
self.script_key = Some(key);
return None;
}
// A stop while a dialog waits ends the run there; the interpreter cannot go on from the call.
if job.realm.waits() {
let kind = LimitKind::Interrupted;
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 };
return Some(self.script_failed(job, &e));
}
if vectorcraft_doc::cancel::check().is_err() {
self.script_stop.set();
}
@@ -1184,6 +1381,12 @@ impl Session {
self.script_key = Some(key);
None
}
Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => {
let n = job.host.dialogs.unused();
let kind = LimitKind::Host;
let message = format!("`answers` has {n} answer{} the script did not use", if n == 1 { "" } else { "s" });
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 }))
}
Ok(Ok(Progress::Done(_))) => {
let r = self.script_commit(job);
self.trim_histories();
@@ -1193,8 +1396,10 @@ impl Session {
}
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
job.host.dialogs.stopped();
let fuel_left = job.realm.fuel_left();
let mut report = failure_report(&job.name, e, "", &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
let (e, file) = located(&job.host, job.realm.error_source(), e);
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
close_run(self, &job.host, &mut report, ending(&e.kind));
drop(job);
raise_ids(self);
@@ -1288,7 +1493,7 @@ impl Session {
if let Some(result) = self.script_pump() {
return result;
}
if self.script_waiting() {
if self.script_waiting() || self.script_dialog().is_some() {
self.script_stop.set();
}
}
@@ -1308,13 +1513,16 @@ const TOO_MANY_ARGUMENTS: &str = "vc.run: takes a command id and an object of pa
const PARAMS_NOT_OBJECT: &str = "vc.run: the parameters must be an object";
const LOG_FULL: &str = "vc.log: the log of this run is full";
const NO_RECOVERY_COPY: &str = "a recovery copy could not be written, so the script was not run";
const EVAL_NO_PATH: &str = "$.evalFile requires a file path";
const EVAL_TIMEOUT: &str = "$.evalFile: the timeout must be a finite number of milliseconds, 0 or more";
const EVAL_ARGUMENTS: &str = "$.evalFile: takes a file path and a timeout";
/// The report of a run that failed.
fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left: u64, fuel_used: u64) -> Value {
json!({
/// The report of a run that failed; `file` is the included file the error is in.
fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value {
let mut report = json!({
"ok": false,
"kind": kind_id(&e.kind),
"message": explained(&e.kind, &e.message, source, e.line),
"message": explained(&e.kind, &e.message),
"name": name,
"line": e.line,
"column": e.column,
@@ -1323,7 +1531,11 @@ fn failure_report(name: &str, e: &RunError, source: &str, host: &Host, fuel_left
"fuelLeft": fuel_left,
"fuelUsed": fuel_used,
"hostCalls": host.calls.get(),
})
});
if let (Some(file), Some(o)) = (file, report.as_object_mut()) {
o.insert("file".into(), json!(file));
}
report
}
/// How the run that failed with `kind` ended, as its console end line gives it.
@@ -1347,8 +1559,8 @@ fn line_to(s: &mut Session, host: &Host, entry: console::Entry, cut: bool) {
/// Ends the console lines of `host`'s run: the line `$.write` left unended, then for a failed run
/// (`report["ok"]` false) its error as `name:line:column: message`, then an end line and a report
/// line in the session's console. Adds the run's time, host calls by kind, slowest commands and
/// console to `report`.
/// line in the session's console. Adds the run's time, host calls by kind, slowest commands,
/// console and dialogs to `report`.
fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::Ending) {
let mut pending = std::mem::take(&mut *host.pending.borrow_mut());
if !pending.is_empty() {
@@ -1361,8 +1573,11 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
if report["ok"] == false {
let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0));
let message = report["message"].as_str().unwrap_or_default();
let text =
if line > 0 { format!("{}:{line}:{column}: {message}", host.name) } else { format!("{}: location unavailable: {message}", host.name) };
let text = match report["file"].as_str() {
Some(file) if line > 0 => format!("{}: {file}:{line}:{column}: {message}", host.name),
_ if line > 0 => format!("{}:{line}:{column}: {message}", host.name),
_ => format!("{}: location unavailable: {message}", host.name),
};
each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut));
}
let timing = clock().is_some();
@@ -1379,6 +1594,7 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
o.insert("hostCallCounts".into(), host.counts.json());
o.insert("slowestCommands".into(), Value::Array(slow_json));
o.insert("console".into(), host.console.borrow().report());
host.dialogs.report(o);
}
}
@@ -1386,7 +1602,11 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
fn failure_text(report: &Value) -> String {
let s = |k: &str| report[k].as_str().unwrap_or_default();
let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0));
let at = if line > 0 { format!(" line {line}, column {column}") } else { String::new() };
let at = match report["file"].as_str() {
Some(file) if line > 0 => format!(" line {line}, column {column} of {file}"),
_ if line > 0 => format!(" line {line}, column {column}"),
_ => String::new(),
};
let written = report["written"].as_array().map_or(0, Vec::len);
let kept = if written > 0 {
let paths: Vec<&str> = report["written"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
@@ -1454,4 +1674,6 @@ thread_local! {
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the `JSINCLUDE` folders in place of the environment's.
pub(crate) static TEST_JSINCLUDE: RefCell<Option<Vec<std::path::PathBuf>>> = const { RefCell::new(None) };
}
+1
View File
@@ -86,6 +86,7 @@ impl Session {
profile_dir: None,
color_settings_file: None,
plugin_dir: None,
scripts_dir: None,
ignored_plugin_grants: Default::default(),
plugin_output: None,
plugin_install_approval: None,
+8 -1
View File
@@ -135,11 +135,18 @@ fn too_large(max: u64) -> String {
format!("larger than {max} bytes")
}
/// Whether `old` holds exactly `bytes`. It is read no further than one byte past their length, so a
/// large file is not read into memory.
pub(crate) fn holds(old: impl Read, bytes: &[u8]) -> bool {
let mut read = vec![];
old.take(bytes.len() as u64 + 1).read_to_end(&mut read).is_ok() && read == bytes
}
/// Write `bytes` to `dir/file`, making the folder; nothing is written when the file has them
/// already. A failure is logged: remembering is best effort and never fails the command.
fn put(dir: &Path, file: &str, bytes: &[u8]) -> bool {
let path = dir.join(file);
if std::fs::read(&path).is_ok_and(|old| old == bytes) {
if std::fs::File::open(&path).is_ok_and(|old| holds(old, bytes)) {
return true;
}
let written = std::fs::create_dir_all(dir).and_then(|()| write_atomic(&path, bytes));
+399
View File
@@ -151,6 +151,9 @@ mod save;
mod saveoptions;
mod scalestrokes;
mod script_console;
mod script_dialogs;
mod script_folder;
mod script_include;
mod script_run;
mod scripts;
mod select_ids_first;
@@ -3455,6 +3458,402 @@ fn reshape_by_no_distance_on_an_anchor_records_no_undo_step() {
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
}
/// Seven anchors 70 apart along a line, from x 0 to x 420.
fn reshape_line_of_seven() -> Value {
json!([{"x": 0, "y": 0}, {"x": 70, "y": 0}, {"x": 140, "y": 0}, {"x": 210, "y": 0}, {"x": 280, "y": 0}, {"x": 350, "y": 0}, {"x": 420, "y": 0}])
}
#[test]
fn reshape_with_two_focal_points_moves_the_anchors_between_them_whole() {
let mut s = session();
let id = reshape_open_path(&mut s, reshape_line_of_seven());
s.execute("path.reshape", &json!({"id": id.0, "x": 280.0, "y": 0.0, "dx": 0.0, "dy": 100.0, "focal": [[0, 2]]})).unwrap();
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert_eq!(&y[2..5], &[100.0, 100.0, 100.0], "both focal points and the anchor between them: {y:?}");
assert_eq!((y[0], y[6]), (0.0, 0.0), "the ends stay: {y:?}");
// Each side stretches from its own end to its nearer focal point, 140 along the path.
assert!((y[1] - 100.0 * reshape_share(0.5)).abs() < 1e-9 && (y[5] - 100.0 * reshape_share(0.5)).abs() < 1e-9, "{y:?}");
}
#[test]
fn reshape_of_a_closed_path_selected_whole_moves_all_of_it() {
let mut s = session();
let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let before = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().clone();
s.execute("path.reshape", &json!({"id": r.0, "x": 0.0, "y": 0.0, "dx": 15.0, "dy": -40.0, "focal": []})).unwrap();
let after = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().clone();
assert_eq!(after.anchor_count(), before.anchor_count(), "a grab on an anchor adds none");
let drag = vectorcraft_geom::Vec2::new(15.0, -40.0);
for ((_, _, a), (_, _, b)) in after.anchors().zip(before.anchors()) {
assert_eq!((a.p - b.p, a.h_in - b.h_in, a.h_out - b.h_out), (drag, drag, drag), "{after:?}");
}
}
#[test]
fn reshape_leaves_the_anchors_that_are_not_selected_in_place() {
let mut s = session();
let id = reshape_open_path(&mut s, reshape_line_of_seven());
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap();
s.execute("path.reshape", &json!({"id": id.0, "x": 350.0, "y": 0.0, "dx": 0.0, "dy": 100.0, "focal": []})).unwrap();
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert_eq!((y[0], y[1], y[5], y[6]), (0.0, 0.0, 100.0, 0.0), "{y:?}");
// The stretch runs from the last anchor that is not selected, 280 from the focal point.
for i in 2..5 {
let u = (i as f64 - 1.0) / 4.0;
assert!((y[i] - 100.0 * reshape_share(u)).abs() < 1e-9, "anchor {i} takes {u} of the way: {y:?}");
}
}
/// A step with neither `focal` nor `radius`, as one recorded before focal points, plays as it did
/// then: the selection does not matter, and a closed path follows with the default falloff.
#[test]
fn reshape_without_focal_or_radius_keeps_the_earlier_rule() {
let mut s = session();
let id = reshape_open_path(&mut s, reshape_line_of_seven());
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap();
s.execute("path.reshape", &json!({"id": id.0, "x": 350.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap();
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert_eq!((y[0], y[5], y[6]), (0.0, 100.0, 0.0), "{y:?}");
// Anchor 1 is not selected and still takes its share, measured from the end 350 away.
for i in 1..5 {
let u = i as f64 / 5.0;
assert!((y[i] - 100.0 * reshape_share(u)).abs() < 1e-9, "anchor {i} takes {u} of the way: {y:?}");
}
// `focal: null` is the same as leaving it out.
let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("path.reshape", &json!({"id": r.0, "x": 0.0, "y": 0.0, "dx": 0.0, "dy": -40.0, "focal": null})).unwrap();
let pts: Vec<Point> = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
assert!(pts.contains(&Point::new(0.0, -40.0)), "{pts:?}");
assert!(pts.contains(&Point::new(100.0, 100.0)), "the far corner stays: {pts:?}");
}
#[test]
fn reshape_of_a_partly_selected_closed_path_stretches_between_the_anchors_that_stay() {
let mut s = session();
let id = NodeId(
s.execute(
"path.create",
&json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 200, "y": 0}, {"x": 200, "y": 100}, {"x": 100, "y": 100}, {"x": 0, "y": 100}], "closed": true}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
// Anchors 5, 0, 1 and 2 are selected; 3 and 4 stay. The walk runs 4, 5, 0, 1, 2, 3.
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 5], [0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap();
s.execute("path.reshape", &json!({"id": id.0, "x": 0.0, "y": 0.0, "dx": 0.0, "dy": -50.0, "focal": []})).unwrap();
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert_eq!((y[0], y[3], y[4]), (-50.0, 100.0, 100.0), "{y:?}");
// From anchor 4 to the focal point is 200: anchor 5 is halfway. From anchor 3 back to it is
// 300: anchor 2 is a third of the way and anchor 1 two thirds.
let want = [(5, 100.0 + -50.0 * reshape_share(0.5)), (2, -50.0 * reshape_share(1.0 / 3.0)), (1, -50.0 * reshape_share(2.0 / 3.0))];
for (i, w) in want {
assert!((y[i] - w).abs() < 1e-9, "anchor {i}: {y:?}");
}
}
#[test]
fn reshape_of_a_segment_keeps_the_selected_anchors_and_selects_the_new_one() {
let mut s = session();
let id = reshape_open_path(&mut s, reshape_line_of_seven());
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap();
s.execute("path.reshape", &json!({"id": id.0, "x": 245.0, "y": 0.0, "dx": 0.0, "dy": 60.0, "focal": [[0, 5]]})).unwrap();
let a = reshape_anchors(&s, id);
assert_eq!(a.len(), 8, "the grab adds an anchor between 210 and 280");
let selected: Vec<(usize, usize)> = s.doc().unwrap().selection.partial(id).unwrap().iter().copied().collect();
assert_eq!(selected, vec![(0, 3), (0, 4), (0, 5), (0, 6)], "the same points stay selected, with the new one");
// The focal point given before the anchor was added still names the anchor at 350.
let y: Vec<f64> = a.iter().map(|a| a.p.y).collect();
assert_eq!(&y[4..7], &[60.0, 60.0, 60.0], "{y:?}");
assert_eq!((y[0], y[1], y[2], y[7]), (0.0, 0.0, 0.0, 0.0), "{y:?}");
}
#[test]
fn reshape_of_a_segment_with_a_selected_anchor_index_past_the_end_does_not_panic() {
let mut s = session();
let id = reshape_open_path(&mut s, reshape_line_of_seven());
let past = usize::MAX;
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, past]], "mode": "set"})).unwrap();
s.execute("path.reshape", &json!({"id": id.0, "x": 175.0, "y": 0.0, "dx": 0.0, "dy": 10.0})).unwrap();
s.execute("path.reshape", &json!({"id": id.0, "x": 105.0, "y": 0.0, "dx": 0.0, "dy": 10.0})).unwrap();
assert_eq!(reshape_anchors(&s, id).len(), 9);
}
#[test]
fn reshape_of_a_segment_keeps_a_selected_segment_as_its_two_halves() {
let mut s = session();
let id = reshape_open_path(&mut s, reshape_line_of_seven());
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 2], [0, 4]], "mode": "set"})).unwrap();
s.execute("path.reshape", &json!({"id": id.0, "x": 175.0, "y": 0.0, "dx": 0.0, "dy": 0.0})).unwrap();
let st = s.doc().unwrap();
let segments: Vec<(usize, usize)> = st.selection.segments[&id].iter().copied().collect();
assert_eq!(segments, vec![(0, 2), (0, 3), (0, 5)]);
let anchors: Vec<(usize, usize)> = st.selection.partial(id).unwrap().iter().copied().collect();
assert_eq!(anchors, vec![(0, 2), (0, 3), (0, 4), (0, 5), (0, 6)], "the new anchor moves with the segment's ends");
}
#[test]
fn reshape_moves_only_the_subpaths_with_a_focal_point() {
let mut s = session();
let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L100 0 L200 0 M0 100 L100 100 L200 100"})).unwrap()["id"].as_u64().unwrap());
s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 0.0, "dx": 0.0, "dy": 40.0, "focal": []})).unwrap();
let pd = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone();
let y: Vec<Vec<f64>> = pd.subpaths.iter().map(|sp| sp.anchors.iter().map(|a| a.p.y).collect()).collect();
assert_eq!(y[1], vec![100.0, 100.0, 100.0], "{y:?}");
assert_eq!((y[0][0], y[0][2]), (0.0, 40.0), "{y:?}");
// A focal point on the other subpath stretches that one too.
s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 40.0, "dx": 0.0, "dy": 10.0, "focal": [[1, 1]]})).unwrap();
let pd = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone();
assert_eq!(pd.subpaths[1].anchors.iter().map(|a| a.p.y).collect::<Vec<_>>(), vec![100.0, 110.0, 100.0]);
}
#[test]
fn reshape_refuses_a_focal_point_that_is_not_an_anchor() {
let mut s = session();
let id = reshape_open_path(&mut s, reshape_line_of_seven());
let before = reshape_anchors(&s, id);
for (focal, want) in [
(json!([[0, 7]]), "`focal` names [0, 7], which is not an anchor of the path"),
(json!([[1, 0]]), "`focal` names [1, 0], which is not an anchor of the path"),
(json!([[0, -1]]), "invalid anchor index -1"),
(json!({"0": 1}), "`focal` must be an array of [subpath, anchor] pairs"),
] {
let e = s.execute("path.reshape", &json!({"id": id.0, "x": 420.0, "y": 0.0, "dx": 0.0, "dy": 10.0, "focal": focal})).unwrap_err();
assert!(e.to_string().contains(want), "{e}");
}
assert_eq!(reshape_anchors(&s, id), before);
let steps = s.doc().unwrap().history.undo.len();
// An empty `focal` chooses the focal-point rule too, so it cannot go with `radius` either.
for focal in [json!([[0, 2]]), json!([])] {
let e =
s.execute("path.reshape", &json!({"id": id.0, "x": 420.0, "y": 0.0, "dx": 0.0, "dy": 10.0, "focal": focal, "radius": 50.0})).unwrap_err();
assert!(e.to_string().contains("`focal` and `radius` cannot be used together"), "{focal}: {e}");
}
assert_eq!(reshape_anchors(&s, id), before);
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
}
/// The line of seven, selected whole, with the Reshape tool picked.
fn reshape_tool_on_a_line(s: &mut Session) -> NodeId {
let id = reshape_open_path(s, reshape_line_of_seven());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.select_tool("reshape", ViewInfo::default()).unwrap();
id
}
/// Presses at `a`, drags to `b` unless it is `a` (a click), and releases, with Shift when `shift`.
fn reshape_gesture(s: &mut Session, a: (f64, f64), b: (f64, f64), shift: bool) {
let v = ViewInfo::default();
let mods = vectorcraft_tools::Mods { shift, ..vectorcraft_tools::Mods::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, a.0, a.1).with_mods(mods), v).unwrap();
if a != b {
s.pointer(&PointerEvent::new(PointerKind::Drag, b.0, b.1).with_mods(mods), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Up, b.0, b.1).with_mods(mods), v).unwrap();
}
/// Where the Reshape tool draws its highlighted focal points.
fn reshape_highlights(s: &mut Session) -> Vec<Point> {
s.overlays(ViewInfo::default())
.into_iter()
.filter_map(|o| match o {
vectorcraft_tools::Overlay::Anchor { p, filled: true, .. } => Some(p),
_ => None,
})
.collect()
}
#[test]
fn reshape_tool_shift_click_adds_focal_points_that_a_drag_moves_together() {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
let steps = s.doc().unwrap().history.undo.len();
reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false);
reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), true);
assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 0.0), Point::new(280.0, 0.0)]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a click on an anchor is not an edit");
reshape_gesture(&mut s, (280.0, 0.0), (280.0, 100.0), false);
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert_eq!(&y[2..5], &[100.0, 100.0, 100.0], "{y:?}");
assert!((y[1] - 50.0).abs() < 1e-9 && (y[5] - 50.0).abs() < 1e-9 && y[0] == 0.0 && y[6] == 0.0, "{y:?}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "the drag is one step");
assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 100.0), Point::new(280.0, 100.0)], "the focal points stay highlighted");
}
#[test]
fn reshape_tool_shift_click_on_a_focal_point_removes_it_and_a_click_starts_again() {
for (clicks, want) in [
// Shift-click 140 again: only 280 is a focal point.
(vec![(140.0, false), (280.0, true), (140.0, true)], vec![Point::new(280.0, 0.0)]),
// A click without Shift: only 350 is a focal point.
(vec![(140.0, false), (280.0, true), (350.0, false)], vec![Point::new(350.0, 0.0)]),
] {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
for (x, shift) in clicks {
reshape_gesture(&mut s, (x, 0.0), (x, 0.0), shift);
}
assert_eq!(reshape_highlights(&mut s), want);
let at = (want[0].x, 0.0);
reshape_gesture(&mut s, at, (at.0, 100.0), false);
let full = reshape_anchors(&s, id).iter().filter(|a| a.p.y == 100.0).count();
assert_eq!(full, 1, "only the dragged focal point moves whole: {:?}", reshape_anchors(&s, id));
}
}
#[test]
fn reshape_tool_focal_point_stays_its_anchor_when_another_anchor_moves_onto_it() {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), false);
// Anchor 2 now lies where the focal point, anchor 4, lies.
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 280.0, "y": 0.0})).unwrap();
// A Shift-click adds the last anchor, and a drag from it moves it and anchor 4 whole.
reshape_gesture(&mut s, (420.0, 0.0), (420.0, 0.0), true);
reshape_gesture(&mut s, (420.0, 0.0), (420.0, 100.0), false);
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert!(y[4] == 100.0 && y[6] == 100.0 && y[2] < 100.0, "{y:?}");
}
#[test]
fn reshape_tool_anchor_added_before_a_focal_point_keeps_it_highlighted() {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), false);
// A Shift-click on the segment from 70 to 140 adds anchor 2, before the focal point.
reshape_gesture(&mut s, (105.0, 0.0), (105.0, 0.0), true);
assert_eq!(reshape_anchors(&s, id).len(), 8);
assert_eq!(reshape_highlights(&mut s), vec![Point::new(280.0, 0.0), Point::new(105.0, 0.0)]);
// A drag from the added anchor moves both focal points whole.
reshape_gesture(&mut s, (105.0, 0.0), (105.0, 40.0), false);
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert!(y[2] == 40.0 && y[5] == 40.0, "{y:?}");
}
#[test]
fn reshape_tool_focal_point_moved_by_another_edit_is_not_passed_to_another_anchor() {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), false);
// The focal point, anchor 4, moves away, and anchor 2 takes its old place.
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 4, "x": 280.0, "y": 50.0})).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 280.0, "y": 0.0})).unwrap();
assert_eq!(reshape_highlights(&mut s), vec![]);
// A Shift-click adds the last anchor, and a drag from it moves it alone as the focal point.
reshape_gesture(&mut s, (420.0, 0.0), (420.0, 0.0), true);
assert_eq!(reshape_highlights(&mut s), vec![Point::new(420.0, 0.0)]);
reshape_gesture(&mut s, (420.0, 0.0), (420.0, 100.0), false);
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert!(y[6] == 100.0 && y[2] < 100.0, "{y:?}");
}
#[test]
fn reshape_tool_drag_from_an_anchor_that_is_not_highlighted_moves_only_it_whole() {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false);
reshape_gesture(&mut s, (350.0, 0.0), (350.0, 100.0), false);
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert!(y[2] < 100.0 && y[5] == 100.0, "{y:?}");
assert_eq!(reshape_highlights(&mut s), vec![Point::new(350.0, 100.0)]);
}
#[test]
fn reshape_tool_click_on_a_segment_adds_a_highlighted_anchor() {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
let steps = s.doc().unwrap().history.undo.len();
reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false);
reshape_gesture(&mut s, (245.0, 0.0), (245.0, 0.0), true);
assert_eq!(reshape_anchors(&s, id).len(), 8);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "adding the anchor is one step");
assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 0.0), Point::new(245.0, 0.0)]);
reshape_gesture(&mut s, (245.0, 0.0), (245.0, 60.0), false);
let a = reshape_anchors(&s, id);
assert_eq!((a[2].p.y, a[3].p.y, a[4].p.y), (60.0, 60.0, 60.0), "{a:?}");
// Undo takes back the drag, then the added anchor. The highlights stay where the drag left
// them, where no anchor is now, so none shows.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(reshape_anchors(&s, id).len(), 7);
assert!(reshape_highlights(&mut s).is_empty());
}
#[test]
fn reshape_tool_escape_during_a_drag_keeps_the_path_and_its_focal_points() {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
let before = reshape_anchors(&s, id);
let steps = s.doc().unwrap().history.undo.len();
reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false);
reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), true);
let v = ViewInfo::default();
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 0.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 90.0), v).unwrap();
assert_ne!(reshape_anchors(&s, id), before, "the preview moves the path");
s.tool_key(ToolKey::Escape, vectorcraft_tools::Mods::default(), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 90.0), v).unwrap();
assert_eq!(reshape_anchors(&s, id), before);
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 0.0), Point::new(280.0, 0.0)]);
}
#[test]
fn reshape_tool_shift_drag_from_an_anchor_that_is_not_highlighted_moves_only_it() {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false);
// Shift keeps the drag's angle; the highlighted anchor at 140 does not move whole with it.
reshape_gesture(&mut s, (350.0, 0.0), (350.0, 100.0), true);
let y: Vec<f64> = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect();
assert!(y[5] == 100.0 && y[2] < 100.0, "{y:?}");
assert_eq!(reshape_highlights(&mut s), vec![Point::new(350.0, 100.0)]);
}
#[test]
fn reshape_tool_click_on_a_curved_segment_highlights_the_anchor_it_adds() {
// Points on the curve from 0 to 300, away from its anchors, each clicked from off it on a
// new copy of the path.
let c = vectorcraft_geom::CubicBez::new(Point::new(0.0, 0.0), Point::new(40.0, -90.0), Point::new(230.0, 110.0), Point::new(300.0, 0.0));
for k in 1..60 {
let t = 0.05 + 0.015 * f64::from(k);
for off in [(0.3, -0.2), (-2.1, 1.7), (2.6, 2.2)] {
let mut s = session();
let id = NodeId(
s.execute(
"path.create",
&json!({"anchors": [{"x": 0, "y": 0, "out": [40, -90]}, {"x": 300, "y": 0, "in": [230, 110]}, {"x": 600, "y": 0}]}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.select_tool("reshape", ViewInfo::default()).unwrap();
let q = vectorcraft_geom::ParamCurve::eval(&c, t);
reshape_gesture(&mut s, (q.x + off.0, q.y + off.1), (q.x + off.0, q.y + off.1), false);
let a = reshape_anchors(&s, id);
assert_eq!(a.len(), 4, "t {t}, {off:?}");
assert_eq!(reshape_highlights(&mut s), vec![a[1].p], "t {t}, {off:?}");
}
}
}
#[test]
fn reshape_tool_leaves_a_locked_or_hidden_path_alone() {
for command in ["object.lock", "object.hide"] {
let mut s = session();
let id = reshape_tool_on_a_line(&mut s);
let before = reshape_anchors(&s, id);
s.execute(command, &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).ok();
reshape_gesture(&mut s, (420.0, 0.0), (420.0, 0.0), false);
reshape_gesture(&mut s, (420.0, 0.0), (420.0, 60.0), false);
assert_eq!(reshape_anchors(&s, id), before, "{command}");
assert!(reshape_highlights(&mut s).is_empty(), "{command}");
}
}
#[test]
fn graph_tool_drag_creates_a_graph_and_asks_for_data() {
let mut s = session();
+22
View File
@@ -647,6 +647,28 @@ fn edits_change_the_active_row_of_the_first_selected_object() {
assert!(!e.contains("internal error"), "{e}");
}
/// After an aligned Remove Item or Duplicate Item, the active row follows the rows that changed in
/// the first selected object, also when that object paints above the others.
#[test]
fn aligned_remove_and_duplicate_keep_the_active_row_of_the_first_selected_object() {
let mut s = session();
let (_, b) = reversed_pair(&mut s);
run(&mut s, "appearance.setActiveItem", json!({"index": 0})); // b's red fill
// a's row 0 is b's white fill, row 1, so b's red fill stays at row 0.
run(&mut s, "appearance.removeItem", json!({"indices": [0], "aligned": true}));
assert_eq!(node(&s, b).appearance.items.len(), 2);
assert_eq!(s.appearance_item(), Some(0));
assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#ff0000");
let mut s = session();
let (_, b) = reversed_pair(&mut s);
run(&mut s, "appearance.setActiveItem", json!({"index": 1})); // b's white fill, a's row 0
// The copy goes above b's white fill, at 2; the active row stays on the original.
run(&mut s, "appearance.duplicateItem", json!({"indices": [0], "aligned": true}));
assert_eq!(node(&s, b).appearance.items.len(), 4);
assert_eq!(s.appearance_item(), Some(1));
}
/// `effect.apply`'s reply names the new effect by its index in the object whose row `item` is,
/// also when the objects painted after it already have effects there.
#[test]
+100
View File
@@ -1321,6 +1321,106 @@ fn break_link_counts_the_instances_mask_art() {
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "it stays an instance");
}
/// A hidden, a locked and a plain instance of one symbol in a group, the group selected.
fn group_with_hidden_and_locked_instances(s: &mut Session) -> (NodeId, String) {
let (shown, name, _) = make_symbol(s);
let hidden = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap());
let locked = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 100})).unwrap()["id"].as_u64().unwrap());
select(s, &[shown, hidden, locked]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(hidden).unwrap().visible = false;
doc.node_mut(locked).unwrap().locked = true;
select(s, &[group]);
(group, name)
}
/// The visibility and lock state of the children of `group`, in paint order.
fn shown_and_locked(s: &Session, group: NodeId) -> Vec<(bool, bool)> {
let g = node(s, group);
let NodeKind::Group { children, .. } = &g.kind else { panic!("a group: {}", g.kind_label()) };
assert!(children.iter().all(|c| !matches!(c.kind, NodeKind::SymbolInstance { .. })), "every instance is expanded");
children.iter().map(|c| (c.visible, c.locked)).collect()
}
/// Break Link to Symbol on a selected group keeps a hidden instance's art hidden and a locked
/// instance's art locked, and selects only the art that can be selected.
#[test]
fn break_link_keeps_hidden_and_locked_instances_hidden_and_locked() {
let mut s = session();
let (group, _) = group_with_hidden_and_locked_instances(&mut s);
let r = s.execute("symbol.breakLink", &json!({})).unwrap();
assert_eq!(r["ids"].as_array().unwrap().len(), 3, "{r}");
assert_eq!(shown_and_locked(&s, group), vec![(true, false), (false, false), (true, true)]);
let d = &s.doc().unwrap().doc;
let selected: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
assert_eq!(selected.len(), 1, "{selected:?}");
assert!(selected.iter().all(|id| d.node(*id).is_some_and(|n| n.visible && !n.locked)), "{selected:?}");
}
/// Break Link to Symbol on a selected group does not select the art of a shown, unlocked instance
/// that sits in a hidden or a locked group inside it.
#[test]
fn break_link_leaves_art_in_hidden_or_locked_groups_unselected() {
let mut s = session();
let (shown, name, _) = make_symbol(&mut s);
let subgroup = |s: &mut Session, y: i64| {
let id = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": y})).unwrap()["id"].as_u64().unwrap());
select(s, &[id]);
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
};
let hidden = subgroup(&mut s, 200);
let locked = subgroup(&mut s, 100);
select(&mut s, &[shown, hidden, locked]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(hidden).unwrap().visible = false;
doc.node_mut(locked).unwrap().locked = true;
select(&mut s, &[group]);
let r = s.execute("symbol.breakLink", &json!({})).unwrap();
assert_eq!(r["ids"].as_array().unwrap().len(), 3, "{r}");
let d = &s.doc().unwrap().doc;
let selected: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
assert_eq!(selected.len(), 1, "{selected:?}");
let a = d.ancestry(selected[0]).unwrap();
assert!(!a.contains(&hidden) && !a.contains(&locked), "{a:?}");
}
/// Break Link to Symbol on an instance just placed on a locked artboard selects the art that
/// replaces it, which stays new art there. The art of an older instance there, named by id, is not
/// selected.
#[test]
fn break_link_keeps_new_art_on_a_locked_artboard_selected() {
let mut s = session();
let (old, name, _) = make_symbol(&mut s);
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
select(&mut s, &[old]);
s.execute("object.move", &json!({"dx": 1000, "dy": 0})).unwrap();
assert!(s.doc().unwrap().selection.objects.is_empty(), "moved onto the locked artboard");
let inst = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 1100, "y": 100})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [inst], "placed art is selected");
let r = s.execute("symbol.breakLink", &json!({})).unwrap();
let art: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
assert_eq!(art.len(), 1, "{r}");
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), art, "the art that replaces it");
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), art, "the art stays editable");
let r = s.execute("symbol.breakLink", &json!({"ids": [old.0]})).unwrap();
assert_eq!(r["ids"].as_array().unwrap().len(), 1, "{r}");
assert!(s.doc().unwrap().selection.objects.is_empty(), "the older instance's art");
}
/// Delete Symbol, expanding the instances, keeps a hidden instance's art hidden and a locked
/// instance's art locked.
#[test]
fn delete_symbol_keeps_hidden_and_locked_instances_hidden_and_locked() {
let mut s = session();
let (group, name) = group_with_hidden_and_locked_instances(&mut s);
s.execute("symbol.delete", &json!({"name": name})).unwrap();
assert_eq!(shown_and_locked(&s, group), vec![(true, false), (false, false), (true, true)]);
}
#[test]
fn delete_duplicate_and_replace_symbols() {
let mut s = session();
+76
View File
@@ -2380,6 +2380,82 @@ fn add_anchor_point_selects_the_path_it_was_added_to() {
assert!(selected_anchors(&s, kept).is_empty(), "a path selected as a whole stays so");
}
fn path_from(s: &mut Session, d: &str) -> NodeId {
NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap())
}
fn selected_segments(s: &Session, id: NodeId) -> Vec<(usize, usize)> {
s.doc().unwrap().selection.segments.get(&id).map(|set| set.iter().copied().collect()).unwrap_or_default()
}
fn selected_points(s: &Session, id: NodeId) -> Vec<Point> {
let pd = path(s, id);
selected_anchors(s, id).iter().filter_map(|&(si, ai)| pd.subpaths.get(si)?.anchors.get(ai)).map(|a| a.p).collect()
}
#[test]
fn add_anchor_point_keeps_the_same_anchors_selected() {
// The direct-selected anchors after the one added are numbered one higher, so the selection
// stays on the same points; one undo step restores the path and the selection.
let mut s = session();
let id = path_from(&mut s, "M0 0 L70 0 L140 0 L210 0 L280 0 L350 0 L420 0");
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, 5]], "mode": "set"})).unwrap();
let before = selected_points(&s, id);
let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 2, "t": 0.5})).unwrap();
assert_eq!(r["anchor"], 3);
assert_eq!(selected_anchors(&s, id), [(0, 1), (0, 6)], "the anchor at 350 is now number 6");
assert_eq!(selected_points(&s, id), before);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, id).subpaths[0].anchors.len(), 7);
assert_eq!(selected_anchors(&s, id), [(0, 1), (0, 5)]);
}
#[test]
fn add_anchor_point_on_a_selected_segment_keeps_both_halves_and_the_new_anchor_selected() {
let mut s = session();
let id = path_from(&mut s, "M0 0 L70 0 L140 0 L210 0 L280 0 L350 0 L420 0");
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 2], [0, 4]], "mode": "set"})).unwrap();
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 2, "t": 0.5})).unwrap();
assert_eq!(selected_segments(&s, id), [(0, 2), (0, 3), (0, 5)]);
assert_eq!(selected_anchors(&s, id), [(0, 2), (0, 3), (0, 4), (0, 5), (0, 6)], "the new anchor is selected with the segment's ends");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, id).subpaths[0].anchors.len(), 7);
assert_eq!(selected_segments(&s, id), [(0, 2), (0, 4)]);
}
#[test]
fn add_anchor_point_on_the_closing_segment_keeps_it_selected_as_two_halves() {
let mut s = session();
let id = path_from(&mut s, "M0 0 L100 0 L100 100 L0 100 Z");
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 3]], "mode": "set"})).unwrap();
let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 3, "t": 0.5})).unwrap();
assert_eq!(r["anchor"], 4);
assert_eq!(selected_segments(&s, id), [(0, 3), (0, 4)]);
assert_eq!(selected_anchors(&s, id), [(0, 0), (0, 3), (0, 4)]);
assert_eq!(selected_points(&s, id), [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(0.0, 50.0)]);
}
#[test]
fn add_anchor_point_renumbers_only_the_subpath_it_was_added_to() {
let mut s = session();
let id = path_from(&mut s, "M0 0 L100 0 L200 0 M0 100 L100 100 L200 100");
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [1, 1], [1, 2]], "mode": "set"})).unwrap();
let before = selected_points(&s, id);
s.execute("path.insertAnchor", &json!({"id": id.0, "subpath": 1, "segment": 0, "t": 0.5})).unwrap();
assert_eq!(selected_anchors(&s, id), [(0, 2), (1, 2), (1, 3)]);
assert_eq!(selected_points(&s, id), before);
}
#[test]
fn add_anchor_point_with_a_selected_anchor_index_past_the_end_does_not_panic() {
// `select.anchors` takes any index, so a selected one can name no anchor.
let mut s = session();
let id = path_from(&mut s, "M0 0 L70 0 L140 0 L210 0");
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, usize::MAX]], "mode": "set"})).unwrap();
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "t": 0.5})).unwrap();
assert_eq!(selected_anchors(&s, id), [(0, 2), (0, usize::MAX)]);
}
fn selected_anchors(s: &Session, id: NodeId) -> Vec<(usize, usize)> {
s.doc().unwrap().selection.anchors.get(&id).map(|set| set.iter().copied().collect()).unwrap_or_default()
}
+23
View File
@@ -75,6 +75,29 @@ fn symbol_instance_tint_survives_expanding_an_object_effect() {
assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8));
}
/// The canvas tints a symbol's art with the instance fill before the instance's color adjustment,
/// and expanding gives the same colors.
#[test]
fn symbol_instance_tint_comes_before_a_color_adjustment_when_expanded() {
let mut s = session();
square(&mut s);
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Tinted Square"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let fill = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": fill, "color": "#00ff00", "opacity": 50}));
run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}}));
let before = render(&s);
assert_ne!(before.pixel(100, 100), [255, 255, 255, 255], "the symbol is visible");
assert!(expandable(&s));
run(&mut s, "effect.expandAppearance", json!({}));
assert!(!matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }));
let after = render(&s);
let (b, a) = (before.pixel(100, 100), after.pixel(100, 100));
assert!(b.iter().zip(a.iter()).all(|(x, y)| x.abs_diff(*y) <= 8), "expanding changed the color from {b:?} to {a:?}");
assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8));
}
/// An instance fill with an opacity of 0 does not tint the symbol's art, so expanding keeps the
/// art's global swatch link.
#[test]
+25
View File
@@ -350,6 +350,31 @@ fn gradients_rasterize_and_flat_areas_stay_vector() {
}
}
#[test]
fn a_long_rasterized_area_is_placed_whole() {
let _settings = settings_lock();
let mut s = session();
// 5569 pt long: more than the renderer's 32,768 pixels a side at the 64 Mpx limit's scale.
let g = rect(&mut s, 10.0, 10.0, 100.0, 5569.0, "#000000");
run(
&mut s,
"paint.setFill",
json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}),
);
run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40}));
let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "lineArtPpi": 1200, "gradientPpi": 1200}));
assert_eq!(rasterized, 1);
let mut placed = vec![];
node(&s, ids[0]).walk(&mut |c| {
if let NodeKind::Image(im) = &c.kind {
placed.push((im.height, im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)))));
}
});
let [(height, b)] = placed[..] else { panic!("one image: {placed:?}") };
assert!(height <= vectorcraft_render::MAX_RASTER_SIDE, "{height} pixels");
assert!(b.y0 <= 10.0 && b.y1 >= 5579.0, "the image covers the strip: {b:?}");
}
#[test]
fn flatten_says_when_an_image_could_not_be_decoded() {
let _settings = settings_lock();
+25
View File
@@ -368,6 +368,31 @@ fn a_transparent_image_is_flattened_with_the_art_under_it_which_stays() {
assert_eq!(colour_at(page, 10.0, 20.0), [255, 0, 0], "the square outside the image");
}
/// A transparent image longer than the renderer draws at its own resolution (32,768 pixels a
/// side) is flattened whole, at a lower resolution.
#[test]
fn a_long_transparent_image_is_flattened_whole() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 4600})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 4600})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let p = json!({"name": "i.png", "dataBase64": vectorcraft_format::base64_encode(&png(2000, 1600, [0, 0, 0, 128])), "at": [50, 50]});
s.execute("file.place", &p).unwrap();
// 10 × 4500 pt: about 600 ppi, so 37,500 pixels long.
s.execute("object.setBounds", &json!({"x": 10, "y": 10, "width": 10, "height": 4500, "reference": 0})).unwrap();
let before = [colour_at(&s.doc().unwrap().doc, 15.0, 100.0), colour_at(&s.doc().unwrap().doc, 15.0, 4400.0)];
assert!(before.iter().all(|c| c[0] < 200), "the image darkens the red: {before:?}");
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7"})).unwrap();
assert!(warnings(&r).iter().any(|w| w.contains("flattened with the art under them")), "{r}");
s.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap();
let d = &s.doc().unwrap().doc;
let after = [colour_at(d, 15.0, 100.0), colour_at(d, 15.0, 4400.0)];
for (a, b) in before.iter().zip(&after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 3), "{before:?} {after:?}");
}
}
/// A `size`×`size` PNG of a black disk of radius `r` pixels with an anti-aliased edge, clear
/// around it, 72 ppi.
fn disk(size: u32, r: f64) -> Vec<u8> {
+20
View File
@@ -1461,6 +1461,26 @@ fn rasterize_replaces_selection_with_image() {
assert_eq!(selected(&s), vec![img]);
}
/// Rasterize refuses art that would be longer than the renderer draws (32,768 pixels a side), and
/// the art stays as it was; at a resolution that fits, the image covers all of it.
#[test]
fn rasterize_refuses_an_image_longer_than_the_renderer_draws() {
let mut s = session();
let a = rect(&mut s, 10.0, 20.0, 100.0, 5569.0);
sel(&mut s, &[a]);
let vb = s.doc().unwrap().doc.bounds_of(&[a], true).unwrap();
let before = (undo_len(&s), node(&s, a));
let e = s.execute("object.rasterize", &json!({"ppi": 600, "padding": 0})).unwrap_err().to_string();
assert!(e.contains("too large"), "{e}");
assert_eq!((undo_len(&s), node(&s, a)), before);
let img = id_of(&s.execute("object.rasterize", &json!({"ppi": 400, "padding": 0})).unwrap());
let n = node(&s, img);
let NodeKind::Image(im) = &n.kind else { panic!() };
assert!(im.height <= vectorcraft_render::MAX_RASTER_SIDE, "{} pixels", im.height);
let b = n.geometric_bounds().unwrap();
assert!(close(b.y0, vb.y0) && b.y1 >= vb.y1, "{b:?} covers {vb:?}");
}
/// Rasterize refuses a resolution given as text or as another value that is not a number, and the
/// selected art stays as it was.
#[test]
+123 -1
View File
@@ -2,7 +2,7 @@
use serde_json::json;
use vectorcraft_color::{Color, GradientKind, Paint};
use vectorcraft_doc::{AppearanceItem, NodeKind};
use vectorcraft_doc::{AppearanceItem, LayerColor, NodeKind};
use crate::*;
@@ -1387,6 +1387,128 @@ fn artboard_video_display_options_are_set_in_one_undo_step() {
assert_eq!(video(&s, 1), (false, 10.0), "10 is in range");
}
/// Artboard Options' guide label: `artboard.setProps {guideLabel}` takes a layer color's name or
/// `#rrggbb` and null clears it, each change one undo step, also on a locked artboard (whose
/// rectangle stays locked) and for several artboards in one list; a value equal to the artboard's
/// adds no undo step. `artboard.new` takes it, a duplicate and an undone delete keep it, and
/// `inspect_document` reports it. A bad value anywhere in a list changes nothing.
#[test]
fn artboard_guide_labels_are_set_and_cleared_in_one_undo_step() {
let mut s = session();
s.execute("artboard.new", &json!({})).unwrap();
let label = |s: &Session, i: usize| s.doc().unwrap().doc.artboards[i].guide_label;
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
assert_eq!((label(&s, 0), label(&s, 1)), (None, None), "no label by default");
let u0 = undo(&s);
s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "Red"})).unwrap();
assert_eq!((label(&s, 0), label(&s, 1)), (None, Some(LayerColor::Preset(1))), "only that artboard");
s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "#12aBcd"})).unwrap();
assert_eq!(label(&s, 1), Some(LayerColor::Custom([0x12, 0xab, 0xcd])));
s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": null})).unwrap();
assert_eq!(label(&s, 1), None, "null clears it");
assert_eq!(undo(&s), u0 + 3, "one undo step each");
for was in [Some(LayerColor::Custom([0x12, 0xab, 0xcd])), Some(LayerColor::Preset(1)), None] {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(label(&s, 1), was);
}
s.execute("edit.redo", &json!({})).unwrap();
// The same label again, or a list that changes nothing: no undo step.
let u = undo(&s);
s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "Red"})).unwrap();
s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": null}, {"index": 1, "guideLabel": "Red"}]})).unwrap();
assert_eq!(undo(&s), u, "nothing changed, no undo step");
// A locked artboard takes a label; its rectangle stays locked.
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
let rect0 = s.doc().unwrap().doc.artboards[0].rect;
s.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Gold"})).unwrap();
assert_eq!(label(&s, 0), Some(LayerColor::Preset(15)));
assert!(s.execute("artboard.setProps", &json!({"index": 0, "x": 999, "guideLabel": "Teal"})).is_err());
assert_eq!((s.doc().unwrap().doc.artboards[0].rect, label(&s, 0)), (rect0, Some(LayerColor::Preset(15))));
let u = undo(&s);
s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Teal"}, {"index": 1, "guideLabel": "#000000"}]})).unwrap();
assert_eq!((label(&s, 0), label(&s, 1)), (Some(LayerColor::Preset(11)), Some(LayerColor::Custom([0, 0, 0]))), "each its own");
assert_eq!(undo(&s), u + 1, "in one undo step");
let doc = crate::inspect::document(&s);
assert_eq!((doc["artboards"][0]["guideLabel"].clone(), doc["artboards"][1]["guideLabel"].clone()), (json!("Teal"), json!("#000000")));
s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": null})).unwrap();
assert!(crate::inspect::document(&s)["artboards"][1].get("guideLabel").is_none(), "no label isn't reported");
let copy = s.execute("artboard.duplicate", &json!({"index": 0})).unwrap()["index"].as_u64().unwrap() as usize;
assert_eq!(label(&s, copy), Some(LayerColor::Preset(11)), "a duplicate keeps it");
let made = s.execute("artboard.new", &json!({"guideLabel": "Violet"})).unwrap()["index"].as_u64().unwrap() as usize;
assert_eq!(label(&s, made), Some(LayerColor::Preset(14)), "a new artboard takes it");
let plain = s.execute("artboard.new", &json!({})).unwrap()["index"].as_u64().unwrap() as usize;
assert_eq!(label(&s, plain), None);
s.execute("artboard.delete", &json!({"index": made})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(label(&s, made), Some(LayerColor::Preset(14)), "undoing a delete brings it back");
let before = s.doc().unwrap().doc.clone();
let bads = [
json!("red"),
json!(" Red"),
json!("#12345"),
json!("#1234567"),
json!("#12345678"),
json!("#fff"),
json!("#gg0000"),
json!(1),
json!([1, 2, 3]),
json!({"Preset": 1}),
json!(true),
];
for bad in bads {
assert!(s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": bad})).is_err(), "{bad}");
assert!(s.execute("artboard.new", &json!({"guideLabel": bad})).is_err(), "{bad}");
assert!(
s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Red"}, {"index": 1, "guideLabel": bad}]})).is_err(),
"{bad}"
);
}
assert!(s.execute("artboard.setProps", &json!({"artboards": [{"index": 1, "guideLabel": "Red"}, {"index": 1, "guideLabel": "Red"}]})).is_err());
assert!(s.execute("artboard.setProps", &json!({"artboards": [{"index": 1, "guideLabel": "Red"}, {"index": 99, "guideLabel": "Red"}]})).is_err());
assert_eq!(*s.doc().unwrap().doc, *before, "a bad value changes nothing");
}
/// The native format keeps the guide label, as `{"Preset": n}` or `{"Custom": [r, g, b]}`. An
/// artboard without one is written as before labels could be set, and a preset outside the layer
/// colors in a file reads as no label. Exports leave the label out.
#[test]
fn artboard_guide_labels_round_trip_through_the_native_format() {
let mut s = session();
rect(&mut s);
s.execute("artboard.new", &json!({})).unwrap();
let save = |s: &Session| vectorcraft_format::save(&s.doc().unwrap().doc, false);
let before = save(&s);
let plain = (*s.doc().unwrap().doc).clone();
s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Green"}, {"index": 1, "guideLabel": "#102030"}]})).unwrap();
let bytes = save(&s);
let saved: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let ab = |i: usize| saved["document"]["artboards"][i]["guide_label"].clone();
assert_eq!((ab(0), ab(1)), (json!({"Preset": 2}), json!({"Custom": [16, 32, 48]})));
let back = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(back.artboards, s.doc().unwrap().doc.artboards);
// Screen-only: SVG and PDF exports are the same as without the labels.
let on = (*s.doc().unwrap().doc).clone();
assert_eq!(vectorcraft_svg::export(&on, &Default::default()), vectorcraft_svg::export(&plain, &Default::default()));
let options = vectorcraft_pdf::PdfOptions { created: Some(0), ..Default::default() };
assert_eq!(crate::export_pdf(&on, &options).unwrap(), crate::export_pdf(&plain, &options).unwrap());
s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": null}, {"index": 1, "guideLabel": null}]})).unwrap();
assert_eq!(save(&s), before, "without labels, the file is as it was");
// A file's labels as another writer might put them: a preset past the layer colors reads as
// none, and a label that isn't a layer color at all is refused.
let mut edited = saved.clone();
edited["document"]["artboards"][0]["guide_label"] = json!({"Preset": 27});
edited["document"]["artboards"][1]["guide_label"] = json!({"Preset": 26});
let back = vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).unwrap();
assert_eq!((back.artboards[0].guide_label, back.artboards[1].guide_label), (None, Some(LayerColor::Preset(26))));
for bad in [json!({"Preset": 256}), json!({"Custom": [1, 2]}), json!("Red"), json!({"Custom": [1, 2, 300]})] {
edited["document"]["artboards"][0]["guide_label"] = bad.clone();
assert!(vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).is_err(), "{bad}");
}
edited["document"]["artboards"][0]["guide_label"] = json!(null);
let back = vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).unwrap();
assert_eq!(back.artboards[0].guide_label, None);
}
/// The native format keeps Show Video Safe Areas and the Video Ruler Pixel Aspect Ratio. A
/// document whose artboards hide the safe areas and have square pixels is written byte for byte as
/// before they could be set, a file written without the two keys opens with the safe areas off
+168
View File
@@ -980,6 +980,174 @@ fn painted_pieces_keep_to_the_effects_budget() {
assert!((350..=100_000).contains(&paths), "{paths} paths");
}
/// A clock for a document's deferrals that reads `step` milliseconds later each time it is read;
/// the test changes the step as it goes.
fn stepping_clock(step: &std::sync::Arc<std::sync::atomic::AtomicU64>) -> vectorcraft_plugins::deferred::Clock {
let (now, step) = (std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)), step.clone());
std::sync::Arc::new(move || Some(now.fetch_add(step.load(std::sync::atomic::Ordering::Relaxed), std::sync::atomic::Ordering::Relaxed)))
}
/// While a document is drawn on screen, the plug-in effects of its first view share a time budget.
/// A stage left out draws its input art, is listed by `effect.deferredStatus`, and stays left out
/// on later drawings; Effect › Refresh Deferred Effects runs it again with a fresh budget, and an
/// export draws every stage. Another document has a budget of its own.
#[test]
fn the_first_view_defers_plug_in_effects_past_its_budget() {
let mut s = session();
let a = rect(&mut s, 10.0, "#ff0000");
let b = rect(&mut s, 30.0, "#ff0000");
for (id, x) in [("test.engine.deferred.a", 100.0), ("test.engine.deferred.b", 140.0)] {
let out = json!({"objects": [{"path": square_at(x)}]}).to_string();
install_wat(&mut s, &tpl::returning(&tpl::manifest(id, "effect", "{}"), &out));
}
run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.deferred.a"}));
run(&mut s, "effect.apply", json!({"ids": [b.0], "effect": "plugin.test.engine.deferred.b"}));
// Each reading is 3 s later: the first run's result comes back after the budget, and the
// second run doesn't start.
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
s.doc_mut().unwrap().plugin_effects = fx.clone();
let img = fx.view(|| drawn(&s));
fx.first_view_done();
assert_eq!((img.pixel(15, 15), img.pixel(35, 15), img.pixel(110, 50), img.pixel(150, 50)), (RED, RED, WHITE, WHITE), "the input art");
assert_eq!(fx.take_report(), Some(2));
let status = run(&mut s, "effect.deferredStatus", json!({}));
let listed = |id: NodeId, plugin: &str| json!({"objectId": id.0, "effectIndex": 0, "pluginId": plugin, "reason": "budget"});
assert_eq!(status, json!({"budgetMs": 2000, "effects": [listed(a, "test.engine.deferred.a"), listed(b, "test.engine.deferred.b")]}));
assert_eq!(fx.view(|| drawn(&s)).pixel(110, 50), WHITE, "a later drawing leaves it deferred");
// Refreshed with a fresh budget, in which the clock stands still.
assert!(s.execute("effect.refreshDeferred", &json!({"ids": ["a"]})).is_err());
assert!(s.execute("effect.refreshDeferred", &json!({"ids": [999_999]})).is_err(), "not an object of the document");
step.store(0, std::sync::atomic::Ordering::Relaxed);
let refreshed = run(&mut s, "effect.refreshDeferred", json!({"ids": [a.0]}));
assert_eq!(refreshed, json!({"refreshed": 1, "stillDeferred": 0, "failed": 0}));
let img = fx.view(|| drawn(&s));
assert_eq!((img.pixel(110, 50), img.pixel(150, 50)), (RED, WHITE));
assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([listed(b, "test.engine.deferred.b")]));
// An export draws every stage; the view then uses the result.
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
assert!(svg.contains(r#"<rect x="140" y="40" width="20" height="20""#), "the square at 140: {svg}");
assert_eq!(fx.view(|| drawn(&s)).pixel(150, 50), RED);
assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([]));
assert!(s.execute("effect.refreshDeferred", &json!({})).is_err(), "nothing is deferred");
// Another document: its first view has a budget of its own.
let mut other = session();
let c = rect(&mut other, 50.0, "#ff0000");
let out = json!({"objects": [{"path": square_at(170.0)}]}).to_string();
install_wat(&mut other, &tpl::returning(&tpl::manifest("test.engine.deferred.c", "effect", "{}"), &out));
run(&mut other, "effect.apply", json!({"ids": [c.0], "effect": "plugin.test.engine.deferred.c"}));
let still = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
let fx_c = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&still));
other.doc_mut().unwrap().plugin_effects = fx_c.clone();
assert_eq!(fx_c.view(|| drawn(&other)).pixel(180, 50), RED);
fx_c.first_view_done();
assert_eq!(fx_c.take_report(), Some(0));
}
/// Deferred stages are listed where their effects are: after an effect that changes no geometry,
/// and on a fill after a Transform effect that reaches its appearance, each of two instances of
/// one plug-in at its own place.
#[test]
fn deferred_stages_are_listed_at_their_effects_places() {
let mut s = session();
let a = rect(&mut s, 10.0, "#ff0000");
let b = rect(&mut s, 60.0, "#ff0000");
let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string();
// An effect that paints its pieces: the object is drawn from its reshaped art.
install_wat(&mut s, &tpl::returning(&painting("test.engine.deferred.at", true), &out));
const FX: &str = "plugin.test.engine.deferred.at";
run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "stylize.dropShadow"}));
for _ in 0..2 {
run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": FX}));
}
run(&mut s, "effect.apply", json!({"ids": [b.0], "effect": "distort.transform", "params": {"strokes": true}, "item": 0}));
for _ in 0..2 {
run(&mut s, "effect.apply", json!({"ids": [b.0], "effect": FX, "item": 0}));
}
// No run has time to give a result.
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
s.doc_mut().unwrap().plugin_effects = fx.clone();
fx.view(|| drawn(&s));
let places = run(&mut s, "effect.deferredStatus", json!({}))["effects"]
.as_array()
.unwrap()
.iter()
.map(|e| (e["objectId"].as_u64().unwrap(), e["item"].as_u64(), e["effectIndex"].as_u64().unwrap()))
.collect::<Vec<_>>();
assert_eq!(places, [(a.0, None, 1), (a.0, None, 2), (b.0, Some(0), 1), (b.0, Some(0), 2)]);
}
/// A refresh that does not draw a stage (its object, or a group holding it, is hidden) leaves it
/// deferred, and a stage whose effect has been removed or hidden, or whose object has been removed,
/// is no longer listed and does not enable Effect › Refresh Deferred Effects.
#[test]
fn refresh_keeps_stages_it_did_not_draw_and_drops_removed_ones() {
let mut s = session();
let a = rect(&mut s, 10.0, "#ff0000");
let b = rect(&mut s, 30.0, "#ff0000");
let c = rect(&mut s, 50.0, "#ff0000");
let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string();
install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.kept", "effect", "{}"), &out));
run(&mut s, "effect.apply", json!({"ids": [a.0, b.0, c.0], "effect": "plugin.test.engine.deferred.kept"}));
run(&mut s, "select.set", json!({"ids": [c.0]}));
let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
s.doc_mut().unwrap().plugin_effects = fx.clone();
fx.view(|| drawn(&s));
fx.first_view_done();
let listed = |s: &mut Session| {
run(s, "effect.deferredStatus", json!({}))["effects"].as_array().unwrap().iter().map(|e| e["objectId"].as_u64().unwrap()).collect::<Vec<_>>()
};
assert_eq!(listed(&mut s), [a.0, b.0, c.0]);
s.execute("object.hide", &json!({"ids": [a.0, g.0]})).unwrap();
step.store(0, std::sync::atomic::Ordering::Relaxed);
let refreshed = run(&mut s, "effect.refreshDeferred", json!({"ids": [a.0, c.0]}));
assert_eq!(refreshed, json!({"refreshed": 0, "stillDeferred": 2, "failed": 0}), "a hidden object is not drawn");
assert_eq!(listed(&mut s), [a.0, b.0, c.0]);
run(&mut s, "effect.remove", json!({"ids": [a.0], "index": 0}));
assert_eq!(listed(&mut s), [b.0, c.0], "its effect was removed");
run(&mut s, "effect.setParams", json!({"ids": [b.0], "index": 0, "visible": false}));
assert_eq!(listed(&mut s), [c.0], "its effect was hidden");
s.execute("edit.clear", &json!({"ids": [b.0, g.0]})).unwrap();
assert_eq!(listed(&mut s), Vec::<u64>::new(), "its object was deleted");
assert!(s.execute("effect.refreshDeferred", &json!({})).is_err(), "nothing is deferred");
}
/// A deferred stage in a symbol's art is listed by the object in that art, and a refresh runs it
/// where the symbol is placed.
#[test]
fn deferred_stages_in_symbol_art_are_listed_and_refreshed() {
let mut s = session();
let a = rect(&mut s, 10.0, "#ff0000");
let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string();
install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.symbol", "effect", "{}"), &out));
run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.deferred.symbol"}));
run(&mut s, "select.set", json!({"ids": [a.0]}));
let instance = run(&mut s, "symbol.new", json!({"name": "Deferred"}))["id"].as_u64().unwrap();
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
s.doc_mut().unwrap().plugin_effects = fx.clone();
fx.view(|| drawn(&s));
fx.first_view_done();
assert_eq!(fx.take_report(), Some(1));
let effects = run(&mut s, "effect.deferredStatus", json!({}))["effects"].clone();
let object = effects[0]["objectId"].as_u64().unwrap();
assert_eq!(effects.as_array().map(Vec::len), Some(1), "{effects}");
assert!(object != instance && s.doc().unwrap().doc.node(NodeId(object)).is_none(), "an object of the symbol's art: {effects}");
step.store(0, std::sync::atomic::Ordering::Relaxed);
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0}));
assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([]));
}
/// `CRAFT_PLUGIN_PAINTS_WASM=<folder>` saves a test live effect to try in the app
/// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its
/// object's stroke is 5 pt wide, and hands the geometry back otherwise.
+22
View File
@@ -130,6 +130,28 @@ fn print_as_bitmap_prints_an_image_of_each_artboard() {
assert!(crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().is_none());
}
/// Print as Bitmap of an artboard longer than the renderer draws at the raster effects resolution
/// (32,768 pixels a side) prints an image of all of it, at a lower resolution.
#[test]
fn print_as_bitmap_prints_all_of_a_long_artboard() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 9000, "height": 100})).unwrap();
s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 9000, "height": 100})).unwrap();
let set = settings(json!({"advanced": {"printAsBitmap": true}}));
let saved = s.prefs.flattener_presets.clone();
let bitmap = crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().unwrap();
let mut placed = vec![];
bitmap.walk(|n| {
if let NodeKind::Image(im) = &n.kind {
placed.push((im.width, im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)))));
}
});
let [(width, b)] = placed[..] else { panic!("one image: {placed:?}") };
assert!(width <= vectorcraft_render::MAX_RASTER_SIDE, "{width} pixels");
assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}");
}
/// Appearance of Black › Printing / Exporting (#394): Print as Bitmap draws pure CMYK black as RGB
/// black when `rich_black` is on.
#[test]
+289
View File
@@ -0,0 +1,289 @@
//! `alert`, `confirm` and `prompt` in a script: their arguments and results, the answers a run with
//! nobody to ask takes from `answers`, the wait in the app, Stop, and the report's `dialogs`.
use serde_json::{Value, json};
use crate::script::{DialogAnswer, DialogKind, ScriptDialog, dialogs};
use crate::*;
/// One open document with one rectangle.
fn one_doc() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
s
}
fn art(s: &Session) -> (String, usize) {
let d = &s.documents()[0];
(format!("{:?}", d.doc.layers), d.history.undo.len())
}
fn headless(s: &mut Session, source: &str, answers: Value) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "d.js", "answers": answers}))
}
/// A run in the app of `source`, one slice in.
fn framed(s: &mut Session, source: &str) {
s.script_frames = true;
assert_eq!(s.execute("script.run", &json!({"source": source, "name": "d.js"})).unwrap()["running"], true);
assert!(s.script_pump().is_none());
}
/// Pumps the run in the app until it ends or waits at a dialog (`None`).
fn pump(s: &mut Session) -> Option<Result<Value>> {
for _ in 0..10_000 {
if s.script_dialog().is_some() {
return None;
}
if let Some(r) = s.script_pump() {
return Some(r);
}
}
panic!("the run neither ended nor waited");
}
fn answers(list: &[Value]) -> Value {
Value::Array(list.to_vec())
}
#[test]
fn notification_signatures_and_returns() {
let mut s = one_doc();
let source = "vc.log(typeof alert('a')); alert(42, 'Title', 1);\
vc.log(confirm('c')); vc.log(confirm('n', true, undefined));\
vc.log(prompt('p', 'pre')); vc.log(prompt({toString: function () { return 'own'; }}, '', 'T'));";
let r = headless(
&mut s,
source,
answers(&[
json!({"kind": "alert", "value": "ok"}),
json!({"kind": "alert", "value": "ok"}),
json!({"kind": "confirm", "value": true}),
json!({"kind": "confirm", "value": false}),
json!({"kind": "prompt", "value": "typed"}),
json!({"kind": "prompt", "value": null}),
]),
)
.unwrap();
assert_eq!(r["log"], json!(["undefined", true, false, "typed", null]), "{r}");
assert_eq!(
r["dialogs"],
json!([
{"kind": "alert", "message": "a", "title": "Script Alert", "errorIcon": false, "answer": "ok"},
{"kind": "alert", "message": "42", "title": "Title", "errorIcon": true, "answer": "ok"},
{"kind": "confirm", "message": "c", "title": "Script Alert", "noAsDefault": false, "answer": true},
{"kind": "confirm", "message": "n", "title": "Script Alert", "noAsDefault": true, "answer": false},
{"kind": "prompt", "message": "p", "title": "Script Alert", "preset": "pre", "answer": "typed"},
{"kind": "prompt", "message": "own", "title": "T", "preset": "", "answer": null},
])
);
assert_eq!((r["dialogCount"].clone(), r["dialogsTruncated"].clone()), (json!(6), json!(false)));
let has = headless(&mut s, "vc.log(vc.api.has('dialogs'));", json!([])).unwrap();
assert_eq!(has["log"], json!([true]));
}
#[test]
fn headless_answers_follow_call_order() {
let mut s = one_doc();
let source = "var out = []; [1, 2].forEach(function (i) { out.push(confirm('q' + i)); }); out.push(prompt('r', 'x')); vc.log(out.join());";
let r = headless(
&mut s,
source,
answers(&[json!({"kind": "confirm", "value": false}), json!({"kind": "confirm", "value": true}), json!({"kind": "prompt", "value": "z"})]),
)
.unwrap();
assert_eq!(r["log"], json!(["false,true,z"]), "a callback of a built-in takes its answer too: {r}");
assert_eq!(headless(&mut s, "1", json!({})).unwrap()["dialogCount"], 0, "an empty object is an empty list");
}
#[test]
fn missing_or_mismatched_answer_rolls_back() {
let mut s = one_doc();
let before = art(&s);
let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});";
for (source, given, says) in [
(format!("{edit} try {{ alert('x'); }} catch (e) {{ vc.log('caught'); }}"), json!([]), "no answer left"),
(format!("{edit} alert('x');"), answers(&[json!({"kind": "confirm", "value": true})]), "is for confirm, not alert"),
(format!("{edit} alert('x');"), answers(&[json!({"kind": "alert", "value": "ok"}), json!({"kind": "alert", "value": "ok"})]), "1 answer"),
] {
let e = headless(&mut s, &source, given).unwrap_err().to_string();
assert!(e.contains(says), "{e}");
assert_eq!(art(&s), before, "{source}");
let report = s.script_report().unwrap();
assert_eq!(report["kind"], "limit", "{report}");
assert_eq!(report["log"], json!([]), "a missing answer cannot be caught");
assert_eq!(report["dialogCount"], 1);
}
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "ok");
headless(&mut s, "alert('x')", json!([])).unwrap_err();
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing");
}
#[test]
fn invalid_answers_are_rejected_before_run() {
let mut s = one_doc();
let before = art(&s);
let many: Vec<Value> = (0..=dialogs::MAX_ANSWERS).map(|_| json!({"kind": "alert", "value": "ok"})).collect();
let big: Vec<Value> = (0..80).map(|_| json!({"kind": "prompt", "value": "x".repeat(16_000)})).collect();
for given in [
json!({"a": 1}),
json!("ok"),
json!([1]),
json!([{"kind": "alert"}]),
json!([{"kind": "alert", "value": true}]),
json!([{"kind": "confirm", "value": "yes"}]),
json!([{"kind": "prompt", "value": 3}]),
json!([{"kind": "prompt", "value": "x".repeat(dialogs::MAX_PROMPT_BYTES + 1)}]),
json!([{"kind": "other", "value": "ok"}]),
json!([{"kind": "alert", "value": "ok", "extra": 1}]),
Value::Array(many),
Value::Array(big),
] {
let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});";
let r = s.execute("script.run", &json!({"source": source, "answers": given}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
assert_eq!(art(&s), before);
}
s.script_frames = true;
let r = s.execute("script.run", &json!({"source": "1", "answers": [{"kind": "alert", "value": "ok"}]}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "a run in the app takes no answers: {r:?}");
assert!(!s.script_running());
}
#[test]
fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() {
let mut s = one_doc();
framed(
&mut s,
"vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); var a = confirm('Go?', true, 'Ask'); var b = prompt('Name', 'n'); vc.log([a, b]);",
);
let want = ScriptDialog {
kind: DialogKind::Confirm,
message: "Go?".into(),
title: Some("Ask".into()),
error_icon: false,
no_as_default: true,
preset: String::new(),
};
assert_eq!(s.script_dialog(), Some(want));
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
assert!(s.script_answer(DialogAnswer::Confirm(true)));
assert!(!s.script_answer(DialogAnswer::Confirm(true)), "nothing waits until the run goes on");
assert!(pump(&mut s).is_none());
assert_eq!(s.script_dialog().unwrap().preset, "n");
assert!(!s.script_answer(DialogAnswer::Prompt(Some("x".repeat(dialogs::MAX_PROMPT_BYTES + 1)))));
assert!(s.script_answer(DialogAnswer::Prompt(Some("Ann".into()))));
let r = pump(&mut s).unwrap().unwrap();
assert_eq!(r["log"], json!([[true, "Ann"]]));
assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a finished run is one undo step");
assert_eq!(r["dialogs"][1]["answer"], "Ann");
}
#[test]
fn prompt_cancel_returns_null() {
let mut s = one_doc();
framed(&mut s, "vc.log(prompt('Name', '') === null);");
assert!(s.script_answer(DialogAnswer::Prompt(None)));
assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([true]));
}
#[test]
fn dialog_loop_stops_or_exhausts() {
let mut s = one_doc();
let before = art(&s);
let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); while (1) { alert('x'); }";
let three: Vec<Value> = (0..3).map(|_| json!({"kind": "alert", "value": "ok"})).collect();
let e = headless(&mut s, source, Value::Array(three)).unwrap_err().to_string();
assert!(e.contains("no answer left"), "{e}");
assert_eq!(s.script_report().unwrap()["dialogCount"], 4);
assert_eq!(art(&s), before);
framed(&mut s, source);
for _ in 0..3 {
assert!(s.script_answer(DialogAnswer::Ok));
assert!(pump(&mut s).is_none());
}
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
assert_eq!(s.script_dialog(), None, "a run asked to stop no longer waits");
assert!(!s.script_answer(DialogAnswer::Ok));
assert!(s.script_pump().unwrap().is_err());
let report = s.script_report().unwrap();
assert_eq!((report["kind"].as_str(), report["dialogCount"].as_u64()), (Some("stopped"), Some(4)), "{report}");
assert_eq!(report["dialogs"][3]["answer"], "stop");
assert_eq!(art(&s), before, "Stop at the first or any later dialog leaves no undo step");
framed(&mut s, source);
assert!(s.script_abandon(), "quitting while a dialog waits abandons the run");
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "stop");
assert_eq!(art(&s), before);
}
#[test]
fn dialog_text_limits_and_controls() {
let mut s = one_doc();
let source = format!(
"var out = [];\
function t(f) {{ try {{ f(); out.push('opened'); }} catch (e) {{ out.push(e.name); }} }}\
t(function () {{ alert('x'); }});\
t(function () {{ alert(new Array({m}).join('m')); }});\
t(function () {{ alert('m', new Array({t}).join('t')); }});\
t(function () {{ prompt('m', new Array({m}).join('p')); }});\
t(function () {{ alert(); }});\
t(function () {{ prompt('m'); }});\
t(function () {{ alert({{toString: function () {{ throw new Error('no'); }}}}); }});\
t(function () {{ alert(undefined); }});\
vc.log(out.join());",
m = dialogs::MAX_MESSAGE_BYTES + 2,
t = dialogs::MAX_TITLE_BYTES + 2,
);
let r = headless(&mut s, &source, answers(&[json!({"kind": "alert", "value": "ok"}), json!({"kind": "alert", "value": "ok"})])).unwrap();
assert_eq!(r["log"], json!(["opened,RangeError,RangeError,RangeError,TypeError,TypeError,Error,opened"]), "{r}");
assert_eq!(r["dialogs"][1]["message"], "undefined", "an explicit undefined message is a message");
assert_eq!(dialogs::shown_text("a\r\nb\rc\nd\te\u{7}\u{7f}", true), "a\nb\nc\nd\u{2409}e\u{2407}\u{2421}");
assert_eq!(dialogs::shown_text("a\nb", false), "a\u{240a}b", "a title stays on one line");
assert_eq!(dialogs::cut_to("aé", 2), "a", "a cut keeps whole characters");
}
#[test]
fn dialog_transcript_on_success_and_failure() {
let mut s = one_doc();
let r = headless(&mut s, "alert('one'); throw new Error('later');", answers(&[json!({"kind": "alert", "value": "ok"})])).unwrap_err();
assert!(r.to_string().contains("later"));
let report = s.script_report().unwrap();
assert_eq!(report["dialogs"], json!([{"kind": "alert", "message": "one", "title": "Script Alert", "errorIcon": false, "answer": "ok"}]));
let ok = headless(&mut s, "1", json!([])).unwrap();
assert_eq!((ok["dialogs"].clone(), ok["dialogCount"].clone()), (json!([]), json!(0)));
}
#[test]
fn dialog_wait_does_not_spend_fuel() {
let mut s = one_doc();
framed(&mut s, "alert('x'); 1");
for _ in 0..20 {
assert!(s.script_pump().is_none(), "the run waits");
}
assert!(s.script_answer(DialogAnswer::Ok));
let r = pump(&mut s).unwrap().unwrap();
let mut t = one_doc();
let plain = headless(&mut t, "alert('x'); 1", answers(&[json!({"kind": "alert", "value": "ok"})])).unwrap();
assert_eq!((r["fuelUsed"].clone(), r["hostCalls"].clone()), (plain["fuelUsed"].clone(), plain["hostCalls"].clone()), "{r}");
}
#[test]
fn second_run_is_busy_while_dialog_waits() {
let mut s = one_doc();
framed(&mut s, "alert('x');");
assert!(s.execute("script.run", &json!({"source": "1"})).is_err());
assert!(s.script_dialog().is_some(), "the first run still waits");
assert!(s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 1, "height": 1})).is_err(), "edits are refused while it waits");
}
#[test]
fn a_dialog_in_a_callback_throws_in_the_app() {
let mut s = one_doc();
s.script_frames = true;
let source = "var m = ''; [1].forEach(function () { try { alert('x'); } catch (e) { m = e.message; } }); vc.log(m);";
s.execute("script.run", &json!({"source": source})).unwrap();
let r = pump(&mut s).unwrap().unwrap();
assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}");
assert_eq!(r["dialogCount"], 0);
}
+324
View File
@@ -0,0 +1,324 @@
//! The Scripts folder: what a listing holds and leaves out, its order and labels, its limits, the
//! read of a listed script, `script.listInstalled` and the automation read root.
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde_json::json;
use crate::script::folder::{self, Entry, Limits, Listing};
use crate::*;
/// A fresh folder for the files of test `name`, holding an empty `Scripts` folder.
fn folder(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("vc-script-folder-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("Scripts")).unwrap();
dir
}
/// Writes the empty file `name` (folders included) under `root`.
fn touch(root: &Path, name: &str) -> PathBuf {
let path = root.join(name);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "").unwrap();
path
}
/// Makes `link` lead to the folder `target`: a symbolic link, or on Windows a junction, which needs
/// no privilege.
fn link_folder(target: &Path, link: &Path) {
#[cfg(unix)]
std::os::unix::fs::symlink(target, link).unwrap();
#[cfg(windows)]
{
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().unwrap();
assert!(made.status.success(), "mklink /J: {}", String::from_utf8_lossy(&made.stderr));
}
}
/// A listing's rows as text: `label`, or `label/` followed by the folder's rows in brackets.
fn rows(entries: &[Entry]) -> String {
let row = |e: &Entry| match e {
Entry::Script { label, .. } => label.clone(),
Entry::Folder { label, entries } => format!("{label}/[{}]", rows(entries)),
};
entries.iter().map(row).collect::<Vec<_>>().join(", ")
}
/// A listing within `limits` that takes no time.
fn list(root: &Path, limits: Limits) -> Listing {
folder::list_with(root, &limits, &mut || Duration::ZERO)
}
#[test]
fn scripts_and_subfolders_are_listed_by_name_without_the_extension() {
let dir = folder("names");
let root = dir.join("Scripts");
for name in
["b.js", "A.JSX", "Dessin (été) #1.jsx", "v1.2 draft.Js", "Zeta/inner.jsx", "Zeta/Deep/x.js", "notes.txt", "x.jsxbin", "lib.jsxinc", "js"]
{
touch(&root, name);
}
std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap();
let listing = folder::list(&root);
assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]");
assert!(!listing.truncated && !listing.unreadable);
// Each script keeps the path the folder gave, whatever its label.
let paths: Vec<_> =
listing.scripts().into_iter().map(|(folders, label, path)| (folders.join("/"), label.to_string(), path.to_path_buf())).collect();
assert_eq!(paths[0], (String::new(), "A".to_string(), root.join("A.JSX")));
assert_eq!(paths[4], ("Zeta/Deep".to_string(), "x".to_string(), root.join("Zeta").join("Deep").join("x.js")));
assert_eq!(paths.len(), 6);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_script_whose_label_another_row_has_shows_its_whole_file_name() {
let dir = folder("same");
let root = dir.join("Scripts");
for name in ["tidy.js", "tidy.jsx", "tidy.js.js", "tidy/x.js", "alone.jsx"] {
touch(&root, name);
}
// `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name.
assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut() {
let dir = folder("escapes");
let root = dir.join("Scripts");
// A right-to-left override, which would show the name backwards.
touch(&root, "a\u{202E}sj.js");
let long = "n".repeat(200);
touch(&root, &format!("{long}.jsx"));
let listing = folder::list(&root);
let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect();
assert_eq!(labels[0], "a\\u{202E}sj");
assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1)));
assert!(folder::holds(&root, &root.join(format!("{long}.jsx"))));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn hidden_names_and_links_are_left_out() {
let dir = folder("hidden");
let root = dir.join("Scripts");
touch(&root, "shown.js");
touch(&root, ".hidden.js");
touch(&root, ".git/hook.js");
let outside = touch(&dir, "Outside/secret.js");
// A link out of the folder, and one back to the folder itself.
link_folder(outside.parent().unwrap(), &root.join("Out"));
link_folder(&root, &root.join("Loop"));
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, root.join("linked.js")).unwrap();
#[cfg(windows)]
{
let marked = touch(&root, "marked.js");
assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success());
}
let listing = folder::list(&root);
assert_eq!(rows(&listing.entries), "shown");
assert!(!listing.truncated && !listing.unreadable);
// Nor is a file behind a link read as a listed script.
assert!(folder::read(&root, &root.join("shown.js"), 10).is_some());
for path in [root.join("Out").join("secret.js"), root.join("Loop").join("shown.js"), root.join(".hidden.js"), root.join("linked.js")] {
assert!(folder::read(&root, &path, 10).is_none(), "{}", path.display());
}
// A script, or the folder it is in, that Windows marks hidden after a listing is not read.
#[cfg(windows)]
{
assert!(folder::read(&root, &root.join("marked.js"), 10).is_none());
let inner = touch(&root, "Sub/inner.js");
assert!(folder::read(&root, &inner, 10).is_some());
assert!(std::process::Command::new("attrib").arg("+h").arg(root.join("Sub")).status().unwrap().success());
assert!(folder::read(&root, &inner, 10).is_none());
}
let _ = std::fs::remove_dir_all(root.join("Out"));
let _ = std::fs::remove_dir_all(root.join("Loop"));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreadable() {
let dir = folder("root");
let root = dir.join("Scripts");
touch(&root, "a.js");
assert_eq!(folder::list(&dir.join("None")), Listing::default());
let file = touch(&dir, "file");
assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() });
let link = dir.join("Link");
link_folder(&root, &link);
assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() });
assert!(folder::read(&link, &link.join("a.js"), 10).is_none());
let _ = std::fs::remove_dir_all(&link);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn each_limit_stops_a_listing_with_what_it_found() {
let dir = folder("limits");
let root = dir.join("Scripts");
for n in 0..10 {
touch(&root, &format!("s{n}.js"));
}
let all = Limits::default();
let entries = list(&root, Limits { entries: 4, ..all });
assert_eq!((entries.scripts().len(), entries.truncated), (4, true));
let scripts = list(&root, Limits { scripts: 3, ..all });
assert_eq!((scripts.scripts().len(), scripts.truncated), (3, true));
// The clock passes the time limit at the third entry.
let mut calls = 0;
let timed = folder::list_with(&root, &all, &mut || {
calls += 1;
if calls > 2 { all.time + Duration::from_millis(1) } else { Duration::ZERO }
});
assert_eq!((timed.scripts().len(), timed.truncated), (2, true));
let whole = list(&root, all);
assert_eq!((whole.scripts().len(), whole.truncated), (10, false));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() {
let dir = folder("depth");
let root = dir.join("Scripts");
touch(&root, "1/2/3/4/kept.js");
touch(&root, "1/2/3/4/5/deeper.js");
let listing = folder::list(&root);
assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]");
assert!(listing.truncated);
assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js")));
assert!(!folder::holds(&root, &root.join("1/2/3/4/5/deeper.js")));
let two = folder("folders");
let root = two.join("Scripts");
touch(&root, "a/x.js");
touch(&root, "b/y.js");
let listing = list(&root, Limits { folders: 1, ..Limits::default() });
assert_eq!(rows(&listing.entries), "a/[x]");
assert!(listing.truncated);
assert!(!folder::list(&root).truncated);
let _ = std::fs::remove_dir_all(dir);
let _ = std::fs::remove_dir_all(two);
}
#[test]
fn a_folder_with_more_scripts_than_the_limit_lists_that_many() {
let dir = folder("many");
let root = dir.join("Scripts");
for n in 0..folder::MAX_SCRIPTS + 40 {
touch(&root, &format!("s{n:04}.js"));
}
let listing = list(&root, Limits::default());
assert_eq!((listing.scripts().len(), listing.truncated), (folder::MAX_SCRIPTS, true));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_read_takes_only_a_script_that_is_still_a_file_under_the_folder() {
let dir = folder("read");
let root = dir.join("Scripts");
let script = touch(&root, "Sub/draw.jsx");
std::fs::write(&script, "vc.log(1);").unwrap();
assert_eq!(folder::read(&root, &script, 100).as_deref(), Some(&b"vc.log(1);"[..]));
assert_eq!(folder::read(&root, &script, 4).as_deref(), Some(&b"vc.l"[..]));
let outside = touch(&dir, "outside.js");
touch(&root, "notes.txt");
for path in [outside, root.join("Sub").join("..").join("..").join("outside.js"), root.join("notes.txt"), root.join("Sub"), root.join("gone.js")] {
assert!(folder::read(&root, &path, 100).is_none(), "{}", path.display());
}
// A folder that took the script's place is not a script.
std::fs::remove_file(&script).unwrap();
std::fs::create_dir(&script).unwrap();
assert!(folder::read(&root, &script, 100).is_none());
// Nor is the script read once a link stands in for its folder.
let other = touch(&dir, "Other/draw.jsx");
std::fs::remove_dir_all(root.join("Sub")).unwrap();
link_folder(other.parent().unwrap(), &root.join("Sub"));
assert!(folder::read(&root, &root.join("Sub").join("draw.jsx"), 100).is_none());
let _ = std::fs::remove_dir_all(root.join("Sub"));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() {
let dir = folder("command");
let root = dir.join("Scripts");
touch(&root, "Tidy Layers.jsx");
touch(&root, "Export/All Artboards.js");
let mut s = Session::new();
assert_eq!(
s.execute("script.listInstalled", &json!({})).unwrap(),
json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false})
);
s.attach_scripts_dir(root.clone());
let text = |p: &Path| p.to_string_lossy().into_owned();
assert_eq!(
s.execute("script.listInstalled", &json!({})).unwrap(),
json!({
"folder": text(&root),
"scripts": [
{"path": text(&root.join("Export").join("All Artboards.js")), "label": "All Artboards", "folders": ["Export"]},
{"path": text(&root.join("Tidy Layers.jsx")), "label": "Tidy Layers", "folders": []},
],
"truncated": false,
"unreadable": false,
})
);
assert!(!find_command("script.listInstalled").unwrap().journal);
assert!(s.execute("script.listInstalled", &json!({"folder": "x"})).is_err());
// A folder that is not there yet lists nothing, and the listing does not make it.
std::fs::remove_dir_all(&root).unwrap();
assert_eq!(s.execute("script.listInstalled", &json!({})).unwrap()["scripts"], json!([]));
assert!(!root.exists());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn an_installed_script_is_read_as_script_run_reads_a_file() {
let dir = folder("installed");
let root = dir.join("Scripts");
let text = |p: &Path| p.to_string_lossy().into_owned();
let mut s = Session::new();
let script = touch(&root, "draw.jsx");
std::fs::write(&script, "\u{feff}vc.log(1);").unwrap();
assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED, "no folder is attached");
s.attach_scripts_dir(root.clone());
assert_eq!(s.installed_script(&text(&script)).unwrap(), "vc.log(1);");
std::fs::write(&script, "@JSXBIN@ES@2.0@").unwrap();
assert!(s.installed_script(&text(&script)).unwrap_err().to_string().contains("compiled script"));
std::fs::write(&script, [0xff, 0xfe]).unwrap();
assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), "the script is not UTF-8 text");
std::fs::write(&script, vec![b' '; script::MAX_SOURCE_BYTES + 1]).unwrap();
assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::TOO_LARGE);
std::fs::remove_file(&script).unwrap();
assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED);
let outside = touch(&dir, "outside.js");
assert_eq!(s.installed_script(&text(&outside)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() {
let dir = folder("roots");
let root = dir.join("Scripts");
let script = touch(&root, "draw.js");
let work = dir.join("work");
std::fs::create_dir_all(&work).unwrap();
let mut s = Session::new();
s.attach_scripts_dir(root.clone());
let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap();
let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err();
assert!(e.to_string().contains("outside the read root"), "{e}");
let e = crate::file_access::confine(Some(&roots), || s.installed_script(&script.to_string_lossy())).unwrap_err();
assert!(e.to_string().contains("outside the read root"), "{e}");
// A read root that holds the folder lets both through.
let roots = crate::file_access::AutomationRoots::new(&[&dir], &[]).unwrap().unwrap();
crate::file_access::confine(Some(&roots), || {
assert_eq!(s.execute("script.listInstalled", &json!({})).unwrap()["scripts"][0]["label"], "draw");
assert_eq!(s.installed_script(&script.to_string_lossy()).unwrap(), "");
});
let _ = std::fs::remove_dir_all(dir);
}
+511
View File
@@ -0,0 +1,511 @@
//! A script's preprocessor lines: `#include` and `//@include` in place, the folders they are looked
//! for in, the run's limits and scope, the other lines, `$.evalFile`, `$.fileName`, and errors at the
//! line of the file they are in.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::script::TEST_JSINCLUDE;
use crate::*;
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-include-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
base
}
fn write(path: &Path, text: &str) {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).unwrap();
}
std::fs::write(path, text).unwrap();
}
/// Runs `main/main.jsx` in `base`, with the text `text`.
fn run(base: &Path, text: &str) -> Result<Value> {
let main = base.join("main/main.jsx");
write(&main, text);
Session::new().execute("script.run", &json!({"path": main.to_string_lossy()}))
}
/// The report of the run that failed with `e`.
fn failed(base: &Path, text: &str) -> Value {
let mut s = Session::new();
let main = base.join("main/main.jsx");
write(&main, text);
let e = s.execute("script.run", &json!({"path": main.to_string_lossy()}));
assert!(e.is_err(), "the run failed: {e:?}");
s.script_report().unwrap().clone()
}
#[test]
fn script_include_sibling_runs_in_place() {
let base = folder("sibling");
write(&base.join("main/lib.jsxinc"), "var b = a + 1;");
write(&base.join("main/two.jsxinc"), "b = b * 10;\r\n");
let r = run(&base, "var a = 1;\n #include \"lib.jsxinc\"\n//@include 'two.jsxinc'\nvc.log(a + b);").unwrap();
assert_eq!(r["log"], json!([21]));
// A file may be included again once its earlier inclusion has ended.
let r = run(&base, "var n = 0;\n#include \"three.jsxinc\"\n#include \"three.jsxinc\"\nvc.log(n);");
assert!(r.is_err(), "three.jsxinc is missing");
write(&base.join("main/three.jsxinc"), "n++;");
let r = run(&base, "var n = 0;\n#include \"three.jsxinc\"\n#include three.jsxinc\nvc.log(n);").unwrap();
assert_eq!(r["log"], json!([2]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_nested_include_uses_including_folder() {
let base = folder("nested");
write(&base.join("main/sub/one.jsxinc"), "#include \"two.jsxinc\"\nvar one = two + 1;");
write(&base.join("main/sub/two.jsxinc"), "var two = 2;");
write(&base.join("main/two.jsxinc"), "var two = 200;");
let r = run(&base, "#include \"sub/one.jsxinc\"\nvc.log(one);").unwrap();
assert_eq!(r["log"], json!([3]), "two.jsxinc beside one.jsxinc, not beside the script");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_missing_include_reports_origin() {
let base = folder("missing");
let report = failed(&base, "vc.log(1);\n\t#include \"nope.jsxinc\"\n");
assert_eq!(report["kind"], "thrown");
assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(2), Some(2)));
assert!(report["message"].as_str().unwrap().contains("include file not found: nope.jsxinc"), "{report}");
assert_eq!(report["log"], json!([]), "nothing ran before the include was read");
assert!(report.get("file").is_none(), "the line is the script's own");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_includepath_searches_in_order() {
let base = folder("includepath");
write(&base.join("main/a/x.jsxinc"), "var x = 'a';");
write(&base.join("main/b/x.jsxinc"), "var x = 'b';");
write(&base.join("main/b/y.jsxinc"), "var y = 'b';");
let r = run(&base, "#includepath \"a; b\"\n#include \"x.jsxinc\"\n#include \"y.jsxinc\"\nvc.log(x + y + $.includePath);").unwrap();
assert_eq!(r["log"], json!(["aba;b"]));
// A later #includepath replaces the list.
let report = failed(&base, "#includepath \"b\"\n#includepath \"a\"\n#include \"y.jsxinc\"");
assert!(report["message"].as_str().unwrap().contains("include file not found: y.jsxinc"), "{report}");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_include_cycle_and_depth_stop() {
let base = folder("cycle");
write(&base.join("main/a.jsxinc"), "#include \"b.jsxinc\"");
write(&base.join("main/b.jsxinc"), "\n#include \"a.jsxinc\"");
let report = failed(&base, "#include \"a.jsxinc\"");
assert!(report["message"].as_str().unwrap().contains("include cycle: a.jsxinc"), "{report}");
assert_eq!(report["line"], 2);
assert!(report["file"].as_str().unwrap().ends_with("b.jsxinc"), "{report}");
// A script that includes itself.
let report = failed(&base, "#include \"main.jsx\"");
assert!(report["message"].as_str().unwrap().contains("include cycle"), "{report}");
for i in 0..20 {
write(&base.join(format!("main/d{i}.jsxinc")), &format!("#include \"d{}.jsxinc\"", i + 1));
}
let report = failed(&base, "#include \"d0.jsxinc\"");
assert_eq!(report["kind"], "limit");
assert!(report["message"].as_str().unwrap().contains("include depth limit (16) reached"), "{report}");
assert!(report["file"].as_str().unwrap().ends_with("d15.jsxinc"), "the 17th level is refused: {report}");
let _ = std::fs::remove_dir_all(base);
}
/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere.
/// `false` when the system does not allow it here.
fn link_folder(target: &Path, link: &Path) -> bool {
#[cfg(windows)]
{
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success());
made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok()
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, link).is_ok()
}
#[cfg(not(any(unix, windows)))]
{
let _ = (target, link);
false
}
}
#[test]
fn script_include_link_out_of_the_folder_is_refused() {
let base = folder("junction");
write(&base.join("outside/x.jsxinc"), "var leaked = 1;");
// `mklink` reads a `/` in its paths as a switch, so each name is joined on its own.
if !link_folder(&base.join("outside"), &base.join("main").join("away")) {
eprintln!("skipped: a folder link can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
assert!(std::fs::canonicalize(base.join("main/away/x.jsxinc")).unwrap().starts_with(std::fs::canonicalize(base.join("outside")).unwrap()));
let report = failed(&base, "#include \"away/x.jsxinc\"\nvc.log(leaked);");
assert!(report["message"].as_str().unwrap().contains("script file read refused: away/x.jsxinc"), "{report}");
let report = failed(&base, "$.evalFile('away/x.jsxinc');");
assert!(report["message"].as_str().unwrap().contains("script file read refused: away/x.jsxinc"), "{report}");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_include_parent_component_refused() {
let base = folder("parent");
write(&base.join("outside.jsxinc"), "var leaked = 1;");
write(&base.join("main/sub/x.jsxinc"), "var x = 1;");
let report = failed(&base, "#include \"../outside.jsxinc\"");
assert!(report["message"].as_str().unwrap().contains("script file read refused: ../outside.jsxinc"), "{report}");
// Refused even where the path would come back inside the folder.
let report = failed(&base, "#include \"sub/../sub/x.jsxinc\"");
assert!(report["message"].as_str().unwrap().contains("script file read refused"), "{report}");
let report = failed(&base, "#includepath \"..\"\n#include \"outside.jsxinc\"");
assert!(report["message"].as_str().unwrap().contains("script file read refused: outside.jsxinc"), "{report}");
let absolute = base.join("outside.jsxinc").to_string_lossy().replace('\\', "/");
let report = failed(&base, &format!("#include \"{absolute}\""));
assert!(report["message"].as_str().unwrap().contains("script file read refused"), "an absolute path outside: {report}");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_jsinclude_outside_grants_ignored() {
let base = folder("jsinclude");
write(&base.join("outside/x.jsxinc"), "var x = 'outside';");
write(&base.join("main/lib/y.jsxinc"), "var y = 'lib';");
TEST_JSINCLUDE.with(|t| *t.borrow_mut() = Some(vec![base.join("outside"), base.join("main/lib")]));
let report = failed(&base, "#include \"x.jsxinc\"");
let r = run(&base, "#include \"y.jsxinc\"\nvc.log(y);");
TEST_JSINCLUDE.with(|t| *t.borrow_mut() = None);
assert!(report["message"].as_str().unwrap().contains("include file not found: x.jsxinc"), "passed over, not refused: {report}");
assert_eq!(r.unwrap()["log"], json!(["lib"]), "a JSINCLUDE folder inside the script's folder is searched");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_target_other_app_does_not_route() {
let mut s = Session::new();
let r = s.execute("script.run", &json!({"source": "#target someapp-12\n#target \"other\"\n//@target x\n#strict off\nvc.log(1);"})).unwrap();
assert_eq!(r["log"], json!([1]));
for (source, message) in [
("#target\nvc.log(1);", "#target needs a value"),
("#targetengine \"session\"", "unsupported script directive: #targetengine"),
("#engine \"main\"", "unsupported script directive: #engine"),
("#strict maybe", "#strict takes on or off"),
("#frobnicate 1", "unknown script directive: #frobnicate"),
("#include \"x.jsxinc", "unterminated quote in #include"),
("#include \"x.jsxinc\"", "script file read refused: x.jsxinc"),
] {
let e = s.execute("script.run", &json!({"source": format!("vc.log(0);\n{source}")})).unwrap_err().to_string();
assert!(e.contains(message), "{source}: {e}");
assert_eq!(s.script_report().unwrap()["line"], 2, "{source}");
assert_eq!(s.script_report().unwrap()["log"], json!([]), "{source}");
}
// An unknown `//@` name stays a comment.
assert_eq!(s.execute("script.run", &json!({"source": "//@frobnicate 1\nvc.log(2);"})).unwrap()["log"], json!([2]));
}
#[test]
fn script_name_comes_from_the_script_line() {
let mut s = Session::new();
let r = s.execute("script.run", &json!({"source": "#script \"First\"\n#script Second\nvc.log($.fileName);"})).unwrap();
assert_eq!((r["name"].as_str(), r["log"].clone()), (Some("Second"), json!([""])));
let r = s.execute("script.run", &json!({"source": "#script Second\n", "name": "given.js"})).unwrap();
assert_eq!(r["name"], "given.js", "a name given to script.run wins");
let base = folder("name");
write(&base.join("main/lib.jsxinc"), "#script Inner\n");
let r = run(&base, "#include \"lib.jsxinc\"").unwrap();
assert_eq!(r["name"], "main.jsx", "an included file's #script line does not rename the run");
let _ = std::fs::remove_dir_all(base);
}
/// The script's `ro`, with a read-only `x`.
const READ_ONLY: &str = "var ro = {};\nObject.defineProperty(ro, 'x', {value: 1});\n";
#[test]
fn strict_on_runs_and_read_only_write_throws() {
let mut s = Session::new();
for head in ["#strict on\n", "//@strict on\n", "#strict ON\n", "#strict off\n#strict on\n"] {
let source = format!("{head}{READ_ONLY}vc.log(1);\n ro.x = 2;\nvc.log(2);");
let e = s.execute("script.run", &json!({"source": source})).unwrap_err().to_string();
assert!(e.contains("TypeError: cannot assign to property 'x': it is read-only"), "{head}: {e}");
let report = s.script_report().unwrap();
assert_eq!(report["kind"], "thrown", "{head}");
assert_eq!(report["log"], json!([1]), "{head}: the script ran up to the write");
let line = head.lines().count() as u64 + 4;
assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(line), Some(3)), "{head}: {report}");
}
// The error can be caught, and every kind of assignment is checked.
let source = format!(
"#strict on\n{READ_ONLY}var out = [];\nfunction t(f) {{ try {{ f(); out.push('wrote'); }} catch (e) {{ out.push(e.name); }} }}\nt(function () {{ ro.x = 2; }});\nt(function () {{ ro['x'] += 1; }});\nt(function () {{ ro.x++; }});\nt(function () {{ undefined = 1; }});\nt(function () {{ [].concat.length = 0; }});\nvc.log(out);\nvc.log(ro.x);"
);
let r = s.execute("script.run", &json!({"source": source})).unwrap();
assert_eq!(r["log"], json!([["TypeError", "TypeError", "TypeError", "TypeError", "TypeError"], 1]));
// Without the line, or with `#strict off` last, the write is ignored as before.
for head in ["", "#strict off\n", "#strict on\n#strict off\n"] {
let r = s.execute("script.run", &json!({"source": format!("{head}{READ_ONLY}ro.x = 2;\nvc.log(ro.x);")})).unwrap();
assert_eq!(r["log"], json!([1]), "{head}");
}
}
#[test]
fn strict_on_rejects_getter_only_and_nonextensible_additions() {
let mut s = Session::new();
let source = "#strict on\nvar out = [];\nfunction t(f) { try { f(); out.push('wrote'); } catch (e) { out.push(String(e)); } }\n\
var g = {get v() { return 1; }}, set = {set v(x) { this.got = x; }};\n\
t(function () { g.v = 2; });\n\
t(function () { Object.preventExtensions({}).n = 1; });\n\
t(function () { Object.seal({a: 1}).n = 1; });\n\
t(function () { Object.freeze({a: 1}).a = 2; });\n\
t(function () { vc.extra = 1; });\n\
var open = {};\nt(function () { open.n = 1; });\nt(function () { set.v = 3; });\nt(function () { Object.seal({a: 1}).a = 2; });\n\
vc.log(out);\nvc.log(open.n);\nvc.log(set.got);";
let r = s.execute("script.run", &json!({"source": source})).unwrap();
assert_eq!(
r["log"],
json!([
[
"TypeError: cannot assign to property 'v': it has only a getter",
"TypeError: cannot assign to property 'n': the object is not extensible",
"TypeError: cannot assign to property 'n': the object is not extensible",
"TypeError: cannot assign to property 'a': it is read-only",
"TypeError: cannot assign to property 'extra': the object is not extensible",
"wrote",
"wrote",
"wrote"
],
1,
3
])
);
let r = s.execute("script.run", &json!({"source": source.replacen("#strict on", "#strict off", 1)})).unwrap();
assert_eq!(r["log"][0], json!(["wrote", "wrote", "wrote", "wrote", "wrote", "wrote", "wrote", "wrote"]), "off, nothing is refused");
}
#[test]
fn strict_on_does_not_enable_es5_early_errors() {
let mut s = Session::new();
let source = "#strict on\nwith ({w: 1}) { vc.log(w); }\nfunction f(a, a) { return a; }\nvc.log(f(1, 2));\nvc.log(010);\nundeclared = 4;\nvc.log(undeclared);\n\
vc.log((function () { return typeof this; })());\nvc.log(delete Object.prototype);\nvar eval2 = 5;\nvc.log((function () { arguments = 6; return arguments; })());";
let r = s.execute("script.run", &json!({"source": source})).unwrap();
assert_eq!(r["log"], json!([1, 2, 8, 4, "object", false, 6]));
// 'use strict' still makes the code strict mode code.
let e = s.execute("script.run", &json!({"source": "#strict on\n'use strict';\nundeclared2 = 1;"})).unwrap_err().to_string();
assert!(e.contains("ReferenceError"), "{e}");
let e = s.execute("script.run", &json!({"source": "#strict on\n'use strict';\nwith ({}) {}"})).unwrap_err().to_string();
assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{e}");
}
#[test]
fn strict_on_in_include_controls_expanded_run() {
let base = folder("strict");
write(&base.join("main/on.jsxinc"), "#strict on\nvar inc = 1;");
write(&base.join("main/off.jsxinc"), "//@strict off\n");
write(&base.join("main/writes.jsxinc"), &format!("{READ_ONLY}\n ro.x = 2;\n"));
// An included file's line sets the checks for the script's own code too.
let report = failed(&base, &format!("#include \"on.jsxinc\"\n{READ_ONLY}ro.x = 2;"));
assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}");
assert_eq!(report["line"], 4, "{report}");
assert!(report.get("file").is_none(), "{report}");
// A write in an included file is reported at its own line.
let report = failed(&base, "#strict on\n#include \"writes.jsxinc\"");
assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}");
assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(4), Some(3)), "{report}");
assert!(report["file"].as_str().unwrap().ends_with("writes.jsxinc"), "{report}");
// The last line of the expanded run wins, wherever it is.
let r = run(&base, &format!("#strict on\n#include \"off.jsxinc\"\n{READ_ONLY}ro.x = 2;\nvc.log(ro.x);")).unwrap();
assert_eq!(r["log"], json!([1]));
let report = failed(&base, &format!("#include \"off.jsxinc\"\n#strict on\n{READ_ONLY}ro.x = 2;"));
assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn strict_mode_in_eval_file_is_scoped() {
let base = folder("strict-eval");
write(
&base.join("main/on.jsx"),
&format!(
"#strict on\n{READ_ONLY}function w(o) {{ o.x = 2; }}\nvar inner;\ntry {{ ro.x = 2; inner = 'wrote'; }} catch (e) {{ inner = e.name; }}\n"
),
);
write(&base.join("main/off.jsx"), &format!("#strict off\n{READ_ONLY}ro.x = 2;\n'off ran';"));
write(&base.join("main/plain.jsx"), &format!("{READ_ONLY}ro.x = 2;\n'plain ran';"));
// A file's own `#strict on` holds for its code, its functions included, and not the caller's.
let r = run(
&base,
"$.evalFile('on.jsx');\nvar after;\ntry { ro.x = 3; after = 'ignored'; } catch (e) { after = e.name; }\nvar called;\ntry { w(ro); called = 'wrote'; } catch (e) { called = e.name; }\nvc.log([inner, after, called]);",
)
.unwrap();
assert_eq!(r["log"], json!([["TypeError", "ignored", "TypeError"]]));
// A file without the line takes the caller's checks, and its own `#strict off` turns them off.
let r = run(&base, "#strict on\nvc.log($.evalFile('off.jsx'));\nvar e1;\ntry { ro.x = 2; } catch (e) { e1 = e.name; }\nvc.log(e1);").unwrap();
assert_eq!(r["log"], json!(["off ran", "TypeError"]), "the caller keeps its own checks");
let report = failed(&base, "#strict on\n$.evalFile('plain.jsx');");
assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}");
assert!(report["file"].as_str().unwrap().ends_with("plain.jsx"), "{report}");
assert_eq!(report["line"], 3, "{report}");
assert_eq!(run(&base, "vc.log($.evalFile('plain.jsx'));").unwrap()["log"], json!(["plain ran"]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_eval_file_returns_last_value_and_shares_globals() {
let base = folder("evalfile");
write(&base.join("main/sub/e.jsx"), "var inner = $.fileName;\nfunction h(x) { return x * g; }\n#include \"f.jsxinc\"\ng + f;");
write(&base.join("main/sub/f.jsxinc"), "var f = 40;");
write(&base.join("main/empty.jsx"), "");
let r = run(
&base,
"var g = 2;\nvar r = $.evalFile('sub/e.jsx', 1000);\nvc.log(r);\nvc.log(h(3));\nvc.log(/e\\.jsx$/.test(inner));\nvc.log(/main\\.jsx$/.test($.fileName));\nvc.log($.evalFile('empty.jsx') === undefined);",
)
.unwrap();
assert_eq!(r["log"], json!([42, 6, true, true, true]));
// Its errors can be caught; a file is evaluated again after it has returned.
let r = run(
&base,
"var g = 1; var out = [];\ntry { $.evalFile(''); } catch (e) { out.push(e.name); }\ntry { $.evalFile('nope.jsx'); } catch (e) { out.push(String(e)); }\ntry { $.evalFile('sub/e.jsx', -1); } catch (e) { out.push(e.name); }\ntry { $.evalFile('sub/e.jsx', Infinity); } catch (e) { out.push(e.name); }\nout.push($.evalFile('sub/e.jsx') + $.evalFile('sub/e.jsx'));\nvc.log(out);",
)
.unwrap();
assert_eq!(r["log"], json!([["TypeError", "Error: include file not found: nope.jsx", "RangeError", "TypeError", 82]]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_eval_file_outside_scope_refused() {
let base = folder("evaloutside");
write(&base.join("outside.jsx"), "1;");
let absolute = base.join("outside.jsx").to_string_lossy().replace('\\', "/");
let script = format!(
"var out = [];\ntry {{ $.evalFile('../outside.jsx'); }} catch (e) {{ out.push(String(e)); }}\ntry {{ $.evalFile('{absolute}'); }} catch (e) {{ out.push(String(e)); }}\nvc.log(out);"
);
let r = run(&base, &script).unwrap();
let out = r["log"][0].as_array().unwrap();
assert_eq!(out.len(), 2);
for e in out {
assert!(e.as_str().unwrap().starts_with("Error: script file read refused"), "{e}");
}
// A script given as text has no folder to read from.
let e = Session::new().execute("script.run", &json!({"source": "$.evalFile('x.jsx');"})).unwrap_err().to_string();
assert!(e.contains("script file read refused: x.jsx"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_directives_in_strings_and_block_comments_are_inert() {
let mut s = Session::new();
let source = "#target x\nvar a = '#include \"nope.jsxinc\"';\n/*\n#include \"nope.jsxinc\"\n//@include \"nope.jsxinc\"\n*/\nvar b = 1; // #include \"nope.jsxinc\"\nvar c = 2; #include\nvc.log(a.length + b);";
let e = s.execute("script.run", &json!({"source": source})).unwrap_err().to_string();
// `#` after code on a line is not a preprocessor line: the script has a syntax error there.
assert!(e.contains("line 8"), "{e}");
let source = source.replace("var c = 2; #include\n", "");
assert_eq!(s.execute("script.run", &json!({"source": source})).unwrap()["log"], json!([23]));
}
#[test]
fn script_included_error_has_local_file_and_line() {
let base = folder("errors");
write(&base.join("main/lib.jsxinc"), "var x = 1;\n\n throw new Error('boom');\n");
write(&base.join("main/bad.jsxinc"), "var y = 1;\nvar = 2;\n");
write(&base.join("main/five.jsxinc"), "1;\n2;\n3;\n4;\n5;");
write(&base.join("main/sub/thrower.jsx"), "\n\nthrow new Error('deep');");
let mut s = Session::new();
let report = failed(&base, "var z = 0;\n#include \"lib.jsxinc\"");
assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(3), Some(5)), "{report}");
assert!(report["file"].as_str().unwrap().ends_with("lib.jsxinc"), "{report}");
let report = failed(&base, "#include \"bad.jsxinc\"");
assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}");
assert!(report["file"].as_str().unwrap().ends_with("bad.jsxinc"), "{report}");
// A line of the script after an include keeps its own number.
let report = failed(&base, "#include \"five.jsxinc\"\n throw new Error('after');");
assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(2), Some(3)), "{report}");
assert!(report.get("file").is_none(), "{report}");
let report = failed(&base, "#include \"five.jsxinc\"\nvar = 1;");
assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}");
// An included file that ends in a carriage return does not join the script's next line ending.
write(&base.join("main/cr.jsxinc"), "1;\r2;\r");
let report = failed(&base, "#include \"cr.jsxinc\"\n\n throw new Error('after');");
assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(3), Some(3)), "{report}");
assert!(report.get("file").is_none(), "{report}");
let report = failed(&base, "#include \"cr.jsxinc\"\r\nvar = 1;");
assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}");
// An uncaught error in a file $.evalFile ran is at that file's line.
let report = failed(&base, "var a = 1;\n$.evalFile('sub/thrower.jsx');");
assert_eq!(report["line"], 3, "{report}");
assert!(report["file"].as_str().unwrap().ends_with("thrower.jsx"), "{report}");
// So is a file $.evalFile could not run: a syntax error, or a bad preprocessor line.
write(&base.join("main/sub/broken.jsx"), "var a = 1;\n\nvar = 2;");
write(&base.join("main/sub/directive.jsx"), "\n#frobnicate 1");
for (file, line) in [("broken.jsx", 3), ("directive.jsx", 2)] {
let report = failed(&base, &format!("var a = 1;\n$.evalFile('sub/{file}');"));
assert_eq!(report["line"], line, "{report}");
assert!(report["file"].as_str().unwrap().ends_with(file), "{report}");
}
// The console's error line names the file.
let main = base.join("main/main.jsx");
write(&main, "#include \"lib.jsxinc\"");
assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err());
let console = s.execute("script.console", &json!({})).unwrap();
let error = console["lines"].as_array().unwrap().iter().find(|l| l["kind"] == "error").unwrap()["text"].as_str().unwrap().to_string();
assert!(error.starts_with("main.jsx: ") && error.contains("lib.jsxinc:3:5: Error: boom"), "{error}");
let _ = std::fs::remove_dir_all(base);
}
/// Pumps the run in the app until it ends or waits at a dialog (`None`).
fn pump(s: &mut Session) -> Option<Result<Value>> {
for _ in 0..10_000 {
if s.script_dialog().is_some() {
return None;
}
if let Some(r) = s.script_pump() {
return Some(r);
}
}
panic!("the run neither ended nor waited");
}
#[test]
fn script_dialogs_in_included_and_evaluated_files() {
let base = folder("dialogs");
write(&base.join("main/ask.jsxinc"), "var a = confirm('inc');\n");
write(&base.join("main/ev.jsx"), "alert('ev'); 7");
let text = "#include \"ask.jsxinc\"\nvar m = '';\ntry { m = $.evalFile('ev.jsx'); } catch (e) { m = e.message; }\nvc.log([a, m]);";
let main = base.join("main/main.jsx");
write(&main, text);
let path = main.to_string_lossy().to_string();
// In the app, an included file's dialog waits as the script's own does; one in a file
// $.evalFile runs cannot wait there and throws an error the script can catch.
let mut s = Session::new();
s.script_frames = true;
assert_eq!(s.execute("script.run", &json!({"path": path})).unwrap()["running"], true);
assert!(pump(&mut s).is_none());
assert_eq!(s.script_dialog().unwrap().message, "inc");
assert!(s.script_answer(crate::script::DialogAnswer::Confirm(true)));
let r = pump(&mut s).unwrap().unwrap();
let m = r["log"][0][1].as_str().unwrap_or_default();
assert_eq!(r["log"][0][0], true, "{r}");
assert!(m.contains("alert") && m.contains("$.evalFile"), "the error names the call and why: {r}");
assert_eq!(r["dialogCount"], 1, "{r}");
// A run with nobody to ask takes both answers in order.
let mut s = Session::new();
let answers = json!([{"kind": "confirm", "value": false}, {"kind": "alert", "value": "ok"}]);
let r = s.execute("script.run", &json!({"path": path, "answers": answers})).unwrap();
assert_eq!((r["log"].clone(), r["dialogCount"].clone()), (json!([[false, 7]]), json!(2)), "{r}");
// An error in an included file after its dialog is at that file's line, and the report keeps
// both the file and the dialog.
write(&base.join("main/ask.jsxinc"), "var a = confirm('inc');\nif (a) throw new Error('after');\n");
let mut s = Session::new();
s.script_frames = true;
s.execute("script.run", &json!({"path": path})).unwrap();
assert!(pump(&mut s).is_none());
assert!(s.script_answer(crate::script::DialogAnswer::Confirm(true)));
assert!(pump(&mut s).unwrap().is_err());
let report = s.script_report().unwrap();
assert_eq!(report["line"], 2, "{report}");
assert!(report["file"].as_str().unwrap().ends_with("ask.jsxinc"), "{report}");
assert_eq!(report["dialogs"][0]["answer"], true, "{report}");
let _ = std::fs::remove_dir_all(base);
}
+10 -1
View File
@@ -166,7 +166,7 @@ fn an_error_names_the_script_its_place_and_kind() {
let e = run(&mut s, "var = 1;").unwrap_err().to_string();
assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}");
assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`"));
assert!(run(&mut s, "#target x\n1").unwrap_err().to_string().contains("#target"));
assert!(run(&mut s, "#targetengine x\n1").unwrap_err().to_string().contains("unsupported script directive: #targetengine"));
assert_eq!(s.script_report().unwrap()["line"], 1);
}
@@ -989,6 +989,15 @@ fn source_text() -> impl proptest::strategy::Strategy<Value = String> {
Just("{".to_string()),
Just("try {".to_string()),
Just("} catch (e) {}".to_string()),
Just("\n#include \"x.jsxinc\"\n".to_string()),
Just("\n//@include 'x\n".to_string()),
Just("\n#includepath \";;..;\"\n".to_string()),
Just("\n#script \"\"\n".to_string()),
Just("\n#target\n".to_string()),
Just("\n#strict on\n".to_string()),
Just("\n#\u{0}\n".to_string()),
Just("try { $.evalFile('x.jsx', NaN); } catch (e) {}".to_string()),
"\n#[a-z]{0,12}[ -~]{0,20}\n",
"[ -~]{0,30}",
"\\PC{0,10}",
];
+42 -1
View File
@@ -5,7 +5,7 @@ use serde_json::{Value, json};
use vectorcraft_color::cms;
use crate::Session;
use crate::store::{MAX_PRESET_FILE, file_stem};
use crate::store::{MAX_PRESET_FILE, file_stem, holds};
fn fresh_dir(tag: &str) -> std::path::PathBuf {
let dir = vectorcraft_testkit::temp_dir(&format!("store-{tag}"));
@@ -128,6 +128,47 @@ fn a_folder_that_does_not_exist_yet_takes_the_presets_the_preferences_held() {
assert_eq!(saved_names(&mut b), ["From Preferences"]);
}
/// Serves `0` bytes without end and counts how many were read.
struct Endless(u64);
impl std::io::Read for Endless {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.0 > 1 << 24 {
return Err(std::io::Error::other("read too far"));
}
buf.fill(0);
self.0 += buf.len() as u64;
Ok(buf.len())
}
}
#[test]
fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() {
let mut old = Endless(0);
assert!(!holds(&mut old, &[0; 10]));
assert_eq!(old.0, 11);
assert!(holds(&[1, 2, 3][..], &[1, 2, 3]));
assert!(!holds(&[1, 2, 3, 4][..], &[1, 2, 3]));
assert!(!holds(&[1, 2][..], &[1, 2, 3]));
assert!(holds(&[][..], &[]));
}
#[test]
fn a_saved_preset_replaces_an_oversized_file_in_its_place() {
let dir = fresh_dir("oversized-put").join("PDF Presets");
let mut a = Session::new();
a.attach_pdf_preset_store(dir.clone());
a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap();
let file = dir.join(format!("{}.vcpdfpresets", file_stem("Web")));
let saved = std::fs::read(&file).unwrap();
let mut oversized = saved.clone();
oversized.resize(usize::try_from(MAX_PRESET_FILE).unwrap() * 2, b' ');
std::fs::write(&file, &oversized).unwrap();
a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap();
assert_eq!(std::fs::read(&file).unwrap(), saved);
}
#[test]
fn damaged_unsafe_and_oversized_preset_files_are_skipped() {
let dir = fresh_dir("damaged").join("PDF Presets");
+11 -1
View File
@@ -41,8 +41,9 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
let mut s = session();
let list = run(&mut s, "graphicStyle.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
assert!(libs.len() >= 7 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}");
assert!(libs.len() >= 8 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}");
for l in libs {
let id = l["id"].as_str().unwrap();
let g = run(&mut s, "graphicStyle.library", json!({"library": id}));
@@ -60,6 +61,9 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
let game = run(&mut s, "graphicStyle.library", json!({"library": "game-hud"}));
let game_names: Vec<&str> = game["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(game_names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]);
let status = run(&mut s, "graphicStyle.library", json!({"library": "status-effects"}));
let status_names: Vec<&str> = status["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]);
let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0);
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]}));
assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow")));
@@ -67,6 +71,12 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#3498db").unwrap()));
assert_eq!(node.appearance.stroke_paint(), Paint::None);
assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["stylize.outerGlow"]);
let id2 = rect(&mut s, 60.0, 20.0, 40.0, 30.0);
let r2 = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "status-effects", "name": "Poison Tint", "apply": true, "ids": [id2.0]}));
assert_eq!((names(&r2["added"]), r2["applied"].as_str()), (vec!["Poison Tint"], Some("Poison Tint")));
let node2 = doc(&s).node(id2).unwrap();
assert_eq!(node2.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#2ecc71").unwrap()));
assert_eq!(node2.appearance.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["stylize.outerGlow"]);
// By name in any case.
assert_eq!(run(&mut s, "graphicStyle.library", json!({"library": "shadows and glows"}))["id"], "shadows-glows");
assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err());
+77
View File
@@ -207,6 +207,83 @@ fn deleting_a_filter_in_use_leaves_the_effect_drawing_nothing() {
assert_eq!(drawn(&s, a), json!(SHIFT_MORE));
}
/// The `(name, xml)` of every `svg.filter` effect on the document's objects.
fn filter_effects(s: &Session) -> Vec<(String, String)> {
let mut out = vec![];
s.doc().unwrap().doc.walk(|n| {
for e in n.appearance.effects.iter().filter(|e| e.id == vectorcraft_render::effects::SVG_FILTER) {
out.push((e.params["name"].as_str().unwrap().to_string(), e.params["xml"].as_str().unwrap().to_string()));
}
});
out
}
/// Pasted art whose filter has a name the document gives another filter keeps its own filter
/// under a free name, so editing or deleting the document's filter leaves it alone. Pasted back
/// into the document it came from, it takes the document's filter as it is now.
#[test]
fn pasted_art_keeps_a_filter_another_of_its_name_would_replace() {
let mut s = session();
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{SHIFT_MORE}</defs><rect width="30" height="30" filter="url(#Shift)"/></svg>"#
);
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
run(&mut s, "edit.pasteInPlace", json!({}));
let pasted = filter_effects(&s);
assert_eq!(pasted.len(), 1);
assert_eq!(pasted[0].0, "Shift 2", "renamed: {pasted:?}");
assert!(pasted[0].1.contains("id=\"Shift 2\"") && pasted[0].1.contains("dx=\"9\""), "its own filter: {pasted:?}");
assert_eq!(names(&mut s), ["Shift"]);
run(&mut s, "svgFilter.delete", json!({"name": "Shift"}));
assert_eq!(filter_effects(&s), pasted, "the document's filter leaves it alone");
// The same filter as the document's keeps its name.
let mut t = session();
run(&mut t, "svgFilter.define", json!({"xml": SHIFT}));
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{SHIFT}</defs><rect width="30" height="30" filter="url(#Shift)"/></svg>"#
);
run(&mut t, "clipboard.importSvg", json!({"svg": svg}));
run(&mut t, "edit.pasteInPlace", json!({}));
assert_eq!(filter_effects(&t), [("Shift".to_string(), SHIFT.to_string())]);
// Copied, then the filter edited: pasted back, the copy draws the edited filter.
let mut u = session();
let a = rect(&mut u, 10.0);
run(&mut u, "svgFilter.define", json!({"xml": SHIFT}));
run(&mut u, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]}));
run(&mut u, "select.set", json!({"ids": [a.0]}));
run(&mut u, "edit.copy", json!({}));
run(&mut u, "svgFilter.define", json!({"xml": SHIFT_MORE, "replace": "Shift"}));
run(&mut u, "edit.pasteInPlace", json!({}));
let both = filter_effects(&u);
assert_eq!(both, [("Shift".to_string(), SHIFT_MORE.to_string()), ("Shift".to_string(), SHIFT_MORE.to_string())]);
}
/// A pasted filter at the size limit, which "Shift 2" would make too long to draw, keeps its own
/// definition under a free name no longer than its own (a free letter for a one-letter name), and
/// its id is that name.
#[test]
fn pasted_art_with_a_filter_at_the_size_limit_still_draws_when_renamed() {
for (name, held, renamed) in [("Shift", SHIFT, "Shif"), ("S", r#"<filter id="S"><feOffset dx="3" dy="3"/></filter>"#, "a")] {
let mut s = session();
run(&mut s, "svgFilter.define", json!({"xml": held}));
let (open, close) = (format!(r#"<filter id="{name}"><feOffset dx="9" dy="9" result=""#), r#""/></filter>"#);
let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len()));
assert!(vectorcraft_render::effects::svg_filter::check(&big).is_ok());
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{big}</defs><rect width="30" height="30" filter="url(#{name})"/></svg>"#
);
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
run(&mut s, "edit.pasteInPlace", json!({}));
let pasted = filter_effects(&s);
assert_eq!(pasted.len(), 1);
assert_eq!(pasted[0].0, renamed, "renamed: {}", pasted[0].0);
assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok(renamed.to_string()), "the pasted filter draws under its name");
assert!(pasted[0].1.contains("dx=\"9\""), "its own filter");
assert_eq!(names(&mut s), [name]);
}
}
/// Art in a symbol's definition that uses a filter follows its edits too.
#[test]
fn a_symbols_art_follows_a_filter_edit() {
+31 -1
View File
@@ -84,7 +84,7 @@ fn the_builtin_library_is_original_art_generated_in_code() {
let mut s = Session::new();
let list = run(&mut s, "symbol.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
assert_eq!(libs.len(), 3, "{libs:?}");
assert_eq!(libs.len(), 4, "{libs:?}");
assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn")));
assert_eq!(
(libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()),
@@ -94,6 +94,10 @@ fn the_builtin_library_is_original_art_generated_in_code() {
(libs[2]["id"].as_str(), libs[2]["name"].as_str(), libs[2]["category"].as_str()),
(Some("map-markers"), Some("Map Markers"), Some("builtIn"))
);
assert_eq!(
(libs[3]["id"].as_str(), libs[3]["name"].as_str(), libs[3]["category"].as_str()),
(Some("inventory-icons"), Some("Inventory Icons"), Some("builtIn"))
);
let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"}));
let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]);
@@ -129,6 +133,32 @@ fn ui_frames_symbols_carry_default_nine_slice_when_added() {
));
}
#[test]
fn inventory_icons_symbols_add_without_nine_slice() {
let mut s = session();
let lib = run(&mut s, "symbol.library", json!({"library": "inventory-icons"}));
let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Sword", "Shield", "Potion", "Key", "Gem"]);
let mut placed = Vec::new();
for (i, name) in names.iter().enumerate() {
let r = run(
&mut s,
"symbol.addFromLibrary",
json!({"library": "inventory-icons", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}),
);
assert_eq!(r["added"], json!([name]));
placed.push(r["placed"].as_u64().unwrap());
}
let d = doc(&s);
for name in &names {
assert_eq!(d.symbol_nine_slice(name), None, "{name} should not carry 9-slice guides");
}
assert!(matches!(
d.node(NodeId(placed[0])).map(|n| &n.kind),
Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == "Sword"
));
}
#[test]
fn map_markers_symbols_add_without_nine_slice() {
let mut s = session();
+100
View File
@@ -280,6 +280,37 @@ fn metrics_pair_step_preserves_the_drawn_auto_position() {
assert!((moved - s.prefs.tracking_increment * 0.1).abs() < 0.01, "V moves by one kerning increment: {moved}");
}
/// At 50% Horizontal Scale the font's pair reads as the same thousandths of an em as at 100%:
/// kerning is measured in the em as the scale draws it (`vectorcraft_text::spacing_scale`), so the
/// value read keeps V where the font's kerning draws it, and a step moves V half as far as at 100%.
#[test]
fn horizontally_scaled_pair_reads_as_the_kerning_that_keeps_it() {
use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font};
let db = vectorcraft_text::FontDb::global();
db.add_font(pair_kerning_font().unwrap());
let mut s = session();
let id = NodeId(
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AV", "size": 100, "font": PAIR_KERNING_FAMILY})).unwrap()["id"].as_u64().unwrap(),
);
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 2, "hScale": 50})).unwrap();
let before = obj(&s, id);
assert_eq!(before.runs[0].style.h_scale, 50.0);
let auto = vectorcraft_text::layout(db, &before);
let drawn_v = |layout: &vectorcraft_text::TextLayout| layout.glyphs.iter().find(|g| g.byte == 1).unwrap().xf.as_coeffs()[4];
let read = crate::cmd::effective_kerning(db, &before, &auto, 0, 1);
assert!((read + 160.0).abs() < 0.01, "the font's -160/1000 em: {read}");
let mut same = before.clone();
vectorcraft_text::edit::style_range(&mut same.runs, 0, 1, |st| st.kerning = Some(read));
assert!((drawn_v(&vectorcraft_text::layout(db, &same)) - drawn_v(&auto)).abs() < 0.01);
s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap();
let after = obj(&s, id);
assert!((after.runs[0].style.kerning.unwrap() + 160.0 - s.prefs.tracking_increment).abs() < 0.01);
let moved = drawn_v(&vectorcraft_text::layout(db, &after)) - drawn_v(&auto);
assert!((moved - s.prefs.tracking_increment * 0.05).abs() < 0.01, "V moves by half a kerning increment at 100%: {moved}");
}
#[test]
fn effective_auto_kerning_at_area_line_end_survives_unkerned_wrap() {
use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font};
@@ -3436,6 +3467,75 @@ fn glyph_alternates_query_reports_the_fallback_glyph_that_is_drawn() {
assert_eq!(query["chosen"], json!(glyph.gid), "an overflowing character reports the fallback glyph it is drawn with");
}
/// `text.setGlyphAlternate` with `gid: null` reports the glyph the character is drawn with, as
/// `text.glyphAlternates` does: the fallback face's glyph for a character the font lacks, laid out
/// or overflowing, and the capital that All Caps draws for an a.
#[test]
fn a_glyph_choice_taken_away_reports_the_glyph_drawn() {
use vectorcraft_text::test_fonts::{alternates_family, alternates_font};
let _fonts = crate::adding_fonts();
let db = vectorcraft_text::FontDb::global();
db.add_font(alternates_font(true).expect("the test font builds"));
let face = db.face(alternates_family(true), "Regular").expect("the test face");
let mut s = session();
let reset = |s: &mut Session, id: NodeId, start: usize| {
s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": start, "gid": null})).unwrap()["gid"].clone()
};
let chosen = |s: &mut Session, id: NodeId, start: usize| {
s.execute("text.glyphAlternates", &json!({"id": id.0, "start": start})).unwrap()["chosen"].clone()
};
let ch = 'Ƃ';
assert_eq!(face.glyph_for(ch), 0);
let point = json!({"x": 0, "y": 0, "text": ch.to_string(), "font": alternates_family(true)});
let id = NodeId(s.execute("text.create", &point).unwrap()["id"].as_u64().unwrap());
let drawn = vectorcraft_text::layout(db, &obj(&s, id)).glyphs[0].gid;
assert_ne!(drawn, 0);
assert_eq!(reset(&mut s, id, 0), json!(drawn), "the fallback glyph");
assert_eq!(chosen(&mut s, id, 0), json!(drawn));
let area = json!({"x": 0, "y": 300, "text": ch.to_string(), "font": alternates_family(true), "area": {"width": 200, "height": 2}});
let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap());
assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows");
assert_eq!(reset(&mut s, boxed, 0), json!(drawn), "the overflowing character's fallback glyph");
let caps = NodeId(
s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute("text.setRangeStyle", &json!({"id": caps.0, "start": 0, "end": 4, "allCaps": true})).unwrap();
let drawn = vectorcraft_text::layout(db, &obj(&s, caps)).glyphs.iter().find(|g| g.byte == 1).expect("the a is laid out").gid;
assert_ne!(drawn, face.glyph_for('a'), "All Caps draws the a as A");
assert_eq!(reset(&mut s, caps, 1), json!(drawn), "the capital drawn");
assert_eq!(chosen(&mut s, caps, 1), json!(drawn));
}
/// A run that holds a choice for its first character and goes on past it, as a file may have,
/// draws Source Serif 4's fi ligature for the f and the i after that character. `gid: null` for the
/// i leaves the text as it is and reports the ligature, as `text.glyphAlternates` does.
#[test]
fn a_glyph_choice_taken_away_inside_a_ligature_reports_the_ligature() {
let db = vectorcraft_text::FontDb::global();
let face = db.face("Source Serif 4", "Regular").expect("the bundled face");
let mut s = session();
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xfin", "size": 40, "font": "Source Serif 4"})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
let mut runs = obj(&s, id).runs;
runs[0].style.glyph_alternate = Some(face.choice('x', face.glyph_for('x')));
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let Some(NodeKind::Text(text)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("text") };
text.runs = runs.clone();
let ligature = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.iter().find(|g| g.byte == 1 && g.len == 2).expect("f + i is one glyph").gid;
let chosen = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap()["chosen"].clone();
assert_eq!(chosen, json!(ligature));
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": null})).unwrap();
assert_eq!(r["gid"], chosen, "the ligature drawn for the i");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no edit");
assert_eq!(obj(&s, id).runs, runs, "the runs are kept");
}
/// A fallback face draws Ka with the vowel sign I in one cluster, the vowel sign first. The glyph
/// reported for Ka is the fallback face's glyph for Ka, laid out or overflowing, not the vowel
/// sign's.
+24
View File
@@ -345,3 +345,27 @@ fn scale_text_attributes_bakes_group_scale_and_undoes() {
s.execute("edit.undo", &json!({})).unwrap();
near(text(&s, id).runs[0].style.size, 12.0);
}
/// Scale Text Attributes bakes a horizontal stretch into the Horizontal Scale: tracked type stays
/// where the stretch drew it, as tracking is measured in the em the Horizontal Scale draws
/// (`vectorcraft_text::spacing_scale`). It used to lose the stretch's share of the tracking.
#[test]
fn scale_text_attributes_keeps_tracked_type_where_it_was() {
let mut s = session();
let id = create(&mut s, 20.0);
s.execute("text.setRangeStyle", &json!({"id": id.0, "tracking": 300})).unwrap();
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let pens = |s: &Session| {
let t = text(s, id);
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
lay.glyphs.iter().map(|g| t.xf * (g.xf * Point::ZERO)).collect::<Vec<_>>()
};
let before = pens(&s);
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
near(text(&s, id).runs[0].style.h_scale, 200.0);
let after = pens(&s);
assert_eq!(before.len(), after.len());
for (b, a) in before.iter().zip(&after) {
assert!((*a - *b).hypot() < 1e-6, "{before:?} {after:?}");
}
}
+75
View File
@@ -199,3 +199,78 @@ fn east_asian_type_unit_leaves_the_document_in_points() {
assert!((lead.unwrap() - Unit::Ha.to_pt(20.0)).abs() < 1e-9, "{lead:?}");
assert!((sz - 17.0 * 72.0 / 101.6).abs() < 1e-9);
}
/// A session whose Preferences › Units › General is `unit`, with no document open.
fn general_in(unit: &str) -> Session {
let mut s = Session::new();
s.execute("prefs.set", &json!({"key": "unitsGeneral", "value": unit})).unwrap();
s
}
/// `bytes` opened as `name` in `s` → the opened document's units.
fn opened_units(s: &mut Session, name: &str, bytes: &[u8]) -> Unit {
s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap();
units(s)
}
/// The active document of a session in `unit`, exported as `format`.
fn exported(unit: &str, format: &str) -> Vec<u8> {
let mut s = session();
s.execute("document.setUnits", &json!({"units": unit})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 30})).unwrap();
let data = s.execute("document.export", &json!({"format": format})).unwrap()["dataBase64"].clone();
vectorcraft_format::base64_decode(data.as_str().unwrap()).unwrap()
}
/// A PostScript `.ai` with one empty layer and `header` among its comments.
fn postscript_ai(header: &str) -> Vec<u8> {
format!(
"%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 14.0\n{header}%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n0 A\n0 Xw\n\nLB\n%AI5_EndLayer--\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n"
)
.into_bytes()
}
#[test]
fn files_that_record_no_units_open_in_the_general_unit() {
let pdf = vectorcraft_testkit::pdf::pdf(&[vectorcraft_testkit::pdf::PdfPage::new(120.0, 60.0, "0 0 0 rg 10 10 50 30 re f")], None);
let png = exported("Inches", "png");
let ai = postscript_ai("");
let mut s = general_in("Millimeters");
assert_eq!(opened_units(&mut s, "plain.pdf", &pdf), Unit::Millimeters, "a PDF records no units (#5820)");
assert_eq!(opened_units(&mut s, "image.png", &png), Unit::Millimeters, "nor does an image");
assert_eq!(opened_units(&mut s, "old.ai", &ai), Unit::Millimeters, "nor a .ai without ruler units");
// Only the units change: the page keeps its size in points.
s.execute("document.open", &json!({"name": "plain.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)})).unwrap();
let board = s.doc().unwrap().doc.artboards[0].rect;
assert!((board.width() - 120.0).abs() < 1e-6 && (board.height() - 60.0).abs() < 1e-6, "{board:?}");
// With the preference left at points, they open in points as before.
let mut p = general_in("Points");
assert_eq!(opened_units(&mut p, "plain.pdf", &pdf), Unit::Points);
}
#[test]
fn files_that_record_units_keep_them_whatever_the_general_unit() {
let mut s = general_in("Millimeters");
assert_eq!(opened_units(&mut s, "inches.ai", &postscript_ai("%AI5_RulerUnits: 0\n")), Unit::Inches, "a .ai's ruler units");
assert_eq!(opened_units(&mut s, "points.ai", &postscript_ai("%AI5_RulerUnits: 2\n")), Unit::Points, "ruler units in points are kept too");
assert_eq!(opened_units(&mut s, "saved.vectorcraft", &exported("Inches", "vectorcraft")), Unit::Inches, "a native file");
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="2in" height="1in" viewBox="0 0 144 72"><rect width="10" height="10"/></svg>"#;
assert_eq!(opened_units(&mut s, "inches.svg", svg.as_bytes()), Unit::Inches, "an SVG's root size");
}
#[test]
fn revert_reopens_a_file_without_units_in_the_general_unit() {
let dir = std::env::temp_dir().join(format!("vc-5820-revert-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("plain.pdf");
std::fs::write(&path, vectorcraft_testkit::pdf::pdf(&[vectorcraft_testkit::pdf::PdfPage::new(120.0, 60.0, "0 0 0 rg 10 10 50 30 re f")], None))
.unwrap();
let mut s = general_in("Millimeters");
s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(units(&s), Unit::Millimeters);
s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 5, "height": 5})).unwrap();
s.execute("document.setUnits", &json!({"units": "Inches"})).unwrap();
s.execute("file.revert", &json!({})).unwrap();
assert_eq!(units(&s), Unit::Millimeters, "as the file opens");
let _ = std::fs::remove_dir_all(&dir);
}
+9 -3
View File
@@ -708,6 +708,14 @@ impl Session {
Ok(())
}
/// The artboard a guide made from a ruler belongs to: with the Artboard tool, its active
/// artboard (an artboard guide); with any other tool, none (a canvas guide).
pub fn ruler_guide_artboard(&self) -> Option<usize> {
let boards = self.active().map_or(0, |d| d.doc.artboards.len());
let active = (self.tool.id() == "artboard").then(|| self.tool.options()["active"].as_u64()).flatten();
active.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < boards)
}
/// A guide dragged out of a ruler, whatever the tool: a vertical one out of the left ruler, a
/// horizontal one out of the top ruler. `ev` is the pointer in document space (a drag, then the
/// release), over the canvas or not (`on_canvas`). The guide shows where the pointer is over
@@ -722,11 +730,9 @@ impl Session {
let g = match self.ruler_guide.take() {
Some(g) => Some(g),
None => {
let boards = self.active().map_or(0, |d| d.doc.artboards.len());
let artboard_tool = self.tool.id() == "artboard";
let swap = self.prefs.cmd_ruler_drag_artboard_guides && ev.mods.cmd;
let active = artboard_tool.then(|| self.tool.options()["active"].as_u64()).flatten();
let artboard = active.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < boards);
let artboard = self.ruler_guide_artboard();
let view_board = view.artboard;
self.with_tool_cx(view, |_, cx| {
Some(match (swap, artboard_tool) {
+1 -1
View File
@@ -44,7 +44,7 @@ impl Measure {
}
/// The unit a Units preference value names (points when it names none).
fn pref_unit(value: &str) -> Unit {
pub(crate) fn pref_unit(value: &str) -> Unit {
Unit::named(value).unwrap_or_default()
}
+52 -15
View File
@@ -9,10 +9,11 @@ use vectorcraft_engine::{Session, command_specs};
use vectorcraft_testkit::catch_quiet;
use vectorcraft_testkit::fixtures::Fixture;
use vectorcraft_testkit::invariants::{check_all, check_session, doc_json};
use vectorcraft_testkit::strategies::{junk_params, junk_values, param_keys};
use vectorcraft_testkit::strategies::{junk_params, junk_values, param_keys, safe_value};
/// Commands that replace/close the active document or touch the filesystem are fine to call, but a
/// few need their paths redirected into a temp dir (handled by `junk_params`).
/// few need their file and folder params redirected into a temp dir (`safe_value`, which
/// `junk_params` applies).
fn safe_path() -> String {
vectorcraft_testkit::temp_dir("sweep").join("out.bin").to_string_lossy().to_string()
}
@@ -230,6 +231,54 @@ fn tool_edit_state(s: &Session) -> ToolEditState {
(docs, s.active_index(), s.paint.clone())
}
/// The params the tool-edit sweep sends `c`: junk params, then each documented key turned on and
/// off, with a string under a file or folder key replaced by a location inside `path`'s folder.
fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value> {
let mut cases = junk_params(c.params, path);
if heavy(c.id) {
cases.truncate(12);
}
for k in param_keys(c.params) {
for v in [json!(true), json!(false), json!(1), json!("on")] {
cases.push(json!({ k.as_str(): safe_value(&k, &v, path) }));
}
}
// Find Objects selects only with a filter, which one key at a time does not give it.
if c.id == "document.find" {
cases.extend([json!({"kind": "Path", "select": true}), json!({"name": "no such name", "select": true})]);
}
cases
}
/// Every string the sweeps send under a key that names a file or folder to write is inside the
/// sweep's temp folder, so no run writes into the working directory.
#[test]
fn sweep_cases_name_files_only_inside_the_temp_folder() {
let path = safe_path();
let dir = vectorcraft_testkit::temp_dir("sweep");
let keys = ["path", "diffPath", "folder", "destinationFolder"];
let mut seen = std::collections::BTreeSet::new();
let mut outside = std::collections::BTreeSet::new();
for c in command_specs() {
let mut cases = junk_params(c.params, &path);
cases.extend(tool_edit_cases(c, &path));
for p in &cases {
let Some(o) = p.as_object() else { continue };
for (k, v) in o.iter().filter(|(k, _)| keys.contains(&k.as_str())) {
seen.insert(k.clone());
if let Some(s) = v.as_str()
&& !std::path::Path::new(s).starts_with(&dir)
{
outside.insert(format!("{} {{\"{k}\": {v}}}", c.id));
}
}
}
}
assert_eq!(seen.len(), keys.len(), "the sweeps send only {seen:?}");
let outside: Vec<String> = outside.into_iter().collect();
assert!(outside.is_empty(), "{} cases name a location outside {}:\n{}", outside.len(), dir.display(), outside.join("\n"));
}
/// Every command that runs at once while the active tool computes an edit on another thread (a
/// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the
/// documents' revisions and selections, the active document and the current paint as they were,
@@ -241,19 +290,7 @@ fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() {
let mut failures = vec![];
for fx in [Fixture::Single, Fixture::Multi] {
for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) {
let mut cases = junk_params(c.params, &path);
if heavy(c.id) {
cases.truncate(12);
}
for k in param_keys(c.params) {
for v in [json!(true), json!(false), json!(1), json!("on")] {
cases.push(json!({ k.as_str(): v }));
}
}
// Find Objects selects only with a filter, which one key at a time does not give it.
if c.id == "document.find" {
cases.extend([json!({"kind": "Path", "select": true}), json!({"name": "no such name", "select": true})]);
}
let cases = tool_edit_cases(c, &path);
for p in &cases {
let mut s = fx.session();
let before = tool_edit_state(&s);
+20
View File
@@ -663,6 +663,26 @@ proptest! {
survive(&svg, || vectorcraft_svg::import(&svg).ok())?;
}
/// Clip paths made of text, of `<use>` elements showing text, and of both with shapes, each with
/// hostile attributes, clipping art that may clip by them in turn.
#[test]
fn svg_text_clip_paths_never_panic(
text in prop::collection::vec(arb_svg_attr(), 0..5),
used in prop::collection::vec(arb_svg_attr(), 0..5),
clip in prop::collection::vec(arb_svg_attr(), 0..3),
body in prop::collection::vec(arb_svg_element(1), 0..3),
) {
let svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><defs><text id=\"t\" font-size=\"20\"{}>ab<tspan dy=\"3\">c</tspan></text></defs><clipPath id=\"e\"{}><text y=\"30\"{}>Clip<tspan x=\"5\" y=\"60\">it</tspan></text><use href=\"#t\"{}/><rect width=\"5\" height=\"5\"/></clipPath><clipPath id=\"f\" clip-path=\"url(#e)\"><use xlink:href=\"#t\" x=\"9\"/></clipPath><rect width=\"90\" height=\"90\" clip-path=\"url(#e)\"/><g clip-path=\"url(#f)\">{}</g></svg>",
text.concat(),
clip.concat(),
text.concat(),
used.concat(),
body.concat()
);
survive(&svg, || vectorcraft_svg::import(&svg).ok())?;
}
#[test]
fn svg_mutated_export_never_panics(
cut in 0usize..20_000,
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff. Show more