mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 17:05:55 +01:00
#6490: reconcile transform validation with upstream main
This commit is contained in:
commit
a776bbe5ab
312 files changed
+22984
-1043
No files matched your search
Generated
+2
-1
@@ -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
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
+436
-15
@@ -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)]
|
||||
@@ -25,6 +25,17 @@ impl DimensionMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// The direction a linear dimension measures in: along the line through its two points, or only
|
||||
/// their horizontal or vertical distance.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Orientation {
|
||||
#[default]
|
||||
Aligned,
|
||||
Horizontal,
|
||||
Vertical,
|
||||
}
|
||||
|
||||
/// The unit a length is labelled in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -295,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>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -304,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
|
||||
@@ -321,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)]
|
||||
@@ -337,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 {
|
||||
@@ -349,6 +627,10 @@ pub struct Dimension {
|
||||
pub length: f64,
|
||||
pub options: DimensionOptions,
|
||||
pub source: Option<DimensionSource>,
|
||||
/// What a linear dimension measures: the distance between its points (aligned), or only its
|
||||
/// horizontal or vertical part. Other modes ignore it.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub orientation: Orientation,
|
||||
/// How far a linked dimension was moved on its own since the last refresh: the refresh turns
|
||||
/// it into a new placement unless the measured art moved too.
|
||||
#[serde(skip)]
|
||||
@@ -359,16 +641,137 @@ impl Dimension {
|
||||
/// A point on the drawn dimension line (linear), arc (angular) or radius line.
|
||||
pub fn handle(&self) -> Point {
|
||||
match self.mode {
|
||||
DimensionMode::Linear => self.a.midpoint(self.b) + self.normal() * self.offset,
|
||||
DimensionMode::Linear => {
|
||||
let (a, b) = self.line_ends();
|
||||
a.midpoint(b)
|
||||
}
|
||||
DimensionMode::Angular => self.vertex + self.bisector() * self.offset.abs().max(12.0),
|
||||
DimensionMode::Radius | DimensionMode::Diameter => self.b,
|
||||
}
|
||||
}
|
||||
/// The left normal of a → b.
|
||||
/// The unit direction a linear dimension measures along: a → b when aligned, else the x axis
|
||||
/// (horizontal) or the y axis (vertical), whichever way the points lie.
|
||||
pub fn direction(&self) -> Vec2 {
|
||||
match self.orientation {
|
||||
Orientation::Horizontal if self.mode == DimensionMode::Linear => Vec2::new(1.0, 0.0),
|
||||
Orientation::Vertical if self.mode == DimensionMode::Linear => Vec2::new(0.0, 1.0),
|
||||
_ => {
|
||||
let u = self.b - self.a;
|
||||
let len = u.hypot();
|
||||
if len > 1e-9 { u / len } else { Vec2::new(1.0, 0.0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The left normal of [`Self::direction`].
|
||||
pub fn normal(&self) -> Vec2 {
|
||||
let u = self.b - self.a;
|
||||
let len = u.hypot();
|
||||
if len > 1e-9 { Vec2::new(-u.y, u.x) / len } else { Vec2::new(0.0, 1.0) }
|
||||
let u = self.direction();
|
||||
Vec2::new(-u.y, u.x)
|
||||
}
|
||||
/// The length a linear dimension shows: the distance between its points along
|
||||
/// [`Self::direction`].
|
||||
pub fn measured(&self) -> f64 {
|
||||
(self.b - self.a).dot(self.direction()).abs()
|
||||
}
|
||||
/// The two ends of a linear dimension's line: the measured points moved onto one line along
|
||||
/// [`Self::direction`], `offset` from a along the normal.
|
||||
pub fn line_ends(&self) -> (Point, Point) {
|
||||
let (u, n) = (self.direction(), self.normal());
|
||||
let a = self.a + n * self.offset;
|
||||
(a, a + u * (self.b - self.a).dot(u))
|
||||
}
|
||||
/// A horizontal or vertical dimension whose points moved from `old`'s keeps its line as far
|
||||
/// outside them as it was, on the same side: the gap is measured from the outermost point
|
||||
/// on the line's side, so the line stays clear of art that turns. A line that lay between
|
||||
/// the two points keeps its distance from the first point.
|
||||
pub fn keep_gap(&mut self, old: &Dimension) {
|
||||
if self.mode != DimensionMode::Linear
|
||||
|| self.orientation == Orientation::Aligned
|
||||
|| old.orientation != self.orientation
|
||||
|| (self.a, self.b) == (old.a, old.b)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let n = self.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)));
|
||||
let (new_low, new_high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
|
||||
let at = if line >= high {
|
||||
new_high + (line - high)
|
||||
} else if line <= low {
|
||||
new_low + (line - low)
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
let offset = at - across(self.a);
|
||||
if offset.is_finite() && offset.abs() <= 1e6 {
|
||||
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();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let line = across(self.a) + self.offset;
|
||||
across(self.a).min(across(self.b)) < line && line < across(self.a).max(across(self.b))
|
||||
}
|
||||
/// Makes a linear dimension measure in `orientation`, with its line on the side of the points
|
||||
/// it was on. The line goes through the middle of the old line when that point lies outside
|
||||
/// the two points along the new normal; otherwise it lies as far past the outermost point on
|
||||
/// that side as the old line lay from its points.
|
||||
pub fn set_orientation(&mut self, orientation: Orientation) {
|
||||
if self.mode != DimensionMode::Linear || self.orientation == orientation {
|
||||
self.orientation = orientation;
|
||||
return;
|
||||
}
|
||||
let (handle, gap) = (self.handle(), self.offset.abs());
|
||||
self.orientation = orientation;
|
||||
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 h = across(handle);
|
||||
let at = if h >= high || h <= low {
|
||||
h
|
||||
} else if 2.0 * h >= low + high {
|
||||
high + gap
|
||||
} else {
|
||||
low - gap
|
||||
};
|
||||
let offset = at - across(self.a);
|
||||
if offset.is_finite() && offset.abs() <= 1e6 {
|
||||
self.offset = offset;
|
||||
}
|
||||
self.length = self.measured();
|
||||
}
|
||||
fn bisector(&self) -> Vec2 {
|
||||
let start = (self.a - self.vertex).atan2();
|
||||
@@ -397,28 +800,46 @@ impl Dimension {
|
||||
self.moved = Some((xf * at) - at + self.moved.unwrap_or_default());
|
||||
return;
|
||||
}
|
||||
// A horizontal or vertical dimension keeps measuring along its axis, between the points
|
||||
// where they now are, and its line goes through where the transform puts it. When that
|
||||
// puts the line between the points (a quarter turn), the line keeps its gap from them.
|
||||
let before = (self.mode == DimensionMode::Linear && self.orientation != Orientation::Aligned).then(|| (self.clone(), xf * self.handle()));
|
||||
self.a = xf * self.a;
|
||||
self.b = xf * self.b;
|
||||
self.vertex = xf * self.vertex;
|
||||
if let Some((old, p)) = before {
|
||||
let offset = (p - self.a).dot(self.normal());
|
||||
if offset.is_finite() && offset.abs() <= 1e6 {
|
||||
self.offset = offset;
|
||||
}
|
||||
if self.line_between_points() && !old.line_between_points() {
|
||||
self.keep_gap(&old);
|
||||
}
|
||||
}
|
||||
if self.mode == DimensionMode::Linear {
|
||||
self.length = self.a.distance(self.b);
|
||||
self.length = self.measured();
|
||||
}
|
||||
}
|
||||
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 = self.a.distance(self.b);
|
||||
self.length = if self.mode == DimensionMode::Linear { self.measured() } else { self.a.distance(self.b) };
|
||||
}
|
||||
Some(DimensionSource::Segment { edge }) => {
|
||||
let (a, b) = edge.endpoints(doc).ok_or("Measured segment no longer exists")?;
|
||||
self.a = a;
|
||||
self.b = b;
|
||||
self.length = a.distance(b);
|
||||
self.length = self.measured();
|
||||
}
|
||||
Some(DimensionSource::Angle { first, second }) => {
|
||||
for edge in [first, second] {
|
||||
@@ -486,7 +907,7 @@ impl Dimension {
|
||||
DimensionMode::Angular => self.angle().abs().to_degrees(),
|
||||
DimensionMode::Radius => self.a.distance(self.b),
|
||||
DimensionMode::Diameter => self.a.distance(self.b) * 2.0,
|
||||
DimensionMode::Linear => self.a.distance(self.b),
|
||||
DimensionMode::Linear => self.measured(),
|
||||
};
|
||||
self.options.label(value, self.mode == DimensionMode::Angular)
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -870,10 +870,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
on_type_path(n, t, p, opt.tol).then_some(HitKind::Outline)
|
||||
}
|
||||
// An image is hit within its frame (on the frame's edge only with Selection by Path Only,
|
||||
// #3291), and where its own fills and strokes paint ([`image_paint`]) except in outline
|
||||
// mode.
|
||||
// #3291, and in outline mode where the frame is all that is drawn, #6437), and where its
|
||||
// own fills and strokes paint ([`image_paint`]) except in outline mode.
|
||||
NodeKind::Image(im) => {
|
||||
if opt.path_only {
|
||||
if opt.path_only || (opt.outline && !symbols.document().setup.outline_images) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let mut frame = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1);
|
||||
frame.apply_affine(im.xf);
|
||||
@@ -909,6 +909,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if stroke_contains(&bp, 0.0, opt.tol, p) {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
// Outline mode draws the mesh lines, not the colours between them (#6437).
|
||||
if opt.outline {
|
||||
return stroke_contains(&m.lines().to_bezpath(), 0.0, opt.tol, p).then_some(HitKind::Outline);
|
||||
}
|
||||
(!opt.path_only && fill_contains(&bp, vectorcraft_geom::FillRule::NonZero, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
_ => None,
|
||||
|
||||
@@ -880,6 +880,45 @@ fn path_only_picks_paths_through_images() {
|
||||
assert_eq!(hit(image_edge, path_only), Some(image), "path only: the image's frame");
|
||||
}
|
||||
|
||||
/// #6437: in outline mode an image is drawn as its frame and a gradient mesh as its mesh lines,
|
||||
/// so a click inside them, on the outline of a path behind, picks that path, and a click on the
|
||||
/// frame or a mesh line picks the image or the mesh. In Preview they cover the path as before,
|
||||
/// and an image whose pixels show in outline mode (Show Images in Outline Mode) still does.
|
||||
#[test]
|
||||
fn outline_mode_picks_paths_through_images_and_meshes() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (path, image, under, mesh) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(path, shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
let xf = vectorcraft_geom::Affine::translate((10.0, 10.0));
|
||||
let im = crate::ImageObject { key: "k".into(), width: 80, height: 80, xf, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(l), 1, Node::new(image, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
d.insert(Some(l), 2, Node::path(under, shapes::rectangle(Rect::new(120.0, 120.0, 160.0, 160.0)), Appearance::default_art())).unwrap();
|
||||
let area = shapes::rectangle(Rect::new(110.0, 110.0, 190.0, 190.0));
|
||||
let m = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap();
|
||||
d.insert(Some(l), 3, Node::new(mesh, NodeKind::Mesh(m))).unwrap();
|
||||
let outline = HitOptions { outline: true, ..Default::default() };
|
||||
let hit = |d: &Document, p: Point, opt| hit_test(d, p, opt).map(|h| h.leaf);
|
||||
// The image: the path's edge and the inside, then the frame.
|
||||
let (path_edge, inside, frame) = (Point::new(20.5, 40.0), Point::new(80.0, 80.0), Point::new(89.5, 50.0));
|
||||
assert_eq!(hit(&d, path_edge, HitOptions::default()), Some(image), "Preview: the image covers the path");
|
||||
assert_eq!(hit(&d, inside, HitOptions::default()), Some(image));
|
||||
assert_eq!(hit(&d, path_edge, outline), Some(path), "outline: the path through the image");
|
||||
assert_eq!(hit(&d, inside, outline), None, "outline: not inside the image");
|
||||
assert_eq!(hit(&d, frame, outline), Some(image), "outline: the image's frame");
|
||||
// The mesh: the path's edge and the inside, then its edge and a mesh line inside it.
|
||||
let (under_edge, inside, edge, line) = (Point::new(120.5, 130.0), Point::new(130.0, 170.0), Point::new(189.5, 130.0), Point::new(150.0, 170.0));
|
||||
assert_eq!(hit(&d, under_edge, HitOptions::default()), Some(mesh), "Preview: the mesh covers the path");
|
||||
assert_eq!(hit(&d, inside, HitOptions::default()), Some(mesh));
|
||||
assert_eq!(hit(&d, under_edge, outline), Some(under), "outline: the path through the mesh");
|
||||
assert_eq!(hit(&d, inside, outline), None, "outline: not between the mesh lines");
|
||||
assert_eq!(hit(&d, edge, outline), Some(mesh), "outline: the mesh's edge");
|
||||
assert_eq!(hit(&d, line, outline), Some(mesh), "outline: a mesh line");
|
||||
// Show Images in Outline Mode: the image's pixels are drawn, and it covers the path again.
|
||||
d.setup.outline_images = true;
|
||||
assert_eq!(hit(&d, path_edge, outline), Some(image));
|
||||
}
|
||||
|
||||
/// Type Object Selection by Path Only: point type is picked on its baseline, area type on its
|
||||
/// frame and type on a path on its path, no longer anywhere in its bounds.
|
||||
#[test]
|
||||
|
||||
+41
-5
@@ -110,8 +110,9 @@ fn visit_paint(p: &mut Paint, f: &mut ColorVisitor) {
|
||||
}
|
||||
|
||||
/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, an
|
||||
/// image's colorize color, not opacity masks) with its swatch link and tint. Mesh points have no
|
||||
/// link: changes to it are dropped.
|
||||
/// image's colorize color, the fills and strokes a dynamic symbol instance keeps for objects of its
|
||||
/// art, not opacity masks) with its swatch link and tint. Mesh points have no link: changes to it
|
||||
/// are dropped.
|
||||
pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
@@ -119,8 +120,13 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
|
||||
AppearanceItem::Stroke(l) => visit_paint(&mut l.paint, f),
|
||||
}
|
||||
}
|
||||
if let Some(p) = n.extras.0.as_deref_mut().and_then(|e| e.colorize.as_deref_mut()) {
|
||||
visit_paint(p, f);
|
||||
if let Some(e) = n.extras.0.as_deref_mut() {
|
||||
if let Some(p) = e.colorize.as_deref_mut() {
|
||||
visit_paint(p, f);
|
||||
}
|
||||
for p in e.symbol_overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() {
|
||||
visit_paint(p, f);
|
||||
}
|
||||
}
|
||||
match &mut n.kind {
|
||||
NodeKind::Text(t) => {
|
||||
@@ -144,7 +150,8 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
|
||||
}
|
||||
|
||||
/// Apply `f` to every colour of a node tree (fills, strokes, gradient stops, text runs, mesh
|
||||
/// points) given its swatch link and tint, keeping the links.
|
||||
/// points, a dynamic symbol instance's own fills and strokes) given its swatch link and tint,
|
||||
/// keeping the links.
|
||||
pub fn map_node_colors(n: &mut Node, f: &mut dyn FnMut(&Color, Link) -> Color) {
|
||||
visit_node_colors(n, &mut |c, swatch, tint| *c = f(c, swatch.as_deref().map(|s| (s, *tint))));
|
||||
}
|
||||
@@ -158,3 +165,32 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
|
||||
map_node_colors(Arc::make_mut(&mut s.art), f);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{NodeId, SymbolOverride};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
#[test]
|
||||
fn a_dynamic_instances_own_fills_and_strokes_are_visited() {
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let blue = Color::rgb(0.0, 0.0, 1.0);
|
||||
let spot = Paint::Solid { color: red, swatch: Some("Spot".into()), tint: 0.5 };
|
||||
let mut inst = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::IDENTITY });
|
||||
inst.extras_mut().symbol_overrides = vec![
|
||||
SymbolOverride { path: vec![0], fill: Some(spot), stroke: Some(Paint::solid(red)), ..Default::default() },
|
||||
SymbolOverride { path: vec![1], opacity: Some(0.5), ..Default::default() },
|
||||
];
|
||||
let mut links = vec![];
|
||||
map_node_colors(&mut inst, &mut |_, link| {
|
||||
links.push(link.map(|(s, t)| (s.to_string(), t)));
|
||||
blue
|
||||
});
|
||||
assert_eq!(links, vec![Some(("Spot".to_string(), 0.5)), None], "each override paint is visited once, with its link");
|
||||
let o = &inst.extras().symbol_overrides;
|
||||
assert_eq!(o[0].fill, Some(Paint::Solid { color: blue, swatch: Some("Spot".into()), tint: 0.5 }), "the link is kept");
|
||||
assert_eq!(o[0].stroke, Some(Paint::solid(blue)));
|
||||
assert_eq!((o[1].fill.as_ref(), o[1].stroke.as_ref()), (None, None), "an override without paint gets none");
|
||||
}
|
||||
}
|
||||
@@ -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")]
|
||||
|
||||
@@ -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)?]))
|
||||
}
|
||||
}
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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, ¶ms, bounds, room, doc) {
|
||||
if let Some(made) = paint_leaf(leaf, plugin, ¶ms, 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, ¶ms, &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, ¶ms, &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, ¶ms, &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));
|
||||
|
||||
@@ -25,17 +25,33 @@ const MAX_OVERLAP_TESTS: usize = 1 << 22;
|
||||
/// The width of the stroke around each face that covers the seams between faces.
|
||||
const SEAM_WIDTH: f64 = 0.75;
|
||||
|
||||
/// About the bytes one copy of `paint` takes.
|
||||
/// About the bytes one copy of `paint` takes, with the strings it owns (swatch and pattern names).
|
||||
fn paint_bytes(paint: &Paint) -> usize {
|
||||
use std::mem::size_of;
|
||||
use vectorcraft_doc::color::{FreeformPoint, GradientStop};
|
||||
let own = size_of::<Paint>();
|
||||
let Paint::Gradient(g) = paint else { return own };
|
||||
let freeform = g
|
||||
.freeform
|
||||
.as_ref()
|
||||
.map_or(0, |f| f.points.len() * size_of::<FreeformPoint>() + f.lines.iter().map(|l| l.len() * size_of::<usize>()).sum::<usize>());
|
||||
own + size_of::<vectorcraft_doc::color::GradientPaint>() + g.gradient.stops.len() * size_of::<GradientStop>() + freeform
|
||||
let name = |s: &Option<String>| s.as_ref().map_or(0, String::len);
|
||||
let g = match paint {
|
||||
Paint::Solid { swatch, .. } => return own + name(swatch),
|
||||
Paint::Pattern { pattern, .. } => return own + pattern.len(),
|
||||
Paint::Gradient(g) => g,
|
||||
_ => return own,
|
||||
};
|
||||
let freeform = g.freeform.as_ref().map_or(0, |f| {
|
||||
// Each line is a Vec: its header too, not only its indices.
|
||||
f.points.len() * size_of::<FreeformPoint>()
|
||||
+ f.lines.len() * size_of::<Vec<usize>>()
|
||||
+ f.lines.iter().map(|l| l.len() * size_of::<usize>()).sum::<usize>()
|
||||
});
|
||||
let stops: usize = g.gradient.stops.iter().map(|s| size_of::<GradientStop>() + name(&s.swatch)).sum();
|
||||
own + size_of::<vectorcraft_doc::color::GradientPaint>() + name(&g.swatch) + stops + freeform
|
||||
}
|
||||
|
||||
/// Add `copies` copies of `paint` to the running byte total `used`; whether it still fits within
|
||||
/// [`MAX_PAINT_COPIES`] (for the solid surfaces, whose items' copies count together).
|
||||
pub(crate) fn paint_copies_add(used: &mut usize, copies: usize, paint: &Paint) -> bool {
|
||||
*used = used.saturating_add(copies.saturating_mul(paint_bytes(paint)));
|
||||
*used <= MAX_PAINT_COPIES
|
||||
}
|
||||
|
||||
fn visible(fx: &[Effect]) -> bool {
|
||||
@@ -463,22 +479,19 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
|
||||
/// The members' `surfaces`, or runs of their faces, in order, from the [`Scope`] at `level` of each
|
||||
/// one's `Profile::scopes` inward: consecutive surfaces that share a scope go in one group with its
|
||||
/// opacity and blending mode, so each applies once, to the faces it holds together.
|
||||
fn scoped(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>, level: usize) -> Vec<Arc<Node>> {
|
||||
fn close(id: NodeId, run: &mut Vec<(&[Scope], Arc<Node>)>, scope: Option<Scope>, level: usize, out: &mut Vec<Arc<Node>>) {
|
||||
/// opacity, blending mode and opacity mask, so each applies once, to the faces it holds together.
|
||||
pub(crate) fn scoped<'a>(id: NodeId, surfaces: Vec<(&'a [Scope], Arc<Node>)>, level: usize) -> Vec<Arc<Node>> {
|
||||
fn close(id: NodeId, run: &mut Vec<(&[Scope], Arc<Node>)>, scope: Option<&Scope>, level: usize, out: &mut Vec<Arc<Node>>) {
|
||||
if let Some(scope) = scope {
|
||||
let mut group = Node::group(id, scoped(id, std::mem::take(run), level + 1));
|
||||
group.opacity = scope.opacity;
|
||||
group.blend = scope.blend;
|
||||
out.push(Arc::new(group));
|
||||
out.push(Arc::new(scope.group(id, scoped(id, std::mem::take(run), level + 1))));
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
let mut run = vec![];
|
||||
let mut scope = None;
|
||||
let mut scope: Option<&'a Scope> = None;
|
||||
for (scopes, s) in surfaces {
|
||||
let at = scopes.get(level).copied();
|
||||
if at.map(|a| a.key) != scope.map(|s: Scope| s.key) {
|
||||
let at = scopes.get(level);
|
||||
if at.map(|a| a.key) != scope.map(|s| s.key) {
|
||||
close(id, &mut run, scope, level, &mut out);
|
||||
scope = at;
|
||||
}
|
||||
|
||||
+110
-32
@@ -4,7 +4,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View};
|
||||
|
||||
@@ -238,20 +238,68 @@ pub(crate) fn object_profile(n: &Node, label: &str) -> Result<(PathData, FillRul
|
||||
})
|
||||
}
|
||||
|
||||
/// A group in a 3D effect's group, or a member of it, whose opacity is below 100% or whose blending
|
||||
/// mode is not Normal. The members of one group share its `key`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
/// A group in a 3D effect's group, or a member of it, whose opacity is below 100%, whose blending
|
||||
/// mode is not Normal or that has an opacity mask. The members of one group share its `key`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Scope {
|
||||
pub(crate) key: usize,
|
||||
pub(crate) opacity: f32,
|
||||
pub(crate) blend: BlendMode,
|
||||
/// The object's opacity mask, unless it has none or it is disabled. The mask art is in
|
||||
/// document coordinates, as the solids' faces are.
|
||||
pub(crate) mask: Option<Arc<OpacityMask>>,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
/// The scope of `n` with key `key`, or `None` when `n` is opaque, blends normally and has no
|
||||
/// opacity mask that applies.
|
||||
fn of(n: &Node, key: usize) -> Option<Self> {
|
||||
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled);
|
||||
(n.opacity < 1.0 || n.blend != BlendMode::Normal || mask.is_some()).then(|| Scope {
|
||||
key,
|
||||
opacity: n.opacity,
|
||||
blend: n.blend,
|
||||
mask: mask.map(|m| Arc::new(m.clone())),
|
||||
})
|
||||
}
|
||||
|
||||
/// A group of `children` with id `id` and this scope's opacity, blending mode and opacity mask.
|
||||
pub(crate) fn group(&self, id: NodeId, children: Vec<Arc<Node>>) -> Node {
|
||||
let mut group = Node::group(id, children);
|
||||
group.opacity = self.opacity;
|
||||
group.blend = self.blend;
|
||||
if let Some(mask) = &self.mask {
|
||||
group.extras_mut().mask = Some(Box::new((**mask).clone()));
|
||||
}
|
||||
group
|
||||
}
|
||||
}
|
||||
|
||||
/// `surfaces`, each with the scopes of the member it was built from, in groups with the opacity
|
||||
/// masks of those scopes, so each mask applies to the faces of the members it holds. The members'
|
||||
/// opacity is already in their paint ([`Profile::opacity`]), so these groups are opaque.
|
||||
fn masked(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>) -> Vec<Arc<Node>> {
|
||||
let masks: Vec<(Vec<Scope>, Arc<Node>)> = surfaces
|
||||
.into_iter()
|
||||
.map(|(scopes, s)| {
|
||||
let masks = scopes.iter().filter(|s| s.mask.is_some()).map(|s| Scope { opacity: 1.0, blend: BlendMode::Normal, ..s.clone() }).collect();
|
||||
(masks, s)
|
||||
})
|
||||
.collect();
|
||||
crate::revolve::scoped(id, masks.iter().map(|(scopes, s)| (scopes.as_slice(), s.clone())).collect(), 0)
|
||||
}
|
||||
|
||||
/// Does any of `shapes` sit in a scope with an opacity mask?
|
||||
fn has_masks(shapes: &[Profile]) -> bool {
|
||||
shapes.iter().any(|s| s.scopes.iter().any(|s| s.mask.is_some()))
|
||||
}
|
||||
|
||||
/// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint
|
||||
/// it, and the opacity of the objects it is in multiplied together (1 for the object with the
|
||||
/// effect itself). `scopes` lists those objects with transparency of their own ([`Scope`]), from
|
||||
/// the outermost group down to the member itself (none for the object itself). Group Revolve
|
||||
/// applies each once, to the surfaces of the members it holds together.
|
||||
/// effect itself). `scopes` lists those objects with transparency or an opacity mask of their own
|
||||
/// ([`Scope`]), from the outermost group down to the member itself (none for the object itself).
|
||||
/// Group Revolve applies each once, to the surfaces of the members it holds together; the other 3D
|
||||
/// effects apply each opacity mask that way.
|
||||
pub(crate) struct Profile {
|
||||
pub(crate) path: PathData,
|
||||
pub(crate) rule: FillRule,
|
||||
@@ -298,9 +346,9 @@ pub(crate) fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
|
||||
}
|
||||
let opacity = opacity * c.opacity;
|
||||
let mut scopes = scopes.to_vec();
|
||||
if c.blend != BlendMode::Normal || c.opacity < 1.0 {
|
||||
if let Some(scope) = Scope::of(c, w.keys + 1) {
|
||||
w.keys += 1;
|
||||
scopes.push(Scope { key: w.keys, opacity: c.opacity, blend: c.blend });
|
||||
scopes.push(scope);
|
||||
}
|
||||
if is_container(c) {
|
||||
let first = w.out.len();
|
||||
@@ -436,6 +484,21 @@ fn paint_of(item: &AppearanceItem, member: f32) -> (Paint, f32, BlendMode) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `item`'s paint, borrowed (for checks that must not copy it).
|
||||
fn paint_ref(item: &AppearanceItem) -> &Paint {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => &f.paint,
|
||||
AppearanceItem::Stroke(s) => &s.paint,
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), six when colored
|
||||
/// lights give each facet derived paints (`lighting::solid_surface`).
|
||||
fn facet_copies(facets: &[Facet], paint: &Paint, colored: bool) -> usize {
|
||||
let derived = colored && paint.color().is_some() && facets.iter().any(|f| f.rgb_gradient.is_some());
|
||||
facets.len().saturating_mul(if derived { 6 } else { 2 })
|
||||
}
|
||||
|
||||
/// The area `item` paints on `path`, and the rule that fills it: the path itself for a fill, the
|
||||
/// stroke's outline (whose contours nest as its holes do) for a stroke.
|
||||
fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, FillRule) {
|
||||
@@ -445,22 +508,26 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData,
|
||||
}
|
||||
}
|
||||
|
||||
/// One part of [`solid_parts`]: a fill or stroke, its shape's opacity, the region it paints and its
|
||||
/// fill rule, and its shape's scopes.
|
||||
type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope]);
|
||||
|
||||
/// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes,
|
||||
/// a group's members from the back up, each with its shape's opacity and the region it paints.
|
||||
/// The solids share the bounds of all their parts (`fallback` when none has any): one center to
|
||||
/// turn, twist and taper about, and Inflate's grid reaches over the strokes' outlines.
|
||||
fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<(&AppearanceItem, f32, PathData, FillRule)>, Rect) {
|
||||
let parts: Vec<(&AppearanceItem, f32, PathData, FillRule)> = shapes
|
||||
/// a group's members from the back up, each with its shape's opacity, the region it paints and its
|
||||
/// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any):
|
||||
/// one center to turn, twist and taper about, and Inflate's grid reaches over the strokes' outlines.
|
||||
fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
|
||||
let parts: Vec<Part> = shapes
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
|
||||
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| {
|
||||
let (area, rule) = region(&s.path, s.rule, i);
|
||||
(i, s.opacity, area, rule)
|
||||
(i, s.opacity, area, rule, s.scopes.as_slice())
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let bounds = parts.iter().filter_map(|(_, _, area, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback);
|
||||
let bounds = parts.iter().filter_map(|(_, _, area, _, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback);
|
||||
(parts, bounds)
|
||||
}
|
||||
|
||||
@@ -483,12 +550,16 @@ pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile
|
||||
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
|
||||
/// a surface one composite or masks it, their faces are drawn in one back-to-front order (where
|
||||
/// depths tie, as for the caps turned toward the viewer, in the order of the appearance);
|
||||
/// otherwise each solid is a surface of its own, in that order.
|
||||
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask, or that of
|
||||
/// a group it is in, masks the surfaces of the members it holds ([`masked`]).
|
||||
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
let b = union_bounds(shapes)?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let classic = fx.id == CLASSIC_EXTRUDE;
|
||||
let colored = !classic && view_options(&p).has_colored_lights();
|
||||
let masks = has_masks(shapes);
|
||||
// The paint copies of every solid together: past the allowance the source path is drawn.
|
||||
let mut paint_bytes = 0usize;
|
||||
if fx.id == ROTATE {
|
||||
// Every part turns about the centre of the object's own bounds (a group's members about
|
||||
// the centre of theirs), so they stay together.
|
||||
@@ -498,24 +569,28 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
|
||||
let (paint, opacity, blend) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
let f = facets(ROTATE, &area, rule, b, &p).ok()?;
|
||||
out.push(Arc::new(surface(n, f, &paint, opacity, blend, colored)));
|
||||
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
|
||||
return None;
|
||||
}
|
||||
out.push((s.scopes.as_slice(), Arc::new(surface(n, f, &paint, opacity, blend, colored))));
|
||||
}
|
||||
}
|
||||
return Some(out);
|
||||
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let built = if fx.id == INFLATE {
|
||||
// One eye for every puff, as far away as the highest needs.
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _)| (area, *rule)).collect();
|
||||
vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p))
|
||||
} else {
|
||||
parts.iter().map(|(_, _, area, rule)| facets(&fx.id, area, *rule, bounds, &p)).collect()
|
||||
parts.iter().map(|(_, _, area, rule, _)| facets(&fx.id, area, *rule, bounds, &p)).collect()
|
||||
};
|
||||
let mut solids = vec![];
|
||||
for ((item, opacity, _, _), f) in parts.iter().zip(built) {
|
||||
for ((item, opacity, _, _, scopes), f) in parts.iter().zip(built) {
|
||||
let item: &AppearanceItem = item;
|
||||
match f {
|
||||
Ok(f) => solids.push((item, *opacity, f)),
|
||||
Ok(f) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => return None,
|
||||
Ok(f) => solids.push((item, *opacity, *scopes, f)),
|
||||
// A stroke's outline past the limits is left out; the fill's solid still draws.
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
// A loaded file or a shape edited past the limits keeps drawing its source path
|
||||
@@ -527,30 +602,33 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
|
||||
if solids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let opaque = solids.iter().all(|(item, member, _)| {
|
||||
let opaque = solids.iter().all(|(item, member, _, _)| {
|
||||
let (_, opacity, blend) = paint_of(item, *member);
|
||||
opacity >= 1.0 && blend == BlendMode::Normal
|
||||
});
|
||||
let surfaces: Vec<(Vec<f64>, Node)> = solids
|
||||
let surfaces: Vec<(Vec<f64>, Node, &[Scope])> = solids
|
||||
.into_iter()
|
||||
.map(|(item, member, f)| {
|
||||
.map(|(item, member, scopes, f)| {
|
||||
let depths: Vec<f64> = f.iter().map(|f| f.depth).collect();
|
||||
let (paint, opacity, blend) = paint_of(item, member);
|
||||
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
|
||||
(depths, art)
|
||||
(depths, art, scopes)
|
||||
})
|
||||
.collect();
|
||||
if masks {
|
||||
return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect()));
|
||||
}
|
||||
// One order takes a plain group of faces from each solid, one face for each facet. With
|
||||
// colored lights a surface can instead be one clipped composite of all its facets, or carry an
|
||||
// opacity mask, and then it stays whole.
|
||||
let plain = surfaces.iter().all(|(depths, s)| {
|
||||
let plain = surfaces.iter().all(|(depths, s, _)| {
|
||||
s.extras().mask.is_none() && matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())
|
||||
});
|
||||
if !opaque || !plain {
|
||||
return Some(surfaces.into_iter().map(|(_, s)| Arc::new(s)).collect());
|
||||
return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect());
|
||||
}
|
||||
let mut faces = vec![];
|
||||
for (depths, s) in surfaces {
|
||||
for (depths, s, _) in surfaces {
|
||||
if let NodeKind::Group { children, .. } = s.kind {
|
||||
faces.extend(depths.into_iter().zip(children));
|
||||
}
|
||||
@@ -702,11 +780,11 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
|
||||
// Inflate lays out every puff at once (they share one eye); each Inflate and Extrude & Bevel
|
||||
// solid and its mesh are built as the loop reaches them.
|
||||
let mut inflated = (fx.id == INFLATE).then(|| {
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _)| (area, *rule)).collect();
|
||||
vectorcraft_three_d::inflate_meshes(&shapes, bounds, inflate_options(&p), view)
|
||||
});
|
||||
let extrude = extrude_options(&p);
|
||||
for (item, member, area, rule) in &parts {
|
||||
for (item, member, area, rule, _) in &parts {
|
||||
let item: &AppearanceItem = item;
|
||||
let mesh = match inflated.as_mut() {
|
||||
Some(built) => built.next().unwrap_or_else(|| Ok(Mesh::default())),
|
||||
|
||||
@@ -350,25 +350,22 @@ fn clip_area(first: &Node) -> (PathData, FillRule) {
|
||||
}
|
||||
|
||||
/// `pieces`, each with the [`Scope`]s of the groups it was in, back in groups of `n`'s id with
|
||||
/// those groups' opacity and blending mode: consecutive pieces sharing the scope at `level` go into
|
||||
/// one group, so its transparency applies to them together. `level` stays below the nesting the
|
||||
/// pieces came from ([`nested_past`]).
|
||||
/// those groups' opacity, blending mode and opacity mask: consecutive pieces sharing the scope at
|
||||
/// `level` go into one group, so its transparency applies to them together. `level` stays below the
|
||||
/// nesting the pieces came from ([`nested_past`]).
|
||||
fn nest(n: &Node, pieces: Vec<(Vec<Scope>, Node)>, level: usize) -> Vec<Arc<Node>> {
|
||||
let mut out = vec![];
|
||||
let mut run: Vec<(Vec<Scope>, Node)> = vec![];
|
||||
let mut key = None;
|
||||
let mut key: Option<Scope> = None;
|
||||
let close = |run: &mut Vec<(Vec<Scope>, Node)>, scope: Option<Scope>, out: &mut Vec<Arc<Node>>| {
|
||||
let Some(scope) = scope else { return };
|
||||
let mut g = Node::group(n.id, nest(n, std::mem::take(run), level + 1));
|
||||
g.opacity = scope.opacity;
|
||||
g.blend = scope.blend;
|
||||
out.push(Arc::new(g));
|
||||
out.push(Arc::new(scope.group(n.id, nest(n, std::mem::take(run), level + 1))));
|
||||
};
|
||||
for (scopes, piece) in pieces {
|
||||
let here = scopes.get(level).copied();
|
||||
if here.map(|s| s.key) != key.map(|s: Scope| s.key) {
|
||||
close(&mut run, key, &mut out);
|
||||
key = here;
|
||||
let here = scopes.get(level).cloned();
|
||||
if here.as_ref().map(|s| s.key) != key.as_ref().map(|s| s.key) {
|
||||
close(&mut run, key.take(), &mut out);
|
||||
key = here.clone();
|
||||
}
|
||||
match here {
|
||||
Some(_) => run.push((scopes, piece)),
|
||||
@@ -437,12 +434,15 @@ fn shape(n: &Node, path: PathData, rule: FillRule, items: Vec<AppearanceItem>) -
|
||||
piece
|
||||
}
|
||||
|
||||
/// A plain group of `children` with `n`'s id, visibility, opacity and blending mode.
|
||||
/// A plain group of `children` with `n`'s id, visibility, opacity, blending mode and opacity mask.
|
||||
fn wrap(n: &Node, children: Vec<Arc<Node>>) -> Node {
|
||||
let mut g = Node::group(n.id, children);
|
||||
g.name = n.name.clone();
|
||||
g.opacity = n.opacity;
|
||||
g.blend = n.blend;
|
||||
if let Some(mask) = &n.extras().mask {
|
||||
g.extras_mut().mask = Some(mask.clone());
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
|
||||
@@ -462,6 +462,67 @@ fn empty_sources_and_sources_inside_sources_build_or_refuse_cleanly() {
|
||||
assert!(close(bounds(&solid_art_in(Some(&d), &placed).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01));
|
||||
}
|
||||
|
||||
/// The id of the art of [`masked_by`]'s opacity masks.
|
||||
const MASK_ART: NodeId = NodeId(900);
|
||||
|
||||
/// `n` with an opacity mask of white art covering `r`.
|
||||
fn masked_by(mut n: Node, r: Rect) -> Node {
|
||||
let art = Node::path(MASK_ART, shapes::rectangle(r), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0));
|
||||
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
|
||||
n
|
||||
}
|
||||
|
||||
/// The faces (paths) of `art`, and how many of them are inside an object [`masked_by`] masks with
|
||||
/// a mask that is not disabled.
|
||||
fn masked_faces(art: &Node) -> (usize, usize) {
|
||||
fn walk(n: &Node, masked: bool, out: &mut (usize, usize)) {
|
||||
let masked = masked || n.extras().mask.as_ref().is_some_and(|m| m.art.id == MASK_ART && !m.disabled);
|
||||
match n.children() {
|
||||
Some(children) => children.iter().for_each(|c| walk(c, masked, out)),
|
||||
None => {
|
||||
out.0 += 1;
|
||||
out.1 += usize::from(masked);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = (0, 0);
|
||||
walk(art, false, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opacity_mask_on_a_member_or_a_group_in_a_three_d_group_masks_its_solids() {
|
||||
let d = document();
|
||||
let mask = Rect::new(0.0, 0.0, 400.0, 400.0);
|
||||
let mut members = vec![("a path", rect(1, 100.0, 100.0, 150.0, 200.0, 2.0))];
|
||||
members.extend(sources());
|
||||
for (what, member) in members {
|
||||
let other = || Arc::new(rect(91, 600.0, 600.0, 650.0, 650.0, 0.0));
|
||||
let in_group = Node::group(NodeId(80), vec![Arc::new(member.clone())]);
|
||||
let cases = [
|
||||
("masked", Node::group(NodeId(90), vec![Arc::new(masked_by(member.clone(), mask)), other()])),
|
||||
("in a masked group", Node::group(NodeId(90), vec![Arc::new(masked_by(in_group, mask)), other()])),
|
||||
];
|
||||
for (how, g) in cases {
|
||||
for id in TYPES {
|
||||
let g = with(g.clone(), id, json!({}));
|
||||
let (faces, masked) = masked_faces(&art(&d, &g, id).expect("drawn"));
|
||||
assert!(masked > 0, "{id}: the faces of {what} {how} are masked");
|
||||
assert!(masked < faces, "{id}: the other member's faces are not ({masked} of {faces})");
|
||||
}
|
||||
}
|
||||
// A disabled mask masks nothing.
|
||||
let mut off = masked_by(member.clone(), mask);
|
||||
if let Some(m) = off.extras_mut().mask.as_mut() {
|
||||
m.disabled = true;
|
||||
}
|
||||
for id in TYPES {
|
||||
let g = with(Node::group(NodeId(90), vec![Arc::new(off.clone()), other()]), id, json!({}));
|
||||
assert_eq!(masked_faces(&art(&d, &g, id).expect("drawn")).1, 0, "{id}: {what} with a disabled mask");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolved_objects_and_groups_in_a_three_d_group_keep_their_geometry_effects() {
|
||||
let mut d = document();
|
||||
|
||||
@@ -14,6 +14,10 @@ use super::{ARCLEN_ACCURACY, kink, push_seg, segments, subpaths, tangent};
|
||||
|
||||
/// More dashes than this (a tiny pattern on a long path) draws the line solid instead.
|
||||
const MAX_DASHES: f64 = 200_000.0;
|
||||
/// Pattern entries walked in all (every subpath and every corner restart starts the pattern over, and
|
||||
/// zero-length entries cost no path length, so a long pattern is walked in full even on a short
|
||||
/// run); past this the line is drawn solid. About 100x what real art needs.
|
||||
const MAX_STEPS: f64 = 20_000_000.0;
|
||||
/// A pattern whose longest entry is shorter than this can't advance along the path (each entry
|
||||
/// ends within the generator's tolerance of where it starts), so it draws the line solid.
|
||||
const MIN_ENTRY: f64 = 1e-6;
|
||||
@@ -80,6 +84,10 @@ pub fn dash_kept(bp: &BezPath, d: &Dash, keep: &dyn Fn(&PathSeg) -> bool) -> Opt
|
||||
if plans.iter().map(|p| p.periods).sum::<f64>() * pat.len() as f64 > MAX_DASHES {
|
||||
return None;
|
||||
}
|
||||
let restarts = |p: &Plan| p.restart.iter().filter(|r| **r).count() as f64;
|
||||
if plans.iter().map(|p| (p.periods.ceil().max(1.0) + restarts(p)) * pat.len() as f64).sum::<f64>() > MAX_STEPS {
|
||||
return None;
|
||||
}
|
||||
// Where an exact pattern starts: `offset` into it.
|
||||
let mut off = d.offset.rem_euclid(period);
|
||||
let mut ix0 = 0;
|
||||
@@ -89,8 +97,13 @@ pub fn dash_kept(bp: &BezPath, d: &Dash, keep: &dyn Fn(&PathSeg) -> bool) -> Opt
|
||||
}
|
||||
let phase = Phase { ix: ix0, rem: pat[ix0] - off, on: ix0 % 2 == 0 };
|
||||
let mut out = Dashed::default();
|
||||
// The estimates above trust the fitted scales; this counts the pattern entries actually walked,
|
||||
// so entries that fit down to nothing can't keep a subpath looping.
|
||||
let mut budget = MAX_STEPS as usize;
|
||||
for plan in &plans {
|
||||
dash_subpath(&mut out, plan, &pat, phase, keep);
|
||||
if !dash_subpath(&mut out, plan, &pat, phase, keep, &mut budget) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
@@ -183,7 +196,8 @@ impl Piece {
|
||||
}
|
||||
}
|
||||
|
||||
fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep: &dyn Fn(&PathSeg) -> bool) {
|
||||
/// Dash one subpath; `false` when `budget` (pattern entries left to walk, shared by all subpaths) runs out.
|
||||
fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep: &dyn Fn(&PathSeg) -> bool, budget: &mut usize) -> bool {
|
||||
let first_dot = out.dots.len();
|
||||
let total: f64 = plan.lens.iter().sum();
|
||||
// Fraction of the subpath's length at `x` along the plan.
|
||||
@@ -244,6 +258,8 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep:
|
||||
push_dot(out, first_dot, Dot { at: seg.eval(t), dir: tangent(seg, t), t: frac(acc + end) });
|
||||
}
|
||||
}
|
||||
let Some(rest) = budget.checked_sub(1) else { return false };
|
||||
*budget = rest;
|
||||
cuts += 1;
|
||||
s = end;
|
||||
ph.ix = (ph.ix + 1) % pat.len();
|
||||
@@ -273,7 +289,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep:
|
||||
write(&mut out.path, &d.segs);
|
||||
out.path.close_path();
|
||||
out.spans.push((frac(0.0), frac(0.0) + 1.0));
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
if starts_on && ends_on && dashes.len() > 1 {
|
||||
// The dash running through the start point is one dash.
|
||||
@@ -291,6 +307,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep:
|
||||
let t0 = frac(d.start);
|
||||
out.spans.push((t0, if total > 0.0 { t0 + (d.end - d.start) / total } else { t0 }));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Add `dot` unless the subpath's last dot (from index `first`) is already there: a run ending on
|
||||
|
||||
@@ -222,3 +222,17 @@ fn smooth_points_of_curves_stay_smooth_with_any_join() {
|
||||
assert!((a - want).abs() / want < 0.005, "{join:?}: {a} vs {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_pattern_restarted_on_many_short_subpaths_draws_solid() {
|
||||
// Each subpath walks the zero-length entries in full although it is far shorter than a period.
|
||||
let mut pattern = vec![0.0; 2000];
|
||||
pattern[0] = 1.0;
|
||||
let mut b = BezPath::new();
|
||||
for i in 0..20_000 {
|
||||
b.move_to((i as f64 * 2.0, 0.0));
|
||||
b.line_to((i as f64 * 2.0 + 0.01, 0.0));
|
||||
}
|
||||
let d = Dash { pattern, offset: 0.0, align_corners: false };
|
||||
assert!(dash(&b, &d).is_none());
|
||||
}
|
||||
@@ -1101,8 +1101,9 @@ pub fn with_id(xml: &str, id: &str) -> Option<String> {
|
||||
let f = filter_element(&doc).ok()?;
|
||||
let at = f.attributes().find(|a| a.name() == "id" && a.namespace().is_none())?.range_value();
|
||||
let (start, end) = (at.start.checked_sub(head)?, at.end.checked_sub(head)?);
|
||||
// The value may sit in single quotes: those are escaped too.
|
||||
let id = escaped(id).replace('\'', "'");
|
||||
// The value may sit in single quotes: those are escaped too. A tab, line feed or carriage
|
||||
// return is written as a character reference, which attribute-value normalization keeps.
|
||||
let id = escaped(id).replace('\'', "'").replace('\t', "	").replace('\n', " ").replace('\r', " ");
|
||||
Some(format!("{}{}{}", xml.get(..start)?, id, xml.get(end..)?))
|
||||
}
|
||||
|
||||
|
||||
@@ -218,34 +218,66 @@ fn visible(sources: &[TrapSource]) -> Vec<PathData> {
|
||||
/// The pairs `(i, j)`, `i < j`, in ascending order, of `rects` (`None`: left out) that come within
|
||||
/// `reach_x` of each other across x and `reach_y` across y. A sweep over the rects sorted by their
|
||||
/// left edge, so shapes spread over the page cost about one check each rather than one per pair.
|
||||
fn near_pairs(rects: &[Option<Rect>], reach_x: f64, reach_y: f64) -> Vec<(usize, usize)> {
|
||||
/// `None` when there are more than [`MAX_NEAR_PAIRS`] (many shapes all within reach of each other
|
||||
/// make the pair list grow with the square of their count) or the sweep examines more than
|
||||
/// `MAX_NEAR_SCAN` pairs (many shapes sharing an x range, far apart in y).
|
||||
fn near_pairs(rects: &[Option<Rect>], reach_x: f64, reach_y: f64) -> Option<Vec<(usize, usize)>> {
|
||||
near_pairs_within(rects, reach_x, reach_y, MAX_NEAR_SCAN)
|
||||
}
|
||||
|
||||
fn near_pairs_within(rects: &[Option<Rect>], reach_x: f64, reach_y: f64, max_scan: usize) -> Option<Vec<(usize, usize)>> {
|
||||
let mut order: Vec<(usize, Rect)> = rects.iter().enumerate().filter_map(|(i, r)| r.map(|r| (i, r))).collect();
|
||||
order.sort_unstable_by(|a, b| a.1.x0.total_cmp(&b.1.x0).then(a.0.cmp(&b.0)));
|
||||
let mut pairs = vec![];
|
||||
let mut scanned = 0usize;
|
||||
for (k, &(i, a)) in order.iter().enumerate() {
|
||||
// Later rects start at or right of `a`, so only how far right they start can rule them out.
|
||||
for &(j, b) in order[k + 1..].iter().take_while(|(_, b)| b.x0 <= a.x1 + reach_x) {
|
||||
// Rects sharing an x range but far apart in y are examined without being stored.
|
||||
scanned += 1;
|
||||
if scanned > max_scan {
|
||||
return None;
|
||||
}
|
||||
if b.y0 <= a.y1 + reach_y && a.y0 <= b.y1 + reach_y {
|
||||
if pairs.len() >= MAX_NEAR_PAIRS {
|
||||
return None;
|
||||
}
|
||||
pairs.push((i.min(j), i.max(j)));
|
||||
}
|
||||
}
|
||||
}
|
||||
pairs.sort_unstable();
|
||||
pairs
|
||||
Some(pairs)
|
||||
}
|
||||
|
||||
/// Most pairs the sweep in `near_pairs` examines, stored or not (a plain bounds check each).
|
||||
const MAX_NEAR_SCAN: usize = 1 << 27;
|
||||
|
||||
/// Most candidate pairs one trap evaluation keeps; past it no traps are made (the art draws as is).
|
||||
/// Each pair costs a boolean trap band, so real art stays far below this.
|
||||
pub const MAX_NEAR_PAIRS: usize = 1 << 20;
|
||||
|
||||
/// The traps between `sources` (back to front) with options `o`: for each two sources of
|
||||
/// different solid colours whose visible parts meet, the strip of the darker one's visible part
|
||||
/// next to the lighter one's (the other way round with [`TrapOptions::reverse`]), painted per
|
||||
/// [`trap_paint`]. Empty when no visible edges of different colours meet.
|
||||
/// [`trap_paint`]. Empty when no visible edges of different colours meet, or when there are more
|
||||
/// than [`MAX_NEAR_PAIRS`] candidate pairs or the pair scan is too long (see [`try_traps`] to tell
|
||||
/// those apart).
|
||||
pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec<TrapPiece> {
|
||||
try_traps(sources, o).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`traps`], but `None` when there are more than [`MAX_NEAR_PAIRS`] candidate pairs or the scan for
|
||||
/// them is too long (`MAX_NEAR_SCAN` pairs examined), as opposed to
|
||||
/// `Some` of an empty list when no edges meet.
|
||||
pub fn try_traps(sources: &[TrapSource], o: &TrapOptions) -> Option<Vec<TrapPiece>> {
|
||||
let colors: Vec<Option<Color>> = sources.iter().map(|s| trap_color(&s.fill)).collect();
|
||||
if colors.iter().flatten().count() < 2 {
|
||||
return vec![];
|
||||
return Some(vec![]);
|
||||
}
|
||||
let (w, r) = (o.thickness, o.height_width);
|
||||
if !(w.is_finite() && w > 0.0 && r.is_finite() && r > 0.0) {
|
||||
return vec![]; // `trap_band` cuts nothing with these.
|
||||
return Some(vec![]); // `trap_band` cuts nothing with these.
|
||||
}
|
||||
let vis = visible(sources);
|
||||
// Only pairs whose visible parts come within the trap's reach can trap (`trap_band` rejects
|
||||
@@ -257,7 +289,8 @@ pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec<TrapPiece> {
|
||||
let extent = rects.iter().flatten().flat_map(|b| [b.x0, b.y0, b.x1, b.y1]).fold(0.0_f64, |m, v| m.max(v.abs()));
|
||||
let hair = 1e-9 * (1.0 + extent + w * r.max(1.0));
|
||||
let mut out = vec![];
|
||||
for (i, j) in near_pairs(&rects, w + hair, w * r + hair) {
|
||||
let pairs = near_pairs(&rects, w + hair, w * r + hair)?;
|
||||
for (i, j) in pairs {
|
||||
let (Some(ci), Some(cj)) = (colors[i], colors[j]) else { continue };
|
||||
if vis[i].is_empty() || vis[j].is_empty() || same_color(&sources[i].fill, &sources[j].fill, ci, cj) {
|
||||
continue;
|
||||
@@ -276,7 +309,7 @@ pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec<TrapPiece> {
|
||||
let Some(color) = colors[from] else { continue };
|
||||
out.push(TrapPiece { path: band, paint: trap_paint(&sources[from].fill, color, o), from, into });
|
||||
}
|
||||
out
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A trap's appearance: one overprinting fill of `paint`, no stroke.
|
||||
@@ -379,10 +412,19 @@ mod tests {
|
||||
assert!(near(po::area(&t[0].path, FillRule::NonZero), 22.0 * 22.0 - 400.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pair_scan_is_bounded_even_when_no_pair_is_near() {
|
||||
// Eleven rects share an x range but lie far apart in y: 55 pairs are examined, none stored.
|
||||
let rects: Vec<Option<Rect>> = (0..11).map(|k| Some(Rect::new(0.0, k as f64 * 1000.0, 10.0, k as f64 * 1000.0 + 10.0))).collect();
|
||||
assert_eq!(near_pairs_within(&rects, 1.0, 1.0, 100), Some(vec![]));
|
||||
assert_eq!(near_pairs_within(&rects, 1.0, 1.0, 54), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_trap_without_adjoining_edges_of_different_colours() {
|
||||
let apart = vec![src(Rect::new(0.0, 0.0, 10.0, 10.0), yellow()), src(Rect::new(30.0, 0.0, 40.0, 10.0), blue())];
|
||||
assert!(traps(&apart, &TrapOptions::default()).is_empty());
|
||||
assert_eq!(try_traps(&apart, &TrapOptions::default()).map(|t| t.len()), Some(0), "no edges meet: empty, not over the cap");
|
||||
let same = vec![src(Rect::new(0.0, 0.0, 10.0, 10.0), blue()), src(Rect::new(10.0, 0.0, 20.0, 10.0), blue())];
|
||||
assert!(traps(&same, &TrapOptions::default()).is_empty());
|
||||
let mut unfilled = abutting();
|
||||
@@ -431,10 +473,13 @@ mod tests {
|
||||
fn only_shapes_within_reach_are_paired() {
|
||||
let s = many_apart_and_one_abutting();
|
||||
let rects: Vec<Option<Rect>> = s.iter().map(|t| t.path.bounds()).collect();
|
||||
assert_eq!(near_pairs(&rects, 1.0, 1.0), vec![(0, 2000)], "the squares 10 pt apart are never paired");
|
||||
assert_eq!(near_pairs(&rects, 1.0, 1.0), Some(vec![(0, 2000)]), "the squares 10 pt apart are never paired");
|
||||
// Reaching 10 pt, neighbours in a row pair, in ascending order; left-out rects never do.
|
||||
let row: Vec<Option<Rect>> = [3, 1, 0, 2].iter().map(|&k| s[k].path.bounds()).chain([None]).collect();
|
||||
assert_eq!(near_pairs(&row, 10.0, 10.0), vec![(0, 3), (1, 2), (1, 3)]);
|
||||
assert_eq!(near_pairs(&row, 10.0, 10.0), Some(vec![(0, 3), (1, 2), (1, 3)]));
|
||||
// Past the allowance the pair list stops growing instead of being built.
|
||||
let packed = vec![Some(Rect::new(0.0, 0.0, 1.0, 1.0)); 1500];
|
||||
assert_eq!(near_pairs(&packed, 1.0, 1.0), None);
|
||||
let t = traps(&s, &TrapOptions { thickness: 1.0, ..Default::default() });
|
||||
assert_eq!(t.len(), 1, "only the abutting pair traps");
|
||||
assert_eq!((t[0].from, t[0].into), (2000, 0));
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -774,8 +774,9 @@ fn divide_dashes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
let only = (segs.len() < sp.segment_count()).then_some(&segs);
|
||||
let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made))
|
||||
.ok_or_else(|| bad(C, "that makes too many pieces (at most 100000): make the dashes longer"))?;
|
||||
let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made)).ok_or_else(|| {
|
||||
bad(C, "that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer")
|
||||
})?;
|
||||
made += out.len();
|
||||
for (piece, kind) in out.into_iter().filter(|(_, k)| !(remove_gaps && *k == pt::Piece::Gap)) {
|
||||
dashes += usize::from(kind == pt::Piece::Dash);
|
||||
@@ -825,7 +826,7 @@ fn dashed_paths(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
|
||||
fn expand_dashes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.pathtools.expandDashes";
|
||||
let too_many = || bad(C, "that makes too many pieces (at most 100000): make the dashes longer");
|
||||
let too_many = || bad(C, "that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer");
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Each dashed path and its dashes, as the canvas draws them.
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -496,7 +496,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// nothing to apply is no edit, and a click that only applies brushes the document has is
|
||||
// named for that.
|
||||
let mut probe = (*st.doc).clone();
|
||||
let imported = clip.import_into(&mut probe, &choices, false);
|
||||
let imported = clip.import_into(&mut probe, &choices, false)?;
|
||||
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
|
||||
let paths = if apply { brush_targets(&st.doc, &roots(s, p)?) } else { vec![] };
|
||||
let paint = stroke_paint(s);
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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) }))
|
||||
}
|
||||
|
||||
@@ -21,14 +21,14 @@ 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};
|
||||
|
||||
use super::super::patterncmds::add_pattern;
|
||||
use super::super::{Result, bad, unique_name};
|
||||
use super::super::{EngineError, Result, bad, unique_name};
|
||||
use super::Clipboard;
|
||||
|
||||
/// A resource kind objects refer to (graphic styles by id, the others by name).
|
||||
@@ -140,6 +140,48 @@ 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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The names the SVG filter effects of appearance `a` give (its own and its fills' and strokes').
|
||||
fn appearance_filter_names(a: &Appearance, out: &mut BTreeSet<String>) {
|
||||
let items = a.items.iter().flat_map(|i| i.effects().iter());
|
||||
let named = a.effects.iter().chain(items).filter(|e| e.id == Appearance::SVG_FILTER);
|
||||
out.extend(named.filter_map(|e| e.params.get("name").and_then(Value::as_str)).map(str::to_string));
|
||||
}
|
||||
|
||||
/// The names the SVG filter effects in the subtree of `n` give (opacity-mask art included).
|
||||
fn node_filter_names(n: &Node, out: &mut BTreeSet<String>) {
|
||||
n.walk(&mut |m| {
|
||||
appearance_filter_names(&m.appearance, out);
|
||||
if let Some(mask) = &m.extras().mask {
|
||||
node_filter_names(&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 +569,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 +611,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
|
||||
@@ -1001,8 +1055,9 @@ impl Clipboard {
|
||||
}
|
||||
|
||||
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
|
||||
/// pasted copies relink to them.
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Imported {
|
||||
/// pasted copies relink to them. An error, with `d` unchanged, when a pasted SVG filter finds no
|
||||
/// free name ([`Self::filter_links`]).
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
|
||||
self.import_used(d, &self.used(), choices, same_doc, false)
|
||||
}
|
||||
|
||||
@@ -1011,8 +1066,9 @@ impl Clipboard {
|
||||
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
|
||||
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
|
||||
/// 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 {
|
||||
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Result<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,8 +1226,83 @@ 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
|
||||
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());
|
||||
Ok(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
|
||||
/// name no filter or effect of the document gives, 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. An error when no free name fits.
|
||||
fn filter_links(&self, d: &Document, same_doc: bool) -> Result<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 effects_read = false;
|
||||
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 {
|
||||
// The names the document's effects give are taken too, those whose filter was
|
||||
// deleted included: defining a filter of that name later changes every effect that
|
||||
// names it. They are read at the first rename only.
|
||||
if !effects_read {
|
||||
effects_read = true;
|
||||
for root in d.art_roots() {
|
||||
node_filter_names(root, &mut taken);
|
||||
}
|
||||
for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) {
|
||||
node_filter_names(a, &mut taken);
|
||||
}
|
||||
for g in &d.graphic_styles {
|
||||
appearance_filter_names(&g.appearance, &mut taken);
|
||||
}
|
||||
}
|
||||
// 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_and(|id| id == new))?;
|
||||
Some((new, drawn))
|
||||
});
|
||||
let Some((new, drawn)) = renamed else {
|
||||
return Err(EngineError::Other(format!(
|
||||
"the pasted SVG filter {name:?} draws differently from the document's filter of that name, and no free name fits it"
|
||||
)));
|
||||
};
|
||||
taken.insert(new.clone());
|
||||
(new, drawn)
|
||||
};
|
||||
links.insert((name, xml), to);
|
||||
}
|
||||
Ok(links)
|
||||
}
|
||||
|
||||
/// Image blobs: a different blob under a key the document uses gets a new key.
|
||||
@@ -1286,13 +1417,13 @@ pub(crate) struct LoadedStyle {
|
||||
/// a pattern added under a free name and a pattern follows a style renamed on the way in. A style
|
||||
/// `d` has under its name, or a numbered copy of it ("Body 2"), that is the same once relinked is
|
||||
/// used; any other is added under a free name. → each style of `src` placed, in order, character
|
||||
/// styles first.
|
||||
pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Vec<LoadedStyle> {
|
||||
/// styles first. An error, as [`Clipboard::import_into`] gives.
|
||||
pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Result<Vec<LoadedStyle>> {
|
||||
let library = OnceCell::new();
|
||||
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true);
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true)?;
|
||||
let mut placed: Vec<LoadedStyle> = vec![];
|
||||
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
|
||||
for s in list {
|
||||
@@ -1302,7 +1433,7 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
|
||||
placed.push(LoadedStyle { para, name, added });
|
||||
}
|
||||
}
|
||||
placed
|
||||
Ok(placed)
|
||||
}
|
||||
|
||||
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -3,7 +3,9 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::dimension::{ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, TextAlignment, TextPosition};
|
||||
use vectorcraft_doc::dimension::{
|
||||
ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition,
|
||||
};
|
||||
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
|
||||
|
||||
@@ -14,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}}, offset?: pt, 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
|
||||
),
|
||||
@@ -23,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Update Dimensions",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [dimension ids] (default selection), options?: dimension options, offset?: pt} restyle or move existing dimensions → {ids}",
|
||||
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}",
|
||||
has_doc,
|
||||
update
|
||||
),
|
||||
@@ -92,11 +94,36 @@ fn recipe(s: &Session, p: &Value) -> Result<Dimension> {
|
||||
} else {
|
||||
Point::ZERO
|
||||
};
|
||||
let mut d = Dimension { mode, a, b, vertex, offset: distance(p, 30.0)?, length: a.distance(b), options: options(s, p)?, source, moved: None };
|
||||
let orientation = orientation(p, mode)?.unwrap_or_default();
|
||||
let mut d = Dimension {
|
||||
mode,
|
||||
a,
|
||||
b,
|
||||
vertex,
|
||||
offset: distance(p, 30.0)?,
|
||||
length: a.distance(b),
|
||||
options: options(s, p)?,
|
||||
source,
|
||||
orientation,
|
||||
moved: None,
|
||||
};
|
||||
if mode == DimensionMode::Linear {
|
||||
d.length = d.measured();
|
||||
}
|
||||
d.resolve(&s.doc()?.doc).map_err(error)?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// The `orientation` param, if given: only a linear dimension is horizontal or vertical.
|
||||
fn orientation(p: &Value, mode: DimensionMode) -> Result<Option<Orientation>> {
|
||||
let Some(v) = p.get("orientation") else { return Ok(None) };
|
||||
let orientation: Orientation = serde_json::from_value(v.clone()).map_err(|_| error("Unknown dimension orientation"))?;
|
||||
if orientation != Orientation::Aligned && mode != DimensionMode::Linear {
|
||||
return Err(error("Only linear dimensions are horizontal or vertical"));
|
||||
}
|
||||
Ok(Some(orientation))
|
||||
}
|
||||
|
||||
fn insert(doc: &mut Document, parent: Option<NodeId>, dim: Dimension) -> Result<NodeId> {
|
||||
let id = doc.alloc_id();
|
||||
let mut group = Node::new(id, NodeKind::Group { children: vec![], clip: false });
|
||||
@@ -134,21 +161,38 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(error("Select dimensions to update"));
|
||||
}
|
||||
let o = if p.get("options").is_some() { Some(options(s, p)?) } else { None };
|
||||
s.edit("Update Dimensions", |doc, _| {
|
||||
// Every dimension is checked before anything changes, and an update that changes none of
|
||||
// them records no undo step.
|
||||
let mut next = Vec::with_capacity(ids.len());
|
||||
{
|
||||
let doc = &s.doc()?.doc;
|
||||
for id in &ids {
|
||||
if !doc.is_editable(*id) {
|
||||
return Err(error("Dimension is locked or hidden"));
|
||||
}
|
||||
let mut dim = dimension_of(doc, *id)?;
|
||||
let old = dimension_of(doc, *id)?;
|
||||
let mut dim = old.clone();
|
||||
if let Some(o) = &o {
|
||||
dim.options = o.clone();
|
||||
}
|
||||
if let Some(orientation) = orientation(p, dim.mode)? {
|
||||
dim.set_orientation(orientation);
|
||||
}
|
||||
dim.offset = distance(p, dim.offset)?;
|
||||
dim.resolve(doc).map_err(error)?;
|
||||
replace(doc, *id, dim)?;
|
||||
if dim != old {
|
||||
next.push((*id, dim));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
if !next.is_empty() {
|
||||
s.edit("Update Dimensions", |doc, _| {
|
||||
for (id, dim) in next {
|
||||
replace(doc, id, dim)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({"ids":ids}))
|
||||
}
|
||||
|
||||
@@ -187,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(())
|
||||
@@ -227,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) {
|
||||
@@ -241,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> {
|
||||
@@ -271,17 +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;
|
||||
@@ -424,17 +618,19 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
text_at = d.vertex + dir * if away { r + gap } else { (r - gap).max(o.font_size * 0.5) };
|
||||
} else {
|
||||
let delta = d.b - d.a;
|
||||
let u = delta / delta.hypot();
|
||||
// A linear dimension measures along its direction (a → b, or the horizontal or vertical axis).
|
||||
let u = if d.mode == DimensionMode::Linear { d.direction() } else { delta / delta.hypot() };
|
||||
let n = Vec2::new(-u.y, u.x);
|
||||
let (a, b) = match d.mode {
|
||||
DimensionMode::Radius => (d.a, d.b),
|
||||
DimensionMode::Diameter => (d.a - delta, d.b),
|
||||
_ => (d.a + n * d.offset, d.b + n * d.offset),
|
||||
_ => d.line_ends(),
|
||||
};
|
||||
// The side of the line facing away from the object.
|
||||
// The side of the line facing away from the object: the side the line is on, seen from
|
||||
// the middle of the measured points.
|
||||
let outward = match d.mode {
|
||||
DimensionMode::Linear => {
|
||||
if d.offset < 0.0 {
|
||||
if (a.midpoint(b) - d.a.midpoint(d.b)).dot(n) < 0.0 {
|
||||
-n
|
||||
} else {
|
||||
n
|
||||
@@ -443,8 +639,16 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result<Vec<Arc<
|
||||
_ => n,
|
||||
};
|
||||
if d.mode == DimensionMode::Linear && !o.hide_extensions {
|
||||
// Each extension line runs from its point toward the dimension line, which can lie on
|
||||
// different sides of the two points of a horizontal or vertical dimension.
|
||||
for (p, q) in [(d.a, a), (d.b, b)] {
|
||||
paths.push((line(p + outward * o.extension_offset, q + outward * o.extension_length), appearance(o, mode, true, false)));
|
||||
let side = (q - p).dot(n);
|
||||
let toward = match side {
|
||||
s if s < 0.0 => -n,
|
||||
s if s > 0.0 => n,
|
||||
_ => outward,
|
||||
};
|
||||
paths.push((line(p + toward * o.extension_offset, q + toward * o.extension_length), appearance(o, mode, true, false)));
|
||||
}
|
||||
}
|
||||
angle = u.atan2();
|
||||
|
||||
@@ -263,6 +263,22 @@ fn record_again(s: &mut Session, again: Value) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `d` with each of `ids` that is not in perspective attached to `fallback` as [`persp_edit`] attaches
|
||||
/// it; `d` itself when every one is in perspective already, there is no `fallback`, or one of them
|
||||
/// cannot attach.
|
||||
fn with_fallback<'a>(d: &'a Document, ids: &[NodeId], fallback: Option<Plane>) -> std::borrow::Cow<'a, Document> {
|
||||
let mut g = grid_of(d);
|
||||
let loose: Vec<NodeId> = ids.iter().copied().filter(|id| g.attachment_of(d, *id).is_none()).collect();
|
||||
let Some(plane) = fallback.filter(|_| !loose.is_empty()) else { return std::borrow::Cow::Borrowed(d) };
|
||||
let mut out = d.clone();
|
||||
for id in loose {
|
||||
if attach_in(&mut out, &mut g, id, plane, false, None).is_err() {
|
||||
return std::borrow::Cow::Borrowed(d);
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(out)
|
||||
}
|
||||
|
||||
fn ids_json(ids: &[NodeId]) -> Value {
|
||||
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
|
||||
}
|
||||
@@ -285,9 +301,11 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let constrain = switch_or(p, "constrain", false, C)?;
|
||||
// `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false.
|
||||
check_switches(p, &["snap"], C)?;
|
||||
// Shift and Snap to Grid read the objects as they are once those not in perspective are attached.
|
||||
let doc = if perp { std::borrow::Cow::Borrowed(&*s.doc()?.doc) } else { with_fallback(&s.doc()?.doc, &ids, fallback) };
|
||||
// Shift: the constrained end point, read on the first object's plane and depth.
|
||||
let snap_to = if constrain && !perp {
|
||||
let doc = &s.doc()?.doc;
|
||||
let doc = &*doc;
|
||||
let g = grid_of(doc);
|
||||
g.plane_bounds(doc, &ids)
|
||||
.and_then(|(plane, depth, _)| {
|
||||
@@ -305,10 +323,10 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fix = if perp {
|
||||
None
|
||||
} else {
|
||||
let doc = &s.doc()?.doc;
|
||||
crate::cmd::perspgrid::snap_fix(doc, &ids, p, (from, snap_to))
|
||||
.and_then(|(plane, depth, correction)| Some((plane, grid_of(doc).plane_delta(plane, depth, from, to)?, correction)))
|
||||
crate::cmd::perspgrid::snap_fix(&doc, &ids, p, (from, snap_to))
|
||||
.and_then(|(plane, depth, correction)| Some((plane, grid_of(&doc).plane_delta(plane, depth, from, to)?, correction)))
|
||||
};
|
||||
drop(doc);
|
||||
let snapped = move |pl: Plane, raw: vectorcraft_geom::Vec2| {
|
||||
let raw = fix.filter(|f| f.0 == pl).map_or(raw, |f| f.1);
|
||||
let (direction, dv) =
|
||||
|
||||
@@ -1332,7 +1332,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
vec![Affine::IDENTITY]
|
||||
};
|
||||
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
|
||||
let imported = clip.import_into(d, choices, same_doc);
|
||||
let imported = clip.import_into(d, choices, same_doc)?;
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
|
||||
let artboards: Vec<usize> = boards
|
||||
|
||||
@@ -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))?;
|
||||
|
||||
@@ -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<_>>() }))
|
||||
|
||||
@@ -1018,6 +1018,65 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Source file names that differ only in case (`a.svg` and `sub/A.svg`) get Export for Screens
|
||||
/// folders of their own: names are compared without case, so the second folder is numbered,
|
||||
/// since Windows and macOS would make `a` and `A` one folder.
|
||||
#[test]
|
||||
fn batch_override_export_numbers_folders_that_differ_only_in_case() {
|
||||
let src = tmp("screens-case-src");
|
||||
std::fs::create_dir_all(src.join("sub")).unwrap();
|
||||
write_svg(&src, "a.svg", "#f00");
|
||||
write_svg(&src.join("sub"), "A.svg", "#0f0");
|
||||
let dest = tmp("screens-case-out");
|
||||
let mut s = Session::new();
|
||||
let r = s
|
||||
.execute(
|
||||
"action.batch",
|
||||
&json!({
|
||||
"folder": src.to_string_lossy(),
|
||||
"includeSubdirs": true,
|
||||
"destinationFolder": dest.to_string_lossy(),
|
||||
"commands": [{"command": "document.exportForScreens", "params": {"formats": [{"format": "svg"}]}}]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert_eq!(file_names(&dest), ["A-2", "a"], "{r}");
|
||||
for (folder, fill) in [("a", "#ff0000"), ("A-2", "#00ff00")] {
|
||||
assert_eq!(file_names(&dest.join(folder)), ["Artboard-1.svg"], "{r}");
|
||||
let svg = std::fs::read_to_string(dest.join(folder).join("Artboard-1.svg")).unwrap();
|
||||
assert!(svg.contains(fill), "{folder}: {svg}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A source file with nothing left of its name without its extension (` .svg`) gets the folder
|
||||
/// `file`, numbered before a source file named `file.svg` takes it.
|
||||
#[test]
|
||||
fn batch_override_export_names_the_folder_of_an_empty_name_file() {
|
||||
let src = tmp("screens-empty-src");
|
||||
write_svg(&src, " .svg", "#f00");
|
||||
write_svg(&src, "file.svg", "#0f0");
|
||||
let dest = tmp("screens-empty-out");
|
||||
let mut s = Session::new();
|
||||
let r = s
|
||||
.execute(
|
||||
"action.batch",
|
||||
&json!({
|
||||
"folder": src.to_string_lossy(),
|
||||
"destinationFolder": dest.to_string_lossy(),
|
||||
"commands": [{"command": "document.exportForScreens", "params": {"formats": [{"format": "svg"}]}}]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert_eq!(file_names(&dest), ["file", "file-2"], "{r}");
|
||||
for (folder, fill) in [("file", "#ff0000"), ("file-2", "#00ff00")] {
|
||||
assert_eq!(file_names(&dest.join(folder)), ["Artboard-1.svg"], "{r}");
|
||||
let svg = std::fs::read_to_string(dest.join(folder).join("Artboard-1.svg")).unwrap();
|
||||
assert!(svg.contains(fill), "{folder}: {svg}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A source file whose name without its extension ends in a period (`a..svg`) gets the folder
|
||||
/// name without it, numbered after the folder of `a.svg`: Windows drops the period from a folder
|
||||
/// name, so `a.` and `a` would be one folder there.
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -92,6 +92,9 @@ fn run_steps(
|
||||
if id == "command.batch" {
|
||||
return Err(bad("command.batch", "batches cannot nest"));
|
||||
}
|
||||
if id == "prefs.import" {
|
||||
return Err(bad("command.batch", "`prefs.import` runs on its own, not as a batch step"));
|
||||
}
|
||||
if s.active().is_some() {
|
||||
s.begin_interaction(label)?;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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:#?}");
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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 { .. } => {
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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(¶);
|
||||
*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>> {
|
||||
|
||||
@@ -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 ¶s {
|
||||
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:?}");
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -1303,7 +1303,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
|
||||
let choices = SwatchChoices::default();
|
||||
// The pattern's name in the document, worked out on a copy: nothing to add is no edit.
|
||||
let mut probe = (*s.doc()?.doc).clone();
|
||||
let imported = clip.import_into(&mut probe, &choices, false);
|
||||
let imported = clip.import_into(&mut probe, &choices, false)?;
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str());
|
||||
let target = renamed.unwrap_or(&name).to_string();
|
||||
let paint = vectorcraft_doc::pattern::pattern_paint(&target);
|
||||
@@ -1315,7 +1315,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
|
||||
in_one_step(s, |s| {
|
||||
if added {
|
||||
s.edit("Add to Swatches", |d, _| {
|
||||
clip.import_into(d, &choices, false);
|
||||
clip.import_into(d, &choices, false)?;
|
||||
if !has_swatch(d) {
|
||||
let swatch = d.free_swatch_name(&target);
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: swatch, paint: paint.clone(), global: false, spot: false });
|
||||
|
||||
@@ -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,11 @@ 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. The sides are
|
||||
// measured in the renderer's whole pixels.
|
||||
let side = vectorcraft_render::MAX_RASTER_SIDE;
|
||||
let (w, h) = vectorcraft_render::region_pixels(region, scale);
|
||||
if region.width() * region.height() * scale * scale > MAX_PIXELS || w > side || h > side {
|
||||
return Err(EngineError::Other("image would be too large; lower the resolution".into()));
|
||||
}
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
@@ -1319,6 +1323,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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(())
|
||||
})?;
|
||||
|
||||
+232
-10
@@ -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); nearby anchors follow with a smooth falloff over radius, measured along the path (default: half the subpath's size)",
|
||||
"{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,6 +1418,145 @@ fn open_run(mut anchors: Vec<vectorcraft_geom::Anchor>) -> Option<SubPath> {
|
||||
Some(SubPath::new(anchors, false))
|
||||
}
|
||||
|
||||
/// 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(len);
|
||||
let mut run = 0.0;
|
||||
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 k > 0 {
|
||||
run += a.h_in.distance(a.p);
|
||||
}
|
||||
let c = run;
|
||||
if k + 1 < len {
|
||||
run += a.p.distance(a.h_out);
|
||||
}
|
||||
pos.push([c_in, c, run]);
|
||||
before = Some(a);
|
||||
}
|
||||
// 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],
|
||||
}
|
||||
}
|
||||
};
|
||||
// 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> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.reshape", "missing id"))?;
|
||||
let at = Point::new(f64_req(p, "x", "path.reshape")?, f64_req(p, "y", "path.reshape")?);
|
||||
@@ -1417,19 +1564,94 @@ fn reshape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let delta = Vec2::new(f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0));
|
||||
let tol = f64_or(p, "tol", 3.0).max(0.0);
|
||||
let radius = p.get("radius").and_then(Value::as_f64);
|
||||
s.edit("Reshape", |d, _| {
|
||||
if radius.is_some_and(|r| r < 0.0) {
|
||||
return Err(bad("path.reshape", "`radius` must be 0 or more"));
|
||||
}
|
||||
// The anchor within `tol` of the grab point, if there is one.
|
||||
let near = |sp: &SubPath| match sp.anchors.iter().enumerate().map(|(i, a)| (i, a.p.distance(at))).min_by(|a, b| a.1.total_cmp(&b.1)) {
|
||||
Some((i, dist)) if dist <= tol => Some(i),
|
||||
_ => None,
|
||||
};
|
||||
// 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")))?;
|
||||
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, 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 grabbed = match sp.anchors.iter().enumerate().map(|(i, a)| (i, a.p.distance(at))).min_by(|a, b| a.1.total_cmp(&b.1)) {
|
||||
Some((i, dist)) if dist <= tol => i,
|
||||
_ => sp.insert_anchor(seg, t),
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("empty path".into()))?;
|
||||
let grabbed = match near(sp) {
|
||||
Some(i) => i,
|
||||
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 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);
|
||||
@@ -1437,7 +1659,6 @@ fn reshape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(b.width().hypot(b.height()) / 2.0).max(1.0)
|
||||
});
|
||||
let from = pos.get(grabbed).copied().unwrap_or(0.0);
|
||||
let closed = sp.closed;
|
||||
for (i, a) in sp.anchors.iter_mut().enumerate() {
|
||||
let w = if i == grabbed {
|
||||
1.0
|
||||
@@ -1470,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) {
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -221,25 +221,41 @@ pub(crate) fn len_param(p: &Value, key: &str) -> Option<f64> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The number `p` gives `cmd` for `key`, as [`num_param`] reads it, or `None` when `p` leaves it out
|
||||
/// or gives null. Any other value, such as `true` or `"wide"`, is an error: "`{key}` must be a
|
||||
/// number, not {v}".
|
||||
/// The number `p` gives `cmd` for `key`, or `None` when `p` leaves it out or gives null. A string
|
||||
/// counts only when all of it is a number (`"20"`). Any other value, such as `true`, `"wide"` or
|
||||
/// `"20abc"`, is an error: "`{key}` must be a number, not {v}".
|
||||
pub(crate) fn number_given(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => num_param(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
Some(v) => match v {
|
||||
Value::String(s) => whole_number(s),
|
||||
_ => num_param(p, key),
|
||||
}
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The distance `p` gives `cmd` for `key`, as [`len_param`] reads it (`"5 mm"` included), or `None`
|
||||
/// when `p` leaves it out or gives null. Any other value is an error, as [`number_given`] gives it.
|
||||
/// The distance `p` gives `cmd` for `key`, or `None` when `p` leaves it out or gives null. A string
|
||||
/// counts only when all of it is a length that [`vectorcraft_doc::Unit::parse`] reads (`"5 mm"`) or a
|
||||
/// number. Any other value, such as `"20abc"`, is an error, as [`number_given`] gives it.
|
||||
pub(crate) fn length_given(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => len_param(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
Some(v) => match v {
|
||||
Value::String(s) => vectorcraft_doc::Unit::Points.parse(s).filter(|v| v.is_finite()).or_else(|| whole_number(s)),
|
||||
_ => num_param(p, key),
|
||||
}
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` as a finite number when all of it, spaces around it aside, is one.
|
||||
fn whole_number(s: &str) -> Option<f64> {
|
||||
s.trim().parse::<f64>().ok().filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
fn ids_json(ids: &[NodeId]) -> Value {
|
||||
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
|
||||
}
|
||||
@@ -703,7 +719,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
/// Pathfinder panel › Trap ([`vectorcraft_render::effects::trap`]): the traps between the selected
|
||||
/// objects' leaf shapes, as one group of overprinting paths above the topmost selected object.
|
||||
fn trap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_render::effects::trap::{TRAP_LABEL, TrapOptions, TrapSource, trap_appearance, traps};
|
||||
use vectorcraft_render::effects::trap::{TRAP_LABEL, TrapOptions, TrapSource, trap_appearance, try_traps};
|
||||
const ID: &str = "object.pathfinder.trap";
|
||||
let mut q = p.clone();
|
||||
if let Some(t) = length_given(p, "thickness", ID)? {
|
||||
@@ -742,7 +758,12 @@ fn trap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if sources.iter().filter(|s| s.fill.color().is_some()).count() < 2 {
|
||||
return Err(EngineError::Other("Trap: select two or more objects filled with solid colours".into()));
|
||||
}
|
||||
let made = traps(&sources, &options);
|
||||
let Some(made) = try_traps(&sources, &options) else {
|
||||
return Err(EngineError::Other(format!(
|
||||
"Trap: more than {} pairs of objects lie close enough to trap, or too many objects share a horizontal range; trap fewer objects at a time",
|
||||
vectorcraft_render::effects::trap::MAX_NEAR_PAIRS
|
||||
)));
|
||||
};
|
||||
if made.is_empty() {
|
||||
return Err(EngineError::Other("Trap: no edges of different colours meet among the selected objects".into()));
|
||||
}
|
||||
@@ -1058,7 +1079,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;
|
||||
@@ -1067,10 +1092,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());
|
||||
|
||||
@@ -10,6 +10,7 @@ use vectorcraft_doc::pattern::pattern_paint;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, PatternDef, TileType};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::Result;
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::swatchlib::LibraryInfo;
|
||||
@@ -84,11 +85,11 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
|
||||
/// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art
|
||||
/// painted with it does: the same pattern there already is used, and a name another pattern or
|
||||
/// swatch has gets a number → the pattern's name in `d`.
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> String {
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<String> {
|
||||
let user = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(pattern_paint(name), Paint::None, 0.0));
|
||||
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false);
|
||||
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false)?;
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str());
|
||||
renamed.unwrap_or(name).to_string()
|
||||
Ok(renamed.unwrap_or(name).to_string())
|
||||
}
|
||||
|
||||
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
|
||||
|
||||
@@ -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,11 +1,12 @@
|
||||
//! Preferences (Edit → Preferences): `prefs.get`, `prefs.set`, `prefs.reset`, `prefs.list`.
|
||||
//! Preferences (Edit → Preferences): `prefs.get`, `prefs.set`, `prefs.reset`, `prefs.list`,
|
||||
//! `prefs.export`, `prefs.import`.
|
||||
//!
|
||||
//! [`PREF_SPECS`] is the single source of truth for every preference: its category, section,
|
||||
//! label and value kind. The Preferences dialog renders from it and `prefs.set` validates with it.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, str_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, str_param, switch_or, text_param};
|
||||
use crate::Prefs;
|
||||
use crate::units::Measure;
|
||||
use vectorcraft_doc::{GridPrefs, Unit};
|
||||
@@ -229,6 +230,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("guideColor", "Guides & Grid", "Guides", "Color", color),
|
||||
p!("guideStyle", "Guides & Grid", "Guides", "Style", choice(LINE_STYLE)),
|
||||
p!("lockGuidesByDefault", "Guides & Grid", "Guides", "Lock Guides by Default", bool),
|
||||
p!("cmdRulerDragArtboardGuides", "Guides & Grid", "Guides", "Artboard Guides with Cmd/Ctrl + Ruler Drag", bool),
|
||||
p!("gridColor", "Guides & Grid", "Grid", "Color", color),
|
||||
p!("gridStyle", "Guides & Grid", "Grid", "Style", choice(LINE_STYLE)),
|
||||
p!("gridlineEvery", "Guides & Grid", "Grid", "Gridline every", len(1.0, 16383.0, General)),
|
||||
@@ -457,6 +459,9 @@ pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinde
|
||||
|
||||
/// Validate a value for preference group `key` against `current`.
|
||||
fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<Value, String> {
|
||||
if !v.is_object() {
|
||||
return Err(format!("`{key}` must be an object"));
|
||||
}
|
||||
match key {
|
||||
"eyedropper" => {
|
||||
let cur: super::EyedropperOptions = serde_json::from_value(current.clone()).unwrap_or_default();
|
||||
@@ -763,15 +768,117 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Preference",
|
||||
[],
|
||||
None,
|
||||
"{key, value} or {values: {key: value, …}} set preferences (validated; see prefs.list; lengths in pt or strings with a unit; unitsGeneral also sets the active document's units, one undo step; the eyedropper group takes a partial object, as eyedropper.setOptions; a new recoveryFolder must be a folder that can be listed and written in, and a new pluginsFolder a folder that can be listed: otherwise an error, and nothing changes; an empty value is not checked)",
|
||||
"{key, value} or {values: {key: value, …}, documentUnits?: bool=true} set preferences (validated; see prefs.list; lengths in pt or strings with a unit; unitsGeneral also sets the active document's units, one undo step, unless documentUnits is false; the eyedropper group takes a partial object, as eyedropper.setOptions, and a group given anything but an object is an error; a new recoveryFolder must be a folder that can be listed and written in, and a new pluginsFolder a folder that can be listed: otherwise an error, and nothing changes; an empty value is not checked)",
|
||||
always,
|
||||
set
|
||||
),
|
||||
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
|
||||
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference", always, list),
|
||||
cmd!(
|
||||
query "prefs.export",
|
||||
"Export Preferences",
|
||||
[],
|
||||
None,
|
||||
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder and glyphSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
|
||||
always,
|
||||
export
|
||||
),
|
||||
cmd!(
|
||||
query "prefs.import",
|
||||
"Import Preferences",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: the file's text} apply the preferences of a file prefs.export wrote (at most 1 MB). Every value is checked first, as prefs.set checks it: another format, a newer version, an unknown preference, a value of the wrong type or out of range, or a folder preference is an error, and nothing changes. Preferences the file leaves out keep their values; the open document's units stay as they are; no undo step; not a command.batch step → {imported: count}",
|
||||
always,
|
||||
import
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The `format` of a preferences file (`prefs.export`, `prefs.import`).
|
||||
pub const PREFS_FORMAT: &str = "vectorcraft-preferences";
|
||||
|
||||
/// The `version` `prefs.export` writes; `prefs.import` refuses a newer one.
|
||||
pub const PREFS_VERSION: u64 = 1;
|
||||
|
||||
/// The largest preferences file `prefs.import` reads.
|
||||
const MAX_PREFS_FILE_BYTES: usize = 1 << 20;
|
||||
|
||||
/// Folder preferences, which name folders on one computer: a preferences file leaves them out.
|
||||
const FOLDER_PREFS: &[&str] = &["fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"];
|
||||
|
||||
/// The preferences `prefs.export` writes: every [`PREF_SPECS`] key but the [`FOLDER_PREFS`], and
|
||||
/// the [`PREF_GROUPS`].
|
||||
fn exported(prefs: &crate::Prefs) -> Map<String, Value> {
|
||||
let all = prefs.to_json();
|
||||
let keys = PREF_SPECS.iter().map(|s| s.key).filter(|k| !FOLDER_PREFS.contains(k)).chain(PREF_GROUPS.iter().copied());
|
||||
keys.map(|k| (k.to_string(), all[k].clone())).collect()
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "prefs.export";
|
||||
let path = text_param(p, "path", C)?;
|
||||
let prefs = exported(&s.prefs);
|
||||
let count = prefs.len();
|
||||
let file = json!({ "format": PREFS_FORMAT, "version": PREFS_VERSION, "prefs": prefs });
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
|
||||
// A file `prefs.import` would refuse is not written.
|
||||
if text.len() > MAX_PREFS_FILE_BYTES {
|
||||
return Err(bad(C, "the file is larger than 1 MB"));
|
||||
}
|
||||
match path {
|
||||
Some(path) => {
|
||||
super::fileio::write_file(path, text.as_bytes())?;
|
||||
Ok(json!({"path": path, "count": count}))
|
||||
}
|
||||
None => Ok(json!({"data": text, "count": count})),
|
||||
}
|
||||
}
|
||||
|
||||
/// The preferences in the bytes of a preferences file, unchecked: `Err` says why the file is not
|
||||
/// one this version reads.
|
||||
fn read_prefs_file(bytes: &[u8]) -> std::result::Result<Map<String, Value>, String> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| format!("not a preferences file: {e}"))?;
|
||||
let Some(file) = v.as_object() else { return Err("not a preferences file: no JSON object".into()) };
|
||||
match file.get("format").and_then(Value::as_str) {
|
||||
Some(PREFS_FORMAT) => {}
|
||||
Some(format) => return Err(format!("not a preferences file (format `{format}`)")),
|
||||
None => return Err("not a preferences file: no `format`".into()),
|
||||
}
|
||||
match file.get("version").and_then(Value::as_u64) {
|
||||
Some(v) if v > PREFS_VERSION => return Err(format!("the file was saved by a newer version of VectorCraft (version {v})")),
|
||||
Some(1..) => {}
|
||||
_ => return Err("not a preferences file: no `version`".into()),
|
||||
}
|
||||
let Some(prefs) = file.get("prefs").and_then(Value::as_object) else { return Err("not a preferences file: no `prefs`".into()) };
|
||||
if prefs.is_empty() {
|
||||
return Err("the file holds no preferences".into());
|
||||
}
|
||||
if let Some(key) = prefs.keys().find(|k| FOLDER_PREFS.contains(&k.as_str())) {
|
||||
return Err(format!("`{key}` names a folder, which preferences files leave out"));
|
||||
}
|
||||
Ok(prefs.clone())
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "prefs.import";
|
||||
let too_large = || bad(C, "the file is larger than 1 MB");
|
||||
let bytes = match (text_param(p, "path", C)?, text_param(p, "data", C)?) {
|
||||
(Some(path), None) => super::fileio::read_file_head(path, MAX_PREFS_FILE_BYTES + 1)?,
|
||||
(None, Some(text)) if text.len() > MAX_PREFS_FILE_BYTES => return Err(too_large()),
|
||||
(None, Some(text)) => text.as_bytes().to_vec(),
|
||||
_ => return Err(bad(C, "give `path` or `data`")),
|
||||
};
|
||||
if bytes.len() > MAX_PREFS_FILE_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
let values = read_prefs_file(&bytes).map_err(|e| bad(C, e))?;
|
||||
let mut next = s.prefs.clone();
|
||||
next.set_values(&values).map_err(|e| bad(C, e))?;
|
||||
s.apply_prefs(next);
|
||||
Ok(json!({ "imported": values.len() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let all = s.prefs.to_json();
|
||||
match str_param(p, "key") {
|
||||
@@ -789,6 +896,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if values.is_empty() {
|
||||
return Err(bad("prefs.set", "give {key, value} or {values}"));
|
||||
}
|
||||
let document_units = switch_or(p, "documentUnits", true, "prefs.set")?;
|
||||
let mut next = s.prefs.clone();
|
||||
next.set_values(&values).map_err(|e| bad("prefs.set", e))?;
|
||||
if let Some(e) = s.prefs.keep_folders(&mut next).into_iter().next() {
|
||||
@@ -797,7 +905,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.prefs.check_folders(&values).map_err(EngineError::Other)?;
|
||||
s.apply_prefs(next);
|
||||
// Units ▸ General is also the open document's units (as Document Setup sets them).
|
||||
if values.contains_key("unitsGeneral") && s.active().is_some() {
|
||||
if document_units && values.contains_key("unitsGeneral") && s.active().is_some() {
|
||||
s.set_document_units(s.default_units())?;
|
||||
}
|
||||
let all = s.prefs.to_json();
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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; 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}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport",
|
||||
"{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
|
||||
),
|
||||
@@ -45,6 +45,33 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
stop
|
||||
),
|
||||
cmd!(
|
||||
query "script.console",
|
||||
"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 (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
|
||||
),
|
||||
cmd!(
|
||||
query "script.console.clear",
|
||||
"Clear Script Console",
|
||||
[],
|
||||
None,
|
||||
"{} empty the Script Console and set its dropped and cut counts to zero; a running script goes on writing, and scriptReport keeps the last run's console → {cleared: lines removed}",
|
||||
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",
|
||||
@@ -104,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) {
|
||||
@@ -135,7 +161,10 @@ 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 locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language));
|
||||
let request =
|
||||
script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), source: text, args, fuel, locale, answers };
|
||||
let name = s.script_start(request)?;
|
||||
if s.script_frames {
|
||||
return Ok(json!({"running": true, "name": name}));
|
||||
}
|
||||
@@ -146,6 +175,60 @@ fn stop(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({"stopped": s.script_request_stop()}))
|
||||
}
|
||||
|
||||
fn console_lines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(s.script_console().to_json())
|
||||
}
|
||||
|
||||
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,
|
||||
|
||||
@@ -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)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -753,7 +753,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
|
||||
// The pattern comes with its swatch; a pattern the document has without one
|
||||
// gets one.
|
||||
let target = patternlib::import(d, src, pattern);
|
||||
let target = patternlib::import(d, src, pattern)?;
|
||||
let name = match patternlib::pattern_swatch(d, &target) {
|
||||
Some(name) => name,
|
||||
None => {
|
||||
|
||||
@@ -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 })
|
||||
@@ -342,7 +405,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// Where the symbols land, worked out on a copy: nothing to add and nothing to place is no edit.
|
||||
let mut probe = (*st.doc).clone();
|
||||
let imported = clip.import_into(&mut probe, &choices, false);
|
||||
let imported = clip.import_into(&mut probe, &choices, false)?;
|
||||
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
|
||||
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None };
|
||||
@@ -350,7 +413,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = json!({ "library": info.id });
|
||||
if imported.added > 0 || place {
|
||||
let placed = s.edit("Add to Symbols", |d, sel| {
|
||||
let imported = clip.import_into(d, &choices, false);
|
||||
let imported = clip.import_into(d, &choices, false)?;
|
||||
// Every symbol brought in (nested ones too) takes its Symbol Options along.
|
||||
for sym in &clip.symbols {
|
||||
let to = target(&imported.renamed, &sym.name);
|
||||
|
||||
@@ -12,7 +12,7 @@ use super::stroke::StrokeChange;
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, id_param,
|
||||
index, number_or, point_param, str_param, switch_or, targets,
|
||||
index, number_or, point_param, str_param, switch_or, targets, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -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
|
||||
),
|
||||
@@ -568,7 +568,8 @@ pub(crate) fn change_font_axes(st: &mut CharStyle, change: &AxisChange) {
|
||||
/// `features: ["dlig", "-liga", …]` → the canonical tag list (differences from the defaults).
|
||||
pub(crate) fn features_param(p: &Value, cmd: &str) -> Result<Option<Vec<String>>> {
|
||||
let Some(v) = p.get("features").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let tags: Vec<&str> = v.as_array().ok_or_else(|| bad(cmd, "features must be a list of tags"))?.iter().filter_map(Value::as_str).collect();
|
||||
let not_tags = || bad(cmd, "features must be a list of tags");
|
||||
let tags: Vec<&str> = v.as_array().ok_or_else(not_tags)?.iter().map(|t| t.as_str().ok_or_else(not_tags)).collect::<Result<_>>()?;
|
||||
if let Some(t) = tags.iter().find(|t| !vectorcraft_text::OtFeatures::known_tag(t)) {
|
||||
return Err(bad(
|
||||
cmd,
|
||||
@@ -708,8 +709,8 @@ impl CharChange {
|
||||
stroke_opts.weight = Some(w.clamp(0.0, 1000.0));
|
||||
}
|
||||
let c = Self {
|
||||
font: str_param(p, "font").map(str::to_string),
|
||||
style: str_param(p, "style").map(str::to_string),
|
||||
font: text_param(p, "font", cmd)?.map(str::to_string),
|
||||
style: text_param(p, "style", cmd)?.map(str::to_string),
|
||||
size: num("size"),
|
||||
leading: auto_or_num(p, "leading", cmd)?,
|
||||
tracking: num("tracking"),
|
||||
@@ -1086,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.
|
||||
@@ -1275,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.
|
||||
@@ -1310,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, _| {
|
||||
|
||||
@@ -976,12 +976,12 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result<Value> {
|
||||
}
|
||||
let (chars, paras) = (kinds.contains(&Kind::Char), kinds.contains(&Kind::Para));
|
||||
let mut trial = (*s.doc()?.doc).clone();
|
||||
let mut placed = import_text_styles(&src, &mut trial, chars, paras);
|
||||
let mut placed = import_text_styles(&src, &mut trial, chars, paras)?;
|
||||
// An undo step only when the document changes. The step takes the document the import made,
|
||||
// unless the edit first ends a typing session, which can change the document it starts from.
|
||||
if trial != *s.doc()?.doc {
|
||||
if super::typing_in_progress(s) {
|
||||
placed = s.edit(label, |d, _| Ok(import_text_styles(&src, d, chars, paras)))?;
|
||||
placed = s.edit(label, |d, _| import_text_styles(&src, d, chars, paras))?;
|
||||
} else {
|
||||
s.edit(label, |d, _| {
|
||||
*d = trial;
|
||||
|
||||
@@ -1105,7 +1105,7 @@ fn self_referencing_pattern_is_not_added_again() {
|
||||
let different = dst.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 30, "height": 30})).unwrap()["id"].clone();
|
||||
dst.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [different]})).unwrap();
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert!(dst.doc().unwrap().doc.pattern("Dots 2").is_some());
|
||||
assert!(
|
||||
dst.doc().unwrap().doc.pattern("Dots 2").unwrap().art[0]
|
||||
@@ -1116,7 +1116,7 @@ fn self_referencing_pattern_is_not_added_again() {
|
||||
);
|
||||
let before = dst.doc().unwrap().doc.clone();
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert!(again.iter().all(|s| !s.added));
|
||||
assert_eq!(dst.doc().unwrap().doc, before);
|
||||
}
|
||||
@@ -1148,13 +1148,13 @@ fn separate_self_referencing_patterns_are_not_added_again() {
|
||||
dst.execute("object.pattern.make", &json!({"name": format!("Dots{k}"), "edit": false, "ids": [different]})).unwrap();
|
||||
}
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
for k in 0..9 {
|
||||
assert!(dst.doc().unwrap().doc.pattern(&format!("Dots{k} 2")).is_some(), "{k}");
|
||||
}
|
||||
let before = dst.doc().unwrap().doc.clone();
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert!(again.iter().all(|s| !s.added));
|
||||
assert_eq!(dst.doc().unwrap().doc.patterns.len(), before.patterns.len());
|
||||
assert_eq!(dst.doc().unwrap().doc, before);
|
||||
@@ -1162,7 +1162,7 @@ fn separate_self_referencing_patterns_are_not_added_again() {
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
target.patterns.retain(|p| !p.name.starts_with("Dots8"));
|
||||
let left = target.patterns.len();
|
||||
let third = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
let third = super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert_eq!(dst.doc().unwrap().doc.patterns.len(), left + 1);
|
||||
assert!(third.iter().filter(|s| s.name != "Patterned8" && !s.name.starts_with("Patterned8 ")).all(|s| !s.added));
|
||||
}
|
||||
@@ -1195,13 +1195,13 @@ fn a_long_loop_of_patterns_is_not_added_again() {
|
||||
dst.execute("object.pattern.make", &json!({"name": format!("Dots{k}"), "edit": false, "ids": [different]})).unwrap();
|
||||
}
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
for k in 0..9 {
|
||||
assert!(dst.doc().unwrap().doc.pattern(&format!("Dots{k} 2")).is_some(), "{k}");
|
||||
}
|
||||
let before = dst.doc().unwrap().doc.clone();
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert!(again.iter().all(|s| !s.added));
|
||||
assert_eq!(dst.doc().unwrap().doc.patterns.len(), before.patterns.len());
|
||||
assert_eq!(dst.doc().unwrap().doc, before);
|
||||
|
||||
@@ -8,10 +8,10 @@ use vectorcraft_doc::{AreaFit, Document, Justify, Node, NodeId, NodeKind, RubyAl
|
||||
use vectorcraft_geom::{Affine, PathData, Vec2};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::{len_param, num_param, shape_node};
|
||||
use super::pathops::{length_given, number_given, shape_node};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, id_param, index, number_or, ok,
|
||||
str_param, switch_or, targets,
|
||||
str_param, switch_or, targets, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -249,16 +249,16 @@ fn ruby(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = text_targets(s, p, C)?;
|
||||
let range = TextRange::parse(p, C)?;
|
||||
let remove = switch_or(p, "remove", false, C)?;
|
||||
let reading = str_param(p, "text").map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);
|
||||
let reading = text_param(p, "text", C)?.map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);
|
||||
if !remove && reading.is_none() {
|
||||
return Err(bad(C, "give `text` (the reading) or `remove`"));
|
||||
}
|
||||
let position = match str_param(p, "position").map(str::to_ascii_lowercase).as_deref() {
|
||||
let position = match text_param(p, "position", C)?.map(str::to_ascii_lowercase).as_deref() {
|
||||
None | Some("above") | Some("right") => RubyPosition::Above,
|
||||
Some("below") | Some("left") => RubyPosition::Below,
|
||||
Some(_) => return Err(bad(C, "`position` is above or below")),
|
||||
};
|
||||
let align = match str_param(p, "align").map(str::to_ascii_lowercase).as_deref() {
|
||||
let align = match text_param(p, "align", C)?.map(str::to_ascii_lowercase).as_deref() {
|
||||
None | Some("center") | Some("centre") => RubyAlign::Center,
|
||||
Some("start") | Some("left") | Some("top") => RubyAlign::Start,
|
||||
Some("end") | Some("right") | Some("bottom") => RubyAlign::End,
|
||||
@@ -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);
|
||||
@@ -812,19 +815,21 @@ pub(crate) fn justify_param(v: &str) -> Option<Justify> {
|
||||
|
||||
fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.setStyle";
|
||||
let font = str_param(p, "font").map(str::to_string);
|
||||
let style = str_param(p, "style").map(str::to_string);
|
||||
let size = len_param(p, "size");
|
||||
let font = text_param(p, "font", C)?.map(str::to_string);
|
||||
let style = text_param(p, "style", C)?.map(str::to_string);
|
||||
let size = length_given(p, "size", C)?;
|
||||
if size.is_some_and(|v| v <= 0.0) {
|
||||
return Err(bad(C, "size must be positive"));
|
||||
}
|
||||
let leading = match p.get("leading") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(None),
|
||||
Some(_) => Some(Some(len_param(p, "leading").ok_or_else(|| bad(C, "leading must be a number or \"auto\""))?.clamp(0.1, 5000.0))),
|
||||
Some(_) => {
|
||||
Some(Some(length_given(p, "leading", C).ok().flatten().ok_or_else(|| bad(C, "leading must be a number or \"auto\""))?.clamp(0.1, 5000.0)))
|
||||
}
|
||||
};
|
||||
let tracking = num_param(p, "tracking");
|
||||
let justify = match str_param(p, "justify") {
|
||||
let tracking = number_given(p, "tracking", C)?;
|
||||
let justify = match text_param(p, "justify", C)? {
|
||||
Some(j) => Some(justify_param(j).ok_or_else(|| bad(C, "justify must be auto|left|center|right|justifyAll"))?),
|
||||
None => None,
|
||||
};
|
||||
@@ -1282,7 +1287,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = super::draw2::usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad(C, "missing anchor"))?;
|
||||
let out = str_param(p, "which") != Some("in");
|
||||
let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in");
|
||||
let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
|
||||
let independent = switch_or(p, "independent", false, C)?;
|
||||
let node = s.doc()?.doc.node(id);
|
||||
|
||||
@@ -94,6 +94,7 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[
|
||||
"view.separationsPreview",
|
||||
"prefs.set",
|
||||
"prefs.reset",
|
||||
"prefs.import",
|
||||
"text.addFontFiles",
|
||||
];
|
||||
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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.
|
||||
@@ -259,6 +262,10 @@ pub struct Session {
|
||||
pub(crate) script_stop: vectorcraft_js::Interrupt,
|
||||
/// The report of the run that ended last.
|
||||
pub(crate) script_report: Option<Value>,
|
||||
/// The Script Console's lines ([`script::console`]).
|
||||
pub(crate) script_console: script::console::Console,
|
||||
/// The runs started in this session, which numbers each run's console lines.
|
||||
pub(crate) script_runs: u64,
|
||||
/// `script.run` starts the job and returns, and the frontend advances it once per frame
|
||||
/// ([`Session::script_pump`]). Off, `script.run` advances it to its end.
|
||||
pub script_frames: bool,
|
||||
|
||||
@@ -124,6 +124,9 @@ pub struct Prefs {
|
||||
pub guide_style: String,
|
||||
/// Lock Guides by Default: the app starts with View › Guides › Lock Guides on.
|
||||
pub lock_guides_by_default: bool,
|
||||
/// Artboard Guides with Cmd/Ctrl + Ruler Drag: Cmd/Ctrl held when a guide is dragged out of a
|
||||
/// ruler makes it a guide of the active artboard, or with the Artboard tool a canvas guide.
|
||||
pub cmd_ruler_drag_artboard_guides: bool,
|
||||
pub grid_color: String,
|
||||
pub grid_style: String,
|
||||
pub gridline_every: f64,
|
||||
@@ -434,6 +437,7 @@ impl Default for Prefs {
|
||||
guide_color: s("#4affff"),
|
||||
guide_style: s("lines"),
|
||||
lock_guides_by_default: false,
|
||||
cmd_ruler_drag_artboard_guides: false,
|
||||
grid_color: s("#c8c8c8"),
|
||||
grid_style: s("lines"),
|
||||
gridline_every: 72.0,
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//! The Script Console: what scripts write with `$.write` and `$.writeln`, what they log with
|
||||
//! `vc.log`, their uncaught errors, and a start, an end and a report line for each run.
|
||||
//!
|
||||
//! A session keeps its own console, and each run keeps one more for its report. Each holds at most
|
||||
//! [`MAX_CONSOLE_LINES`] lines and [`MAX_CONSOLE_BYTES`] of text, dropping its oldest lines first,
|
||||
//! and a line holds at most [`MAX_LINE_BYTES`], cut at a character boundary and ended with
|
||||
//! [`CUT_MARK`]. A script's name in its lines is cut the same way to [`MAX_NAME_BYTES`]. These are
|
||||
//! VectorCraft's own limits. A line break is a line feed, a carriage
|
||||
//! return or the two together. Other control characters show as their Unicode Control Pictures
|
||||
//! (U+2400 to U+2421), and the line and paragraph separators as U+2424.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The most lines a console keeps.
|
||||
pub const MAX_CONSOLE_LINES: usize = 2_048;
|
||||
/// The most bytes of text (UTF-8) a console keeps.
|
||||
pub const MAX_CONSOLE_BYTES: usize = 1 << 20;
|
||||
/// The most bytes (UTF-8) of one line, its cut mark included.
|
||||
pub const MAX_LINE_BYTES: usize = 4_096;
|
||||
/// The most bytes (UTF-8) of a script's name as console lines give it, its cut mark included.
|
||||
pub const MAX_NAME_BYTES: usize = 256;
|
||||
/// The end of a line that was cut.
|
||||
pub const CUT_MARK: char = '…';
|
||||
|
||||
/// How a run ended, as its end line gives it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Ending {
|
||||
/// The script ran to its end and its changes were kept.
|
||||
Finished,
|
||||
/// An uncaught error or a syntax error.
|
||||
Error,
|
||||
/// The instructions ran out (`maxFuel`).
|
||||
Fuel,
|
||||
/// A host limit: host calls, data passed to commands, growth, or a command's fault.
|
||||
HostLimit,
|
||||
/// Another limit of the interpreter: heap, call depth or a nested run that could not pause.
|
||||
Limit,
|
||||
/// `script.stop`, Stop or a cancel from the caller.
|
||||
Stopped,
|
||||
/// A fault inside VectorCraft.
|
||||
Internal,
|
||||
}
|
||||
|
||||
impl Ending {
|
||||
/// The id `script.console` gives.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Ending::Finished => "finished",
|
||||
Ending::Error => "error",
|
||||
Ending::Fuel => "fuel",
|
||||
Ending::HostLimit => "hostLimit",
|
||||
Ending::Limit => "limit",
|
||||
Ending::Stopped => "stopped",
|
||||
Ending::Internal => "internal",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A command among the slowest of a run: its id, how often it ran and how long it took.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Slow {
|
||||
pub id: String,
|
||||
pub calls: u64,
|
||||
pub total_ms: u64,
|
||||
pub max_ms: u64,
|
||||
}
|
||||
|
||||
/// What a console line holds.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Entry {
|
||||
/// The run started.
|
||||
Start,
|
||||
/// A line of `$.write` and `$.writeln` output.
|
||||
Output(String),
|
||||
/// A `vc.log` entry: a string as it is, any other value as JSON.
|
||||
Log(String),
|
||||
/// The uncaught error that ended the run: `name:line:column: message`.
|
||||
Error(String),
|
||||
/// The run ended.
|
||||
End(Ending),
|
||||
/// The run's report: its time (when the platform has a clock), host calls and slowest commands.
|
||||
Report { ms: Option<u64>, host_calls: u64, slowest: Vec<Slow> },
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
/// The id of the line's kind that `script.console` gives.
|
||||
pub fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Entry::Start => "start",
|
||||
Entry::Output(_) => "output",
|
||||
Entry::Log(_) => "log",
|
||||
Entry::Error(_) => "error",
|
||||
Entry::End(_) => "end",
|
||||
Entry::Report { .. } => "report",
|
||||
}
|
||||
}
|
||||
|
||||
/// The line's text in English, as `script.console` and the run report give it.
|
||||
pub fn text(&self) -> String {
|
||||
match self {
|
||||
Entry::Start => "started".to_string(),
|
||||
Entry::Output(t) | Entry::Log(t) | Entry::Error(t) => t.clone(),
|
||||
Entry::End(e) => format!("ended: {}", e.id()),
|
||||
Entry::Report { ms, host_calls, slowest } => {
|
||||
let time = ms.map_or_else(|| "time unavailable".to_string(), |ms| format!("{ms} ms"));
|
||||
let calls = if *host_calls == 1 { "host call" } else { "host calls" };
|
||||
let mut s = format!("{time}, {host_calls} {calls}");
|
||||
if !slowest.is_empty() {
|
||||
let list: Vec<String> = slowest.iter().map(|c| format!("{} ×{} {} ms", c.id, c.calls, c.total_ms)).collect();
|
||||
s.push_str("; slowest: ");
|
||||
s.push_str(&list.join(", "));
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes the line counts toward [`MAX_CONSOLE_BYTES`].
|
||||
fn bytes(&self) -> usize {
|
||||
match self {
|
||||
Entry::Output(t) | Entry::Log(t) | Entry::Error(t) => t.len(),
|
||||
Entry::Start | Entry::End(_) => 16,
|
||||
Entry::Report { slowest, .. } => 48 + slowest.iter().map(|c| c.id.len() + 24).sum::<usize>(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A console line: the run it belongs to, by its number in the session, and the script's name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ConsoleLine {
|
||||
pub run: u64,
|
||||
pub name: Arc<str>,
|
||||
pub entry: Entry,
|
||||
}
|
||||
|
||||
/// A bounded store of console lines.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Console {
|
||||
lines: VecDeque<ConsoleLine>,
|
||||
bytes: usize,
|
||||
dropped: u64,
|
||||
truncated: u64,
|
||||
/// The number of the first line kept: every line the console was given has its own number,
|
||||
/// counted from 0, which dropping and clearing do not change.
|
||||
first: u64,
|
||||
}
|
||||
|
||||
impl Console {
|
||||
/// The lines kept, oldest first.
|
||||
pub fn lines(&self) -> &VecDeque<ConsoleLine> {
|
||||
&self.lines
|
||||
}
|
||||
|
||||
/// The number of [`Console::lines`]' first line; each line after it has the next number.
|
||||
pub fn first_number(&self) -> u64 {
|
||||
self.first
|
||||
}
|
||||
|
||||
/// The lines dropped to make room since the console was last cleared.
|
||||
pub fn dropped_lines(&self) -> u64 {
|
||||
self.dropped
|
||||
}
|
||||
|
||||
/// The lines cut to [`MAX_LINE_BYTES`] since the console was last cleared.
|
||||
pub fn truncated_lines(&self) -> u64 {
|
||||
self.truncated
|
||||
}
|
||||
|
||||
/// Removes every line and sets the counts to zero.
|
||||
pub fn clear(&mut self) {
|
||||
*self = Self { first: self.first + self.lines.len() as u64, ..Self::default() };
|
||||
}
|
||||
|
||||
/// Adds a line, dropping the oldest ones past the limits. `cut`: the line's text was cut.
|
||||
pub(crate) fn push(&mut self, line: ConsoleLine, cut: bool) {
|
||||
if cut {
|
||||
self.truncated = self.truncated.saturating_add(1);
|
||||
}
|
||||
let bytes = line.entry.bytes();
|
||||
while !self.lines.is_empty() && (self.lines.len() >= MAX_CONSOLE_LINES || self.bytes + bytes > MAX_CONSOLE_BYTES) {
|
||||
if let Some(old) = self.lines.pop_front() {
|
||||
self.bytes -= old.entry.bytes();
|
||||
self.dropped = self.dropped.saturating_add(1);
|
||||
self.first += 1;
|
||||
}
|
||||
}
|
||||
self.bytes += bytes;
|
||||
self.lines.push_back(line);
|
||||
}
|
||||
|
||||
/// `{lines: [text…], droppedLines, truncatedLines}`, as a run report gives its console.
|
||||
pub(crate) fn report(&self) -> Value {
|
||||
let lines: Vec<String> = self.lines.iter().map(|l| l.entry.text()).collect();
|
||||
json!({"lines": lines, "droppedLines": self.dropped, "truncatedLines": self.truncated})
|
||||
}
|
||||
|
||||
/// `{lines: [{run, name, kind, text}…], droppedLines, truncatedLines}`, as `script.console`
|
||||
/// gives it.
|
||||
pub fn to_json(&self) -> Value {
|
||||
let lines: Vec<Value> =
|
||||
self.lines.iter().map(|l| json!({"run": l.run, "name": &*l.name, "kind": l.entry.kind(), "text": l.entry.text()})).collect();
|
||||
json!({"lines": lines, "droppedLines": self.dropped, "truncatedLines": self.truncated})
|
||||
}
|
||||
}
|
||||
|
||||
/// `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.
|
||||
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}',
|
||||
'\u{80}'..='\u{9f}' => '\u{fffd}',
|
||||
'\u{2028}' | '\u{2029}' => '\u{2424}',
|
||||
c => c,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `text` to `line` as the console shows it, up to [`MAX_LINE_BYTES`]. → `true` when part of
|
||||
/// it did not fit.
|
||||
fn append(line: &mut String, text: &str) -> bool {
|
||||
for c in text.chars().map(shown) {
|
||||
if line.len() + c.len_utf8() > MAX_LINE_BYTES {
|
||||
return true;
|
||||
}
|
||||
line.push(c);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A script's name as console lines give it: shown as a line shows its text, and cut to
|
||||
/// [`MAX_NAME_BYTES`] with [`CUT_MARK`].
|
||||
pub(crate) fn line_name(name: &str) -> Arc<str> {
|
||||
let mut out = String::new();
|
||||
for c in name.chars().map(shown) {
|
||||
if out.len() + c.len_utf8() > MAX_NAME_BYTES {
|
||||
mark_cut(&mut out, MAX_NAME_BYTES);
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
Arc::from(out)
|
||||
}
|
||||
|
||||
/// Ends a line that was cut with [`CUT_MARK`], within `limit` bytes.
|
||||
fn mark_cut(line: &mut String, limit: usize) {
|
||||
let mut at = line.len().min(limit - CUT_MARK.len_utf8());
|
||||
while !line.is_char_boundary(at) {
|
||||
at -= 1;
|
||||
}
|
||||
line.truncate(at);
|
||||
line.push(CUT_MARK);
|
||||
}
|
||||
|
||||
/// What `$.write` has written of the line it has not ended yet.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Pending {
|
||||
text: String,
|
||||
/// Part of the line did not fit; the rest is left out until the line ends.
|
||||
cut: bool,
|
||||
/// The last text written ended with a carriage return, so a line feed next ends no line.
|
||||
after_cr: bool,
|
||||
}
|
||||
|
||||
impl Pending {
|
||||
/// Writes `text`, calling `done` with each line it ends and whether that line was cut.
|
||||
pub(crate) fn write(&mut self, text: &str, mut done: impl FnMut(String, bool)) {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut rest = text;
|
||||
if self.after_cr && rest.starts_with('\n') {
|
||||
rest = &rest[1..];
|
||||
}
|
||||
self.after_cr = false;
|
||||
while let Some(at) = rest.find(['\r', '\n']) {
|
||||
self.add(&rest[..at]);
|
||||
done(self.take_line(), self.cut);
|
||||
self.cut = false;
|
||||
let skip = if rest[at..].starts_with("\r\n") { 2 } else { 1 };
|
||||
if skip == 1 && rest[at..].starts_with('\r') && at + 1 == rest.len() {
|
||||
self.after_cr = true;
|
||||
}
|
||||
rest = &rest[at + skip..];
|
||||
}
|
||||
self.add(rest);
|
||||
}
|
||||
|
||||
/// Ends the current line, empty or not.
|
||||
pub(crate) fn end_line(&mut self, mut done: impl FnMut(String, bool)) {
|
||||
let cut = self.cut;
|
||||
done(self.take_line(), cut);
|
||||
self.cut = false;
|
||||
self.after_cr = false;
|
||||
}
|
||||
|
||||
/// Is part of a line waiting for its end?
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.text.is_empty() && !self.cut
|
||||
}
|
||||
|
||||
fn add(&mut self, text: &str) {
|
||||
if !self.cut && !text.is_empty() {
|
||||
self.cut = append(&mut self.text, text);
|
||||
}
|
||||
}
|
||||
|
||||
fn take_line(&mut self) -> String {
|
||||
if self.cut {
|
||||
mark_cut(&mut self.text, MAX_LINE_BYTES);
|
||||
}
|
||||
std::mem::take(&mut self.text)
|
||||
}
|
||||
}
|
||||
@@ -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")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! The members of a script's `$` object besides `$.write`, `$.writeln`, `$.evalFile`, `$.fileName`
|
||||
//! and `$.includePath`, from the Dollar object
|
||||
//! page (<https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/>), and
|
||||
//! the locale the global `localize` reads
|
||||
//! (<https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/>).
|
||||
//!
|
||||
//! Every value here belongs to one run: a run starts with the locale of the interface, the
|
||||
//! environment values of [`ENV_NAMES`] read from the process, localization off and a timer at zero,
|
||||
//! and what a script changes ends with its run. `$.setenv` never changes the process's environment.
|
||||
//!
|
||||
//! These are VectorCraft's own values and rules: `$.appEncoding` is always UTF-8; `$.build` and
|
||||
//! `$.version` give VectorCraft's version, `$.engineName` is `VectorCraft` and `$.buildDate` is
|
||||
//! `null`; `$.flags` takes only 512, which turns localization on; `$.level` and `$.memCache` are 0
|
||||
//! and `$.screens` is empty; `$.os` names the system without its version; `$.strict` is whether the
|
||||
//! realm reads scripts as strict mode code; `$.bp` and `$.colorPicker` throw, since scripts have no
|
||||
//! debugger and cannot show a dialog; `$.gc` does nothing, since the interpreter collects its own
|
||||
//! garbage; `$.getenv` and `$.setenv` know only [`ENV_NAMES`], with values of at most
|
||||
//! [`MAX_ENV_BYTES`] bytes of letters, digits and `_ . - @`; and `$.sleep` waits at most
|
||||
//! [`MAX_SLEEP_MS`] milliseconds, between two frames of the app, and does not wait on the web,
|
||||
//! which has no clock.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use vectorcraft_js::{Data, HostError, HostItem, Localization, ScriptItem};
|
||||
|
||||
use super::{Host, function};
|
||||
|
||||
/// The longest `$.sleep`, in milliseconds.
|
||||
pub const MAX_SLEEP_MS: f64 = 1_000.0;
|
||||
/// The environment variables `$.getenv` reads and `$.setenv` sets.
|
||||
pub const ENV_NAMES: &[&str] = &["LANG", "LC_MESSAGES", "LC_ALL", "OS"];
|
||||
/// The most bytes of an environment value.
|
||||
pub const MAX_ENV_BYTES: usize = 64;
|
||||
/// The value of `$.flags` that turns localization on, the only one a script may set.
|
||||
pub const LOCALIZE_FLAG: f64 = 512.0;
|
||||
|
||||
/// What `$` knows of a run.
|
||||
pub(crate) struct RunInfo {
|
||||
/// The locale the run starts with, such as `de_DE`.
|
||||
pub locale: String,
|
||||
/// The realm reads scripts as strict mode code.
|
||||
pub strict: bool,
|
||||
}
|
||||
|
||||
/// The locale for an interface language code such as `de`, `pt-br` or `zh-hant`: the language,
|
||||
/// with its region after `_` where the code gives one (`pt_BR`; `zh_CN` for `zh-hans` and `zh_TW`
|
||||
/// for `zh-hant`); `en` for a code that is not a language.
|
||||
pub(crate) fn ui_locale(code: &str) -> String {
|
||||
let mut parts = code.split(['-', '_']);
|
||||
let language = parts.next().unwrap_or_default().to_ascii_lowercase();
|
||||
if !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_lowercase()) {
|
||||
return "en".into();
|
||||
}
|
||||
let region = match parts.next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("hans") => Some("CN".to_string()),
|
||||
Some("hant") => Some("TW".to_string()),
|
||||
Some(r) if r.len() == 2 && r.bytes().all(|b| b.is_ascii_lowercase()) => Some(r.to_ascii_uppercase()),
|
||||
_ => None,
|
||||
};
|
||||
region.map_or(language.clone(), |r| format!("{language}_{r}"))
|
||||
}
|
||||
|
||||
/// A locale a script gives `$.locale`, as `ll` or `ll_RR`: a language of two or three letters and
|
||||
/// an optional region of two letters or three digits, joined by `_` or `-`, in any case.
|
||||
fn script_locale(text: &str) -> Option<String> {
|
||||
let mut parts = text.split(['-', '_']);
|
||||
let language = parts.next()?;
|
||||
let region = parts.next();
|
||||
if parts.next().is_some() || !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||
return None;
|
||||
}
|
||||
let language = language.to_ascii_lowercase();
|
||||
match region {
|
||||
None => Some(language),
|
||||
Some(r) if r.len() == 2 && r.bytes().all(|b| b.is_ascii_alphabetic()) => Some(format!("{language}_{}", r.to_ascii_uppercase())),
|
||||
Some(r) if r.len() == 3 && r.bytes().all(|b| b.is_ascii_digit()) => Some(format!("{language}_{r}")),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The languages whose numbers are written with a decimal comma (VectorCraft's own list).
|
||||
const DECIMAL_COMMA: &[&str] = &[
|
||||
"bg", "ca", "cs", "da", "de", "el", "es", "et", "fi", "fr", "hr", "hu", "id", "it", "lt", "lv", "nb", "nl", "no", "pl", "pt", "ro", "ru", "sk",
|
||||
"sl", "sr", "sv", "tr", "uk", "vi",
|
||||
];
|
||||
|
||||
/// The character `locale` writes before a number's fraction.
|
||||
pub(crate) fn decimal_point(locale: &str) -> &'static str {
|
||||
let language = locale.split('_').next().unwrap_or_default();
|
||||
if DECIMAL_COMMA.contains(&language) { "," } else { "." }
|
||||
}
|
||||
|
||||
/// The platform suffix of a localization object's names on this system.
|
||||
pub(crate) fn platform() -> Option<&'static str> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
None
|
||||
} else if cfg!(windows) {
|
||||
Some("Win")
|
||||
} else if cfg!(target_os = "macos") {
|
||||
Some("Mac")
|
||||
} else {
|
||||
Some("Unix")
|
||||
}
|
||||
}
|
||||
|
||||
/// `$.os`: the system, without its version.
|
||||
fn os() -> &'static str {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
"Web"
|
||||
} else if cfg!(windows) {
|
||||
"Windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"macOS"
|
||||
} else if cfg!(target_os = "linux") {
|
||||
"Linux"
|
||||
} else if cfg!(target_os = "freebsd") {
|
||||
"FreeBSD"
|
||||
} else {
|
||||
"Unix"
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `value` one an environment value may be?
|
||||
fn env_value_ok(value: &str) -> bool {
|
||||
value.len() <= MAX_ENV_BYTES && value.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-' | b'@'))
|
||||
}
|
||||
|
||||
/// The values of [`ENV_NAMES`] in the process's environment, each left out when it is not one an
|
||||
/// environment value may be.
|
||||
fn process_env() -> Vec<(&'static str, Option<String>)> {
|
||||
ENV_NAMES.iter().map(|&n| (n, std::env::var(n).ok().filter(|v| env_value_ok(v)))).collect()
|
||||
}
|
||||
|
||||
fn one_string(args: &[Data], name: &str) -> Result<String, HostError> {
|
||||
match args.first() {
|
||||
Some(Data::String(s)) => Ok(s.clone()),
|
||||
_ => Err(HostError::Type(format!("$.{name}: give a name, as a string"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn value(v: Data) -> HostItem {
|
||||
HostItem::Value(v)
|
||||
}
|
||||
|
||||
fn text(s: impl Into<String>) -> Data {
|
||||
Data::String(s.into())
|
||||
}
|
||||
|
||||
/// The members `$` has besides `write`, `writeln`, `evalFile`, `fileName` and `includePath`.
|
||||
pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localization>) -> Vec<(String, HostItem)> {
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let host_locale = info.locale.clone();
|
||||
localization.set_locale(&info.locale);
|
||||
localization.set_platform(platform());
|
||||
let env = Rc::new(RefCell::new(process_env()));
|
||||
let timer = Rc::new(Cell::new(Duration::ZERO));
|
||||
let getter = |f: Rc<dyn Fn() -> Data>| HostItem::Getter(function(move |_| Ok(f())));
|
||||
let property = |get: Rc<dyn Fn() -> Data>, set: Rc<dyn Fn(Data) -> Result<(), HostError>>| HostItem::Property {
|
||||
get: function(move |_| Ok(get())),
|
||||
set: function(move |mut a| {
|
||||
set(if a.is_empty() { Data::Undefined } else { a.swap_remove(0) })?;
|
||||
Ok(Data::Undefined)
|
||||
}),
|
||||
};
|
||||
let fail = |message: &'static str| HostItem::Function(function(move |_| Err(HostError::Error(message.to_string()))));
|
||||
|
||||
let locale = {
|
||||
let (l, s) = (localization.clone(), localization.clone());
|
||||
property(
|
||||
Rc::new(move || text(l.locale())),
|
||||
Rc::new(move |v| {
|
||||
let locale = match v {
|
||||
Data::Null | Data::Undefined => host_locale.clone(),
|
||||
Data::String(t) if t.is_empty() => host_locale.clone(),
|
||||
Data::String(t) => script_locale(&t).ok_or_else(|| HostError::Range(BAD_LOCALE.to_string()))?,
|
||||
_ => return Err(HostError::Type(BAD_LOCALE.to_string())),
|
||||
};
|
||||
s.set_locale(&locale);
|
||||
Ok(())
|
||||
}),
|
||||
)
|
||||
};
|
||||
let localize = {
|
||||
let (l, s) = (localization.clone(), localization.clone());
|
||||
property(
|
||||
Rc::new(move || Data::Bool(l.enabled())),
|
||||
Rc::new(move |v| match v {
|
||||
Data::Bool(on) => {
|
||||
s.set_enabled(on);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(HostError::Type("$.localize: give true or false".into())),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let flags = {
|
||||
let (l, s) = (localization.clone(), localization.clone());
|
||||
property(
|
||||
Rc::new(move || Data::Number(if l.enabled() { LOCALIZE_FLAG } else { 0.0 })),
|
||||
Rc::new(move |v| match v {
|
||||
Data::Number(n) if n == 0.0 || n == LOCALIZE_FLAG => {
|
||||
s.set_enabled(n == LOCALIZE_FLAG);
|
||||
Ok(())
|
||||
}
|
||||
Data::Number(_) => Err(HostError::Range("$.flags: only 512, which turns localization on, or 0 can be set".into())),
|
||||
_ => Err(HostError::Type("$.flags: give a number".into())),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let decimal = {
|
||||
let l = localization.clone();
|
||||
getter(Rc::new(move || text(decimal_point(&l.locale()))))
|
||||
};
|
||||
let app_encoding = property(
|
||||
Rc::new(|| text("UTF-8")),
|
||||
Rc::new(|v| match v {
|
||||
Data::String(t) if t.eq_ignore_ascii_case("utf-8") || t.eq_ignore_ascii_case("utf8") => Ok(()),
|
||||
Data::String(_) => Err(HostError::Range("$.appEncoding: scripts here read and write UTF-8 only".into())),
|
||||
_ => Err(HostError::Type("$.appEncoding: give an encoding's name, as a string".into())),
|
||||
}),
|
||||
);
|
||||
let mem_cache =
|
||||
property(Rc::new(|| Data::Number(0.0)), Rc::new(|_| Err(HostError::Error("$.memCache: the memory cache size cannot be set".into()))));
|
||||
let hires_timer = {
|
||||
let (h, last) = (host.clone(), timer.clone());
|
||||
getter(Rc::new(move || {
|
||||
let Some(now) = h.elapsed() else { return Data::Number(0.0) };
|
||||
let since = now.saturating_sub(last.replace(now));
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
Data::Number(since.as_micros() as f64)
|
||||
}))
|
||||
};
|
||||
let getenv = {
|
||||
let (h, env) = (host.clone(), env.clone());
|
||||
function(move |a| {
|
||||
let name = one_string(&a, "getenv")?;
|
||||
h.charge_call(name.len() as u64 + 2)?;
|
||||
let env = env.borrow();
|
||||
let found = env.iter().find(|(n, _)| *n == name).and_then(|(_, v)| v.clone());
|
||||
Ok(found.map_or(Data::Null, Data::String))
|
||||
})
|
||||
};
|
||||
let setenv = {
|
||||
let (h, env) = (host.clone(), env.clone());
|
||||
function(move |a| {
|
||||
let name = one_string(&a, "setenv")?;
|
||||
let Some(Data::String(v)) = a.get(1) else { return Err(HostError::Type("$.setenv: give a value, as a string".into())) };
|
||||
h.charge_call((name.len() + v.len()) as u64 + 4)?;
|
||||
let mut env = env.borrow_mut();
|
||||
let Some(slot) = env.iter_mut().find(|(n, _)| *n == name) else {
|
||||
return Err(HostError::Error(format!("$.setenv: only {} can be set", ENV_NAMES.join(", "))));
|
||||
};
|
||||
if !env_value_ok(v) {
|
||||
return Err(HostError::Range(format!("$.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @")));
|
||||
}
|
||||
slot.1 = Some(v.clone());
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
};
|
||||
let sleep = {
|
||||
let h = host.clone();
|
||||
function(move |a| {
|
||||
let ms = match a.first() {
|
||||
Some(Data::Number(n)) if (0.0..=MAX_SLEEP_MS).contains(n) => *n,
|
||||
Some(Data::Number(_)) => return Err(HostError::Range(format!("$.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS}"))),
|
||||
_ => return Err(HostError::Type("$.sleep: give a number of milliseconds".into())),
|
||||
};
|
||||
h.charge_call(8)?;
|
||||
h.sleep(Duration::from_secs_f64(ms / 1000.0))?;
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
};
|
||||
let about = text(format!("VectorCraft script engine {version}"));
|
||||
|
||||
vec![
|
||||
("about".into(), HostItem::Function(function(move |_| Ok(about.clone())))),
|
||||
("appEncoding".into(), app_encoding),
|
||||
("bp".into(), fail("$.bp: scripts here have no debugger")),
|
||||
("build".into(), value(text(version))),
|
||||
("buildDate".into(), value(Data::Null)),
|
||||
("colorPicker".into(), fail("$.colorPicker: scripts cannot show a dialog yet")),
|
||||
("decimalPoint".into(), decimal),
|
||||
("engineName".into(), value(text("VectorCraft"))),
|
||||
("error".into(), HostItem::Script(ScriptItem::LastError)),
|
||||
("flags".into(), flags),
|
||||
("gc".into(), HostItem::Function(function(|_| Ok(Data::Undefined)))),
|
||||
("getenv".into(), HostItem::Function(getenv)),
|
||||
("global".into(), HostItem::Script(ScriptItem::Global)),
|
||||
("hiresTimer".into(), hires_timer),
|
||||
("level".into(), value(Data::Number(0.0))),
|
||||
("line".into(), HostItem::Script(ScriptItem::Line)),
|
||||
("locale".into(), locale),
|
||||
("localize".into(), localize),
|
||||
("memCache".into(), mem_cache),
|
||||
("os".into(), value(text(os()))),
|
||||
("screens".into(), value(Data::Array(Vec::new()))),
|
||||
("setenv".into(), HostItem::Function(setenv)),
|
||||
("sleep".into(), HostItem::Function(sleep)),
|
||||
("stack".into(), HostItem::Script(ScriptItem::Stack)),
|
||||
("strict".into(), value(Data::Bool(info.strict))),
|
||||
("version".into(), value(text(version))),
|
||||
]
|
||||
}
|
||||
|
||||
const BAD_LOCALE: &str = "$.locale: give a locale such as \"en\" or \"de_DE\", or null for the interface's";
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
+600
-41
@@ -20,7 +20,29 @@
|
||||
//! The values here are VectorCraft's own limits: [`MAX_SOURCE_BYTES`], [`DEFAULT_FUEL`],
|
||||
//! [`MAX_FUEL`], [`SLICE_FUEL`], [`HEAP_BYTES`], [`MAX_HOST_CALLS`], [`GROWTH_OBJECTS`],
|
||||
//! [`GROWTH_BYTES`], [`MAX_CONTINUES`], [`MAX_LOG_LINES`], [`MAX_LOG_BYTES`], [`MAX_ARGS_BYTES`],
|
||||
//! and the 64 levels, 16 MiB and 1,048,576 entries of [`vectorcraft_js::DataLimits`]'s default.
|
||||
//! 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. The rest of `$`, and the global `localize` and
|
||||
//! `toSource`, are in [`dollar`].
|
||||
//!
|
||||
//! `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 dollar;
|
||||
pub mod include;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
@@ -36,6 +58,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.
|
||||
@@ -72,7 +96,9 @@ 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"];
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"];
|
||||
/// The most commands a run's report lists in `slowestCommands`.
|
||||
pub const SLOWEST_COMMANDS: usize = 5;
|
||||
|
||||
/// What the step of a run's one undo step is called.
|
||||
pub const STEP_LABEL: &str = "Run Script";
|
||||
@@ -121,10 +147,18 @@ 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 locale the run starts with (`$.locale`).
|
||||
pub locale: String,
|
||||
/// The answers to the dialogs of a run with nobody to ask, in order.
|
||||
pub answers: Vec<DialogAnswer>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -136,21 +170,27 @@ thread_local! {
|
||||
static NEXT_JOB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
/// A session's hold on its running job: while one exists the lease is held. Dropping it ends the job.
|
||||
/// It keeps the run's number and its name as console lines give it, so the run's console entry can
|
||||
/// end when the job is gone.
|
||||
#[derive(Debug)]
|
||||
pub struct JobKey(u64);
|
||||
pub struct JobKey {
|
||||
id: u64,
|
||||
run: u64,
|
||||
name: Arc<str>,
|
||||
}
|
||||
|
||||
impl Drop for JobKey {
|
||||
fn drop(&mut self) {
|
||||
let _ = JOBS.try_with(|jobs| {
|
||||
if let Ok(mut jobs) = jobs.try_borrow_mut() {
|
||||
jobs.remove(&self.0);
|
||||
jobs.remove(&self.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn with_job<T>(key: &JobKey, f: impl FnOnce(&mut Job) -> T) -> Option<T> {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.0).map(f))
|
||||
JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.id).map(f))
|
||||
}
|
||||
|
||||
/// The state a script changes that a rollback puts back.
|
||||
@@ -446,13 +486,169 @@ struct Host {
|
||||
log: RefCell<Vec<Value>>,
|
||||
log_bytes: Cell<usize>,
|
||||
written: RefCell<Vec<String>>,
|
||||
/// The run's number in its session, and the script's name, which its console lines carry.
|
||||
run: u64,
|
||||
name: Arc<str>,
|
||||
/// The run's own output and error, for its report.
|
||||
console: RefCell<console::Console>,
|
||||
/// The line `$.write` has not ended yet.
|
||||
pending: RefCell<console::Pending>,
|
||||
counts: Counts,
|
||||
/// Each command `vc.run` ran: its calls, its total time and its longest call, in nanoseconds.
|
||||
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 file, line and column of each error `$.evalFile` raised for a file it could not run, in
|
||||
/// order: the error's mark ([`HostError::Marked`]) is its index.
|
||||
eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>,
|
||||
/// When the run started, where the platform has a clock.
|
||||
started: Option<std::time::Instant>,
|
||||
/// The time since [`Host::started`] at which a `$.sleep` ends.
|
||||
wake_at: Cell<Option<std::time::Duration>>,
|
||||
/// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]).
|
||||
can_wait: Rc<Cell<bool>>,
|
||||
/// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one).
|
||||
eval_strict: Cell<Option<bool>>,
|
||||
}
|
||||
|
||||
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
|
||||
#[derive(Default)]
|
||||
struct Counts {
|
||||
vc_run: Cell<u64>,
|
||||
document_reads: Cell<u64>,
|
||||
command_list_reads: Cell<u64>,
|
||||
vc_log: Cell<u64>,
|
||||
console_writes: Cell<u64>,
|
||||
}
|
||||
|
||||
impl Counts {
|
||||
fn json(&self) -> Value {
|
||||
json!({
|
||||
"vcRun": self.vc_run.get(),
|
||||
"documentReads": self.document_reads.get(),
|
||||
"commandListReads": self.command_list_reads.get(),
|
||||
"vcLog": self.vc_log.get(),
|
||||
"consoleWrites": self.console_writes.get(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn bump(c: &Cell<u64>) {
|
||||
c.set(c.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// Now, where the platform has a clock (not in a wasm build).
|
||||
fn clock() -> Option<std::time::Instant> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
Some(std::time::Instant::now())
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Whole milliseconds, rounded down.
|
||||
fn millis(nanos: u128) -> u64 {
|
||||
u64::try_from(nanos / 1_000_000).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
/// The [`SLOWEST_COMMANDS`] commands of `times` that took longest in all, longest first and then by
|
||||
/// id.
|
||||
pub(crate) fn slowest(times: &HashMap<&'static str, (u64, u128, u128)>) -> Vec<console::Slow> {
|
||||
let mut all: Vec<(&&str, &(u64, u128, u128))> = times.iter().collect();
|
||||
all.sort_by(|a, b| b.1.1.cmp(&a.1.1).then_with(|| a.0.cmp(b.0)));
|
||||
all.into_iter()
|
||||
.take(SLOWEST_COMMANDS)
|
||||
.map(|(id, &(calls, total, max))| console::Slow { id: (*id).to_string(), calls, total_ms: millis(total), max_ms: millis(max) })
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// Adds a line to the run's console and, during a slice, to the session's.
|
||||
fn line(&self, entry: console::Entry, cut: bool) {
|
||||
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
|
||||
if let Ok(mut s) = self.session.try_borrow_mut() {
|
||||
s.script_console.push(line.clone(), cut);
|
||||
}
|
||||
self.console.borrow_mut().push(line, cut);
|
||||
}
|
||||
|
||||
/// `$.write` and `$.writeln`: `text`, then with `end` a line break.
|
||||
fn write(&self, text: &str, end: bool) {
|
||||
let mut pending = self.pending.borrow_mut();
|
||||
pending.write(text, |line, cut| self.line(console::Entry::Output(line), cut));
|
||||
if end {
|
||||
pending.end_line(|line, cut| self.line(console::Entry::Output(line), cut));
|
||||
}
|
||||
}
|
||||
|
||||
/// The time since the run started; none without a clock.
|
||||
fn elapsed(&self) -> Option<std::time::Duration> {
|
||||
#[cfg(test)]
|
||||
if TEST_NO_CLOCK.with(Cell::get) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(d) = TEST_ELAPSED.with(Cell::get) {
|
||||
return Some(d);
|
||||
}
|
||||
self.started.map(|s| s.elapsed())
|
||||
}
|
||||
|
||||
/// `$.sleep`: ends the slice, and the run does not go on until `d` has passed. Without a clock
|
||||
/// it does not wait. A getter, a conversion, a built-in's callback or a file `$.evalFile` runs
|
||||
/// cannot stop at the call, so a wait there is an error, with or without a clock.
|
||||
fn sleep(&self, d: std::time::Duration) -> std::result::Result<(), HostError> {
|
||||
if d.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
if !self.can_wait.get() {
|
||||
return Err(HostError::Error(
|
||||
"$.sleep: a run cannot wait 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"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if let Some(now) = self.elapsed() {
|
||||
self.wake_at.set(Some(now.saturating_add(d)));
|
||||
self.pause.set(true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The time left of a `$.sleep`, or none when the run is not asleep.
|
||||
fn asleep(&self) -> Option<std::time::Duration> {
|
||||
let wake = self.wake_at.get()?;
|
||||
let left = self.elapsed().map_or(std::time::Duration::ZERO, |now| wake.saturating_sub(now));
|
||||
if left.is_zero() {
|
||||
self.wake_at.set(None);
|
||||
return None;
|
||||
}
|
||||
Some(left)
|
||||
}
|
||||
|
||||
fn over(&self, limit: &str) -> HostError {
|
||||
HostError::Abort(limit.to_string())
|
||||
}
|
||||
|
||||
/// `error`, marked as an error at `file`, `line` and `column`, the place [`located`] gives when
|
||||
/// the run ends with it uncaught.
|
||||
fn placed(&self, error: HostError, file: Arc<str>, line: u32, column: u32) -> HostError {
|
||||
let mut places = self.eval_failures.borrow_mut();
|
||||
let Ok(mark) = u32::try_from(places.len()) else { return error };
|
||||
places.push((file, line, column));
|
||||
HostError::Marked { error: Box::new(error), mark }
|
||||
}
|
||||
|
||||
fn charge_call(&self, bytes: u64) -> std::result::Result<(), HostError> {
|
||||
let calls = self.calls.get() + 1;
|
||||
self.calls.set(calls);
|
||||
@@ -706,11 +902,20 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
|
||||
};
|
||||
let bytes = args.iter().map(data_size).sum();
|
||||
host.charge_call(bytes)?;
|
||||
bump(&host.counts.vc_run);
|
||||
let session = host.session.clone();
|
||||
let started = clock();
|
||||
let r = {
|
||||
let mut s = session.borrow_mut();
|
||||
step(&mut s, host, &id, ¶ms)
|
||||
};
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) {
|
||||
let nanos = started.elapsed().as_nanos();
|
||||
let mut times = host.commands.borrow_mut();
|
||||
let row = times.entry(spec.id).or_insert((0, 0, 0));
|
||||
*row = (row.0 + 1, row.1.saturating_add(nanos), row.2.max(nanos));
|
||||
}
|
||||
let (value, objects, added, save) = match r {
|
||||
Ok(done) => done,
|
||||
// A bug is not something a script can handle, and neither is a request to stop.
|
||||
@@ -778,10 +983,107 @@ fn vc_log(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError>
|
||||
return Err(HostError::Range(LOG_FULL.to_string()));
|
||||
}
|
||||
host.log_bytes.set(host.log_bytes.get() + bytes);
|
||||
host.log.borrow_mut().push(to_json(entry));
|
||||
let value = to_json(entry);
|
||||
let text = match &value {
|
||||
Value::String(s) => s.clone(),
|
||||
v => v.to_string(),
|
||||
};
|
||||
host.log.borrow_mut().push(value);
|
||||
each_line(&text, |line, cut| host.line(console::Entry::Log(line), cut));
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// Calls `done` with each console line of `text` and whether that line was cut, one at a time.
|
||||
fn each_line(text: &str, mut done: impl FnMut(String, bool)) {
|
||||
let mut pending = console::Pending::default();
|
||||
pending.write(text, &mut done);
|
||||
pending.end_line(done);
|
||||
}
|
||||
|
||||
/// 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. Its other members are
|
||||
/// [`dollar::members`].
|
||||
fn dollar_object(host: &Rc<Host>, info: dollar::RunInfo, localization: &Rc<vectorcraft_js::Localization>) -> Vec<(String, HostItem)> {
|
||||
let writer = |end: bool| {
|
||||
let h = host.clone();
|
||||
HostItem::TextFunction(function(move |a| {
|
||||
let text: String = a.iter().map(|d| if let Data::String(s) = d { s.as_str() } else { "" }).collect();
|
||||
h.charge_call(text.len() as u64 + 2)?;
|
||||
bump(&h.counts.console_writes);
|
||||
h.write(&text, end);
|
||||
Ok(Data::Undefined)
|
||||
}))
|
||||
};
|
||||
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()),
|
||||
}
|
||||
};
|
||||
let mut items = 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)),
|
||||
];
|
||||
items.extend(dollar::members(host, info, localization));
|
||||
items
|
||||
}
|
||||
|
||||
/// `$.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 };
|
||||
let error = match f.kind {
|
||||
include::FailKind::Limit => HostError::Abort(message),
|
||||
include::FailKind::Syntax => HostError::Syntax(message),
|
||||
include::FailKind::Error => HostError::Error(message),
|
||||
};
|
||||
if f.line > 0 { host.placed(error, f.file, f.line, f.column) } else { error }
|
||||
})?;
|
||||
// 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);
|
||||
return Err(host.placed(HostError::Syntax(message), file, line, column));
|
||||
}
|
||||
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 {
|
||||
Rc::new(f)
|
||||
}
|
||||
@@ -795,6 +1097,7 @@ fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> {
|
||||
let h = host.clone();
|
||||
function(move |_| {
|
||||
h.charge_call(64)?;
|
||||
bump(&h.counts.document_reads);
|
||||
vc_document(&h)
|
||||
})
|
||||
};
|
||||
@@ -804,6 +1107,7 @@ fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> {
|
||||
let size = data_size(&list);
|
||||
function(move |_| {
|
||||
h.charge_call(size)?;
|
||||
bump(&h.counts.command_list_reads);
|
||||
Ok((*list).clone())
|
||||
})
|
||||
};
|
||||
@@ -811,6 +1115,7 @@ fn vc_object(host: &Rc<Host>, args: Data) -> Vec<(String, HostItem)> {
|
||||
let h = host.clone();
|
||||
function(move |a| {
|
||||
h.charge_call(data_size(a.first().unwrap_or(&Data::Undefined)))?;
|
||||
bump(&h.counts.vc_log);
|
||||
vc_log(&h, a)
|
||||
})
|
||||
};
|
||||
@@ -840,22 +1145,69 @@ 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`]) with host error mark `mark`
|
||||
/// ([`Realm::error_mark`]), 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, mark: Option<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, and no script caught, is at that
|
||||
// file's place.
|
||||
if let Some((file, line, column)) = mark.and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
|
||||
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, column }, Some(file));
|
||||
}
|
||||
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 {
|
||||
@@ -873,6 +1225,19 @@ impl Session {
|
||||
self.script_report.as_ref()
|
||||
}
|
||||
|
||||
/// The Script Console: the lines of this session's runs, oldest first.
|
||||
pub fn script_console(&self) -> &console::Console {
|
||||
&self.script_console
|
||||
}
|
||||
|
||||
/// Empties the Script Console and sets its counts to zero. The last run's report, and the
|
||||
/// report of a running script, keep their lines. → the lines removed.
|
||||
pub fn clear_script_console(&mut self) -> usize {
|
||||
let n = self.script_console.lines().len();
|
||||
self.script_console.clear();
|
||||
n
|
||||
}
|
||||
|
||||
/// The error text of the last run when it failed: its name, place, message and kind, and the
|
||||
/// files it left written.
|
||||
pub fn script_failure_text(&self) -> Option<String> {
|
||||
@@ -885,6 +1250,32 @@ 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 time left of the running script's `$.sleep`, or none when it is not asleep. A run asked
|
||||
/// to stop is not asleep: the next [`Session::script_pump`] ends it.
|
||||
pub fn script_sleep_left(&self) -> Option<std::time::Duration> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.asleep())).flatten()
|
||||
}
|
||||
|
||||
/// 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()))
|
||||
@@ -917,12 +1308,8 @@ impl Session {
|
||||
/// ([`Self::script_report`]). False with none running.
|
||||
pub fn script_abandon(&mut self) -> bool {
|
||||
let Some(key) = self.script_key.take() else { return false };
|
||||
let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else {
|
||||
drop(key);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
|
||||
self.script_gone(key, console::Ending::Stopped);
|
||||
return true;
|
||||
};
|
||||
drop(key);
|
||||
@@ -932,6 +1319,19 @@ impl Session {
|
||||
true
|
||||
}
|
||||
|
||||
/// Ends the run whose job is no longer held: its console entry ends with `ending`, with no
|
||||
/// report line, since its time and host calls went with the job, and the session's state is
|
||||
/// put back as at the end of any run.
|
||||
fn script_gone(&mut self, key: JobKey, ending: console::Ending) {
|
||||
let line = console::ConsoleLine { run: key.run, name: key.name.clone(), entry: console::Entry::End(ending) };
|
||||
self.script_console.push(line, false);
|
||||
drop(key);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
}
|
||||
|
||||
/// A script can't start while a document holds a drag in progress or an undo group, which its
|
||||
/// one undo step could not take in.
|
||||
fn settle_for_script(&mut self) -> Result<()> {
|
||||
@@ -945,8 +1345,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() {
|
||||
@@ -957,11 +1357,19 @@ 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 strict = options.strict;
|
||||
let mut realm = Realm::with_options(options, limits);
|
||||
realm.share_interrupt(&self.script_stop);
|
||||
realm.set_data_limits(DataLimits::default());
|
||||
self.script_runs += 1;
|
||||
let host = Rc::new(Host {
|
||||
session: Rc::new(RefCell::new(Session::new())),
|
||||
pause: realm.pause_flag(),
|
||||
@@ -978,36 +1386,81 @@ impl Session {
|
||||
log: RefCell::new(Vec::new()),
|
||||
log_bytes: Cell::new(0),
|
||||
written: RefCell::new(Vec::new()),
|
||||
run: self.script_runs,
|
||||
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_failures: RefCell::default(),
|
||||
started: clock(),
|
||||
wake_at: Cell::new(None),
|
||||
can_wait: realm.wait_flag(),
|
||||
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 started = realm.define_host_object("vc", vc_object(&host, args)).and_then(|()| realm.start(&request.source));
|
||||
if let Err(e) = started {
|
||||
let report = failure_report(&request.name, &e, &request.source, &host, 0);
|
||||
let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry: console::Entry::Start };
|
||||
self.script_console.push(line, false);
|
||||
let info = dollar::RunInfo { locale: request.locale, strict };
|
||||
let localization = realm.localization();
|
||||
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
|
||||
.add_script_extensions()
|
||||
.and_then(|()| realm.define_host_object("vc", vc_object(&host, args)))
|
||||
.and_then(|()| realm.define_host_object("$", dollar_object(&host, info, &localization)))
|
||||
.and_then(|()| dialogs::install(&mut realm, &host))
|
||||
.and_then(|()| realm.start(&expanded.source))
|
||||
.map_err(|e| located(&host, realm.error_source(), realm.error_mark(), &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 (run, line_name) = (host.run, host.name.clone());
|
||||
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(())
|
||||
self.script_key = Some(JobKey { id, run, name: line_name });
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Advances the running script by one slice. `None` while it is still running; otherwise the
|
||||
/// run has ended: its report, or the error that ended it, with the documents put back.
|
||||
pub fn script_pump(&mut self) -> Option<Result<Value>> {
|
||||
let key = self.script_key.take()?;
|
||||
let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else {
|
||||
let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
|
||||
self.script_gone(key, console::Ending::Internal);
|
||||
return Some(Err(EngineError::Other(JOB_GONE.to_string())));
|
||||
};
|
||||
if job.host.waiting.get() && !self.script_stop.is_set() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job));
|
||||
if let Some(e) = job.host.dialogs.take_failure() {
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, 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();
|
||||
}
|
||||
@@ -1020,10 +1473,16 @@ impl Session {
|
||||
}
|
||||
Ok(Err(e)) => Some(self.script_failed(job, &e)),
|
||||
Ok(Ok(Progress::Paused)) => {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job));
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
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();
|
||||
@@ -1033,7 +1492,11 @@ impl Session {
|
||||
}
|
||||
|
||||
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
|
||||
let report = failure_report(&job.name, e, "", &job.host, job.realm.fuel_left());
|
||||
job.host.dialogs.stopped();
|
||||
let fuel_left = job.realm.fuel_left();
|
||||
let (e, file) = located(&job.host, job.realm.error_source(), job.realm.error_mark(), 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);
|
||||
self.script_stop.clear();
|
||||
@@ -1106,7 +1569,7 @@ impl Session {
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
let host = &job.host;
|
||||
let report = json!({
|
||||
let mut report = json!({
|
||||
"ok": true,
|
||||
"name": job.name,
|
||||
"changed": changed_names,
|
||||
@@ -1115,6 +1578,7 @@ impl Session {
|
||||
"fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(),
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
self.script_report = Some(report.clone());
|
||||
Ok(report)
|
||||
}
|
||||
@@ -1125,9 +1589,14 @@ 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();
|
||||
}
|
||||
// A `$.sleep` waits here, where nothing is drawn, instead of turning the loop over.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(left) = self.script_sleep_left() {
|
||||
std::thread::sleep(left.min(std::time::Duration::from_millis(100)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1145,27 +1614,100 @@ 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) -> 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,
|
||||
"written": *host.written.borrow(),
|
||||
"log": *host.log.borrow(),
|
||||
"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.
|
||||
fn ending(kind: &RunErrorKind) -> console::Ending {
|
||||
match kind {
|
||||
RunErrorKind::Syntax | RunErrorKind::Thrown => console::Ending::Error,
|
||||
RunErrorKind::Limit(LimitKind::Fuel) => console::Ending::Fuel,
|
||||
RunErrorKind::Limit(LimitKind::Host) => console::Ending::HostLimit,
|
||||
RunErrorKind::Limit(LimitKind::Interrupted) => console::Ending::Stopped,
|
||||
RunErrorKind::Limit(_) => console::Ending::Limit,
|
||||
RunErrorKind::Internal => console::Ending::Internal,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a line of `host`'s run to the session's console and to the run's own.
|
||||
fn line_to(s: &mut Session, host: &Host, entry: console::Entry, cut: bool) {
|
||||
let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry };
|
||||
s.script_console.push(line.clone(), cut);
|
||||
host.console.borrow_mut().push(line, cut);
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// 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() {
|
||||
let mut last = None;
|
||||
pending.end_line(|line, cut| last = Some((line, cut)));
|
||||
if let Some((line, cut)) = last {
|
||||
line_to(s, host, console::Entry::Output(line), cut);
|
||||
}
|
||||
}
|
||||
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 = 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();
|
||||
let ms = millis(host.run_nanos.get());
|
||||
let slow = slowest(&host.commands.borrow());
|
||||
let slow_json: Vec<Value> = slow.iter().map(|c| json!({"id": c.id, "calls": c.calls, "totalMs": c.total_ms, "maxMs": c.max_ms})).collect();
|
||||
let line = |entry| console::ConsoleLine { run: host.run, name: host.name.clone(), entry };
|
||||
s.script_console.push(line(console::Entry::End(ending)), false);
|
||||
let summary = console::Entry::Report { ms: timing.then_some(ms), host_calls: host.calls.get(), slowest: slow };
|
||||
s.script_console.push(line(summary), false);
|
||||
if let Some(o) = report.as_object_mut() {
|
||||
o.insert("runTimeMs".into(), json!(if timing { ms } else { 0 }));
|
||||
o.insert("timingAvailable".into(), json!(timing));
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a failed run's error.
|
||||
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();
|
||||
@@ -1187,6 +1729,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
let scope = job.scope.clone();
|
||||
let realm = &mut job.realm;
|
||||
let started = clock();
|
||||
let r = scope.run(|| {
|
||||
guard::catch_panic(|| {
|
||||
#[cfg(test)]
|
||||
@@ -1196,6 +1739,9 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
realm.advance(SLICE_FUEL)
|
||||
})
|
||||
});
|
||||
if let Some(started) = started {
|
||||
job.host.run_nanos.set(job.host.run_nanos.get().saturating_add(started.elapsed().as_nanos()));
|
||||
}
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
s.script_in_run = false;
|
||||
job.world.swap(s);
|
||||
@@ -1203,6 +1749,13 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
r
|
||||
}
|
||||
|
||||
/// Tests: removes the session's running job while the session keeps its hold on it. → whether a
|
||||
/// job was removed.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn forget_job(s: &Session) -> bool {
|
||||
s.script_key.as_ref().is_some_and(|k| JOBS.with(|jobs| jobs.borrow_mut().remove(&k.id)).is_some())
|
||||
}
|
||||
|
||||
/// The objects a run may add before it is asked to continue or stop.
|
||||
fn growth_objects() -> u64 {
|
||||
#[cfg(test)]
|
||||
@@ -1229,4 +1782,10 @@ 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) };
|
||||
/// Tests: the time since a run started, in place of its clock's.
|
||||
pub(crate) static TEST_ELAPSED: Cell<Option<std::time::Duration>> = const { Cell::new(None) };
|
||||
/// Tests: runs have no clock, as in a wasm build.
|
||||
pub(crate) static TEST_NO_CLOCK: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
@@ -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,
|
||||
@@ -135,6 +136,8 @@ impl Session {
|
||||
script_key: None,
|
||||
script_stop: vectorcraft_js::Interrupt::new(),
|
||||
script_report: None,
|
||||
script_console: Default::default(),
|
||||
script_runs: 0,
|
||||
script_frames: false,
|
||||
script_high_water: Default::default(),
|
||||
script_in_run: false,
|
||||
|
||||
@@ -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));
|
||||
|
||||
Loaded 100 of 312 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user