diff --git a/Cargo.lock b/Cargo.lock index b77485ae02..74b6189119 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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]] diff --git a/Cargo.toml b/Cargo.toml index 9b4b99c92d..2d53acdc39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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 diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 57b3d41224..fab468c391 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -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); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index b97ee681fe..bb94bad1cc 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -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); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 063d9b1aa1..96e09f5e78 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -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) { diff --git a/crates/doc/src/artboard.rs b/crates/doc/src/artboard.rs index d7bfcafca5..ac5db48c76 100644 --- a/crates/doc/src/artboard.rs +++ b/crates/doc/src/artboard.rs @@ -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, + /// 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, +} + +/// 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, D::Error> { + Ok(Option::::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 diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 5ca27311eb..89df899743 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -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, b: Option, vertex: Option, + /// 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, + /// The second point when it is not an anchor. + #[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")] + free_b: Option, }, } @@ -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 { + let mut first: Option = 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, 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, + #[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 + 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 + 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 { + 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 { + 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 { + 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 { + 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 { + 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::() - 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 { + 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, + /// 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) } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 2a2f8a8d7a..fecdc9bacb 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -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(); diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 15f04ce156..f3b655d76a 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -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, #[serde(skip_serializing_if = "Option::is_none")] pub legend: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub values_para: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub categories_para: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub legend_para: Option, + /// 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, + /// 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, + /// 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, } 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::>().join(",")); + let line = r.iter().map(|v| v.map(|v| v.to_string()).unwrap_or_default()).collect::>().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 diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 14bda9a00b..3412a7ff40 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -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, diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index cb5b19d1a4..2c0a6984d0 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -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] diff --git a/crates/doc/src/inks.rs b/crates/doc/src/inks.rs index 696b274134..e10c424ee9 100644 --- a/crates/doc/src/inks.rs +++ b/crates/doc/src/inks.rs @@ -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"); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5735d9b480..1f555b74e3 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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, + /// 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")] diff --git a/crates/doc/src/node/ids.rs b/crates/doc/src/node/ids.rs index 9e09a47a95..58915eb663 100644 --- a/crates/doc/src/node/ids.rs +++ b/crates/doc/src/node/ids.rs @@ -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 { + 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)?])) + } } diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index f769572588..eb7e0d39b9 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -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)) { diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index 90424d5bc2..f64bdb4300 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -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 { ] } +/// Status Effects: buffs and debuffs for RPG/gamedev art (original, catalogue stylize effects only). +fn status_effects() -> Vec { + 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] diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 4b75b01497..21fe8d7ce9 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -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::(v).unwrap(), a); + let read = |label: serde_json::Value| { + let mut v = plain.clone(); + v["guide_label"] = label; + serde_json::from_value::(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::(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(); diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 67ccb60a44..fd828c79af 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -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, - /// 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, /// Use glyph shapes for automatic pair spacing; false uses font metrics. diff --git a/crates/effects/src/adjust.rs b/crates/effects/src/adjust.rs index a656f11e85..c345136255 100644 --- a/crates/effects/src/adjust.rs +++ b/crates/effects/src/adjust.rs @@ -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 { +/// `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) -> Option { 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 } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index afe256e596..be3e99522f 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -112,7 +112,7 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { } // 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 { 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; diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 85248e08cf..a2e5478b28 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -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, } 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 { diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index d04982d98a..73d7266c31 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -209,7 +209,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, 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, 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 { } 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) { diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 5c06fae8fc..7785aff335 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -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) } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index f6c5cf2aea..0bdc134625 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -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 { +/// 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, +) -> Option { 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, ) -> Option { 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 = (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 = 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::>()) .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)); diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index a5004ab996..43b339ccf4 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -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::(); - let Paint::Gradient(g) = paint else { return own }; - let freeform = g - .freeform - .as_ref() - .map_or(0, |f| f.points.len() * size_of::() + f.lines.iter().map(|l| l.len() * size_of::()).sum::()); - own + size_of::() + g.gradient.stops.len() * size_of::() + freeform + let name = |s: &Option| 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::() + + f.lines.len() * size_of::>() + + f.lines.iter().map(|l| l.len() * size_of::()).sum::() + }); + let stops: usize = g.gradient.stops.iter().map(|s| size_of::() + name(&s.swatch)).sum(); + own + size_of::() + 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 { /// 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)>, level: usize) -> Vec> { - fn close(id: NodeId, run: &mut Vec<(&[Scope], Arc)>, scope: Option, level: usize, out: &mut Vec>) { +/// 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)>, level: usize) -> Vec> { + fn close(id: NodeId, run: &mut Vec<(&[Scope], Arc)>, scope: Option<&Scope>, level: usize, out: &mut Vec>) { 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; } diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 4ac4628b17..3c433d3445 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -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>, +} + +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 { + 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>) -> 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)>) -> Vec> { + let masks: Vec<(Vec, Arc)> = 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, 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>, Rect) { + let parts: Vec = 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>> { 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>> 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>> 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, Node)> = solids + let surfaces: Vec<(Vec, Node, &[Scope])> = solids .into_iter() - .map(|(item, member, f)| { + .map(|(item, member, scopes, f)| { let depths: Vec = 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())), diff --git a/crates/effects/src/solids/source.rs b/crates/effects/src/solids/source.rs index c5f664c686..ad9495cf08 100644 --- a/crates/effects/src/solids/source.rs +++ b/crates/effects/src/solids/source.rs @@ -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, Node)>, level: usize) -> Vec> { let mut out = vec![]; let mut run: Vec<(Vec, Node)> = vec![]; - let mut key = None; + let mut key: Option = None; let close = |run: &mut Vec<(Vec, Node)>, scope: Option, out: &mut Vec>| { 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) - 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>) -> 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 } diff --git a/crates/effects/src/solids/tests_sources.rs b/crates/effects/src/solids/tests_sources.rs index 4957f88fa4..2973b7113b 100644 --- a/crates/effects/src/solids/tests_sources.rs +++ b/crates/effects/src/solids/tests_sources.rs @@ -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(); diff --git a/crates/effects/src/stroke/dash.rs b/crates/effects/src/stroke/dash.rs index f660a6c8f7..400f3b58b9 100644 --- a/crates/effects/src/stroke/dash.rs +++ b/crates/effects/src/stroke/dash.rs @@ -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::() * 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::() > 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 diff --git a/crates/effects/src/stroke/tests_fit.rs b/crates/effects/src/stroke/tests_fit.rs index 91933087d4..b427fdbce7 100644 --- a/crates/effects/src/stroke/tests_fit.rs +++ b/crates/effects/src/stroke/tests_fit.rs @@ -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()); +} diff --git a/crates/effects/src/svg_filter.rs b/crates/effects/src/svg_filter.rs index 325ce9b38a..3877a60ae9 100644 --- a/crates/effects/src/svg_filter.rs +++ b/crates/effects/src/svg_filter.rs @@ -1101,8 +1101,9 @@ pub fn with_id(xml: &str, id: &str) -> Option { 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..)?)) } diff --git a/crates/effects/src/trap.rs b/crates/effects/src/trap.rs index f60232bedd..b2721ed0ff 100644 --- a/crates/effects/src/trap.rs +++ b/crates/effects/src/trap.rs @@ -218,34 +218,66 @@ fn visible(sources: &[TrapSource]) -> Vec { /// 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], 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], reach_x: f64, reach_y: f64) -> Option> { + near_pairs_within(rects, reach_x, reach_y, MAX_NEAR_SCAN) +} + +fn near_pairs_within(rects: &[Option], reach_x: f64, reach_y: f64, max_scan: usize) -> Option> { 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 { + 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> { let colors: Vec> = 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 { 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 { 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> = (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> = 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> = [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)); diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 73b21356b0..6e6abfaa48 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -544,7 +544,11 @@ fn merge(chain: &[&Piece]) -> std::result::Result { 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); } diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs index c75446b106..27d0233bb6 100644 --- a/crates/engine/src/cmd/addons/cleanup/text/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -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. diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 5d0e5723ff..9ddcc43559 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -774,8 +774,9 @@ fn divide_dashes(s: &mut Session, p: &Value) -> Result { 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 { fn expand_dashes(s: &mut Session, p: &Value) -> Result { 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. diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 45b23a0cb1..024358adfe 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -939,7 +939,10 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { 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 { // 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() diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index a5ff58ddf8..b58af91ff8 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -496,7 +496,7 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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 = 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); diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 13b6ab8814..85c1412f0c 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -208,7 +208,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 60353921e4..4c5cd89edf 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -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> { +fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result> { 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 Result { 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::>()) })?; Ok(json!({ "ids": ids_json(&out) })) } diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 4488b4746f..534e0ec89f 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -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) { + 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) { + 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>, + /// 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, /// 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 { 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 { 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> { + 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 = 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 = 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 { +/// 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> { 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::>()); - 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 = 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 diff --git a/crates/engine/src/cmd/compositefonts/tests.rs b/crates/engine/src/cmd/compositefonts/tests.rs index f51f066dfe..7997ca8f64 100644 --- a/crates/engine/src/cmd/compositefonts/tests.rs +++ b/crates/engine/src/cmd/compositefonts/tests.rs @@ -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] diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index f39aba2b12..e1b88d5d9f 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -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 { "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 { "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 { } 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> { + 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, dim: Dimension) -> Result { 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 { 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 { fn replace(doc: &mut Document, id: NodeId, dim: Dimension) -> Result<()> { let old: Vec = 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 { 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 ended } -/// The dimensions in `ended` whose art is as it was are live again. -pub(crate) fn restore_unchanged(doc: &mut Document, ended: Vec) { +/// 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) { 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 { + 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, + index: usize, + node: Arc, + assets: Vec<(usize, vectorcraft_doc::assets::ExportAsset)>, + bindings: Vec<(NodeId, std::collections::BTreeSet)>, +} + +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 { + 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) { + 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 = 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 { @@ -271,17 +455,27 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result { 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 (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 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(); diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 8c35254494..62b72a8e0f 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -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) -> std::borrow::Cow<'a, Document> { + let mut g = grid_of(d); + let loose: Vec = 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::>() }) } @@ -285,9 +301,11 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result { 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 { 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) = diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 024ba535b4..3558f1b569 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -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 = boards diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 8bf5c9a3d7..89d4f5011c 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -87,7 +87,7 @@ pub fn specs() -> Vec { "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 { 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, 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, 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 { + 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 { + 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) -> 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 { + 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> = 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::>()) } @@ -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 { // 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 { 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))?; diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 546b5a8258..ffb58d9d4b 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -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 { "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 { "{} 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 { /// (#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 { 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 = 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 { 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 = 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::>() })) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index caa08cfda2..74d9185ea3 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -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. diff --git a/crates/engine/src/cmd/fileio/affinity/document.rs b/crates/engine/src/cmd/fileio/affinity/document.rs index e87e9ac0f0..9114e9a40f 100644 --- a/crates/engine/src/cmd/fileio/affinity/document.rs +++ b/crates/engine/src/cmd/fileio/affinity/document.rs @@ -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() { diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 60f8be3297..dec69c9eee 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -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)?; } diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1108d3e2ca..84188c313a 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -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 } diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 9bf7a311a0..a197363b23 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -270,7 +270,9 @@ fn flattened(src: &Document, at: usize, id: NodeId) -> Result> { 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); } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index fd40139cfe..9b3223829f 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -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 // 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 // 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, opts: &LoadOptions, as_template: bool) -> Result { - 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 = warnings diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index e0acc2d52d..ccafc96e5e 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "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 searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{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: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", 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> { +/// 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, 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: diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 6cc93ede1b..9f4e5b0572 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1051,7 +1051,7 @@ fn can_revert(s: &Session) -> std::result::Result<(), String> { fn revert(s: &mut Session, _: &Value) -> Result { 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; diff --git a/crates/engine/src/cmd/fileio/tests_eps.rs b/crates/engine/src/cmd/fileio/tests_eps.rs index af918d33ee..8e2c1d429a 100644 --- a/crates/engine/src/cmd/fileio/tests_eps.rs +++ b/crates/engine/src/cmd/fileio/tests_eps.rs @@ -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); diff --git a/crates/engine/src/cmd/fileio/tests_pdfx.rs b/crates/engine/src/cmd/fileio/tests_pdfx.rs index abd1bbe4a3..68df66bd93 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfx.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfx.rs @@ -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, 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) { + 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:#?}"); +} diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index 2a12eb9c5e..f950f8c1da 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -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}; diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index c70f4dca6c..409db3f1b2 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -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 = 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 = art.iter().map(|n| sc.plain(n)).collect(); - let reaches: Vec> = plain.iter().map(reach).collect(); + // Each object as its clip groups and clipping layers show it. + let clipped: Vec = plain.iter().zip(roots).map(|(n, id)| clipped_by_ancestors(src, *id, n, None)).collect(); + let reaches: Vec> = plain.iter().zip(&clipped).map(|(n, c)| reach(n).zip(reach(c)).map(|(a, b)| a.intersect(b))).collect(); let see_through: Vec = 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 = 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 { + 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 = 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::>(), 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, Vec) = 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 = 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, 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 { + 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) -> 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 { + 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, Vec)> { + if !clips_count() || g.len() < 2 { + return None; + } + let ids: Vec = 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, Vec) = 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)> { @@ -163,8 +347,10 @@ fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Reg let mut complex: Vec = 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(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 = 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(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 { @@ -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, o: &FlattenOptions) -> Result { 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::>()); 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 { + 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> = roots.iter().map(|r| clip_ancestors(d, *r)).collect(); + let above = all.last().map_or(&[][..], Vec::as_slice); + let shared = |mine: &Vec| mine.iter().all(|c| all.iter().all(|theirs| theirs.contains(c))); + let leaves_fill = |mine: &Vec| 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"); diff --git a/crates/engine/src/cmd/flatten/commands.rs b/crates/engine/src/cmd/flatten/commands.rs index a2edde1f0f..4053dcac78 100644 --- a/crates/engine/src/cmd/flatten/commands.rs +++ b/crates/engine/src/cmd/flatten/commands.rs @@ -10,7 +10,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/flatten/compose.rs b/crates/engine/src/cmd/flatten/compose.rs index 0598905348..fef23f86ae 100644 --- a/crates/engine/src/cmd/flatten/compose.rs +++ b/crates/engine/src/cmd/flatten/compose.rs @@ -53,6 +53,11 @@ enum Body { pub(super) struct Builder { pub(super) shapes: Vec, pub(super) kinds: Vec, + /// 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>, + /// The clipping path of the clip group being built. + pub(super) clip: Option, /// 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 { 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 { .. } => { diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 8c838d421b..f4b6c90c13 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -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)] diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 3e21223497..f4eb3ef83c 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -50,6 +50,10 @@ pub(super) fn parse_csv(csv: &str) -> (Vec, Vec, Vec 1 { tabs } else { split_unquoted(l, ',') }; parts.into_iter().map(cell).collect() diff --git a/crates/engine/src/cmd/graph/generate.rs b/crates/engine/src/cmd/graph/generate.rs index d1a5ddde06..a789304b24 100644 --- a/crates/engine/src/cmd/graph/generate.rs +++ b/crates/engine/src/cmd/graph/generate.rs @@ -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 { 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> { - 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![vec![]]; + let mut rows: Vec> = 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)); } diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index fdd640a954..b115714256 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -10,7 +10,7 @@ use super::{ pub(super) struct Gen<'a> { pub(super) d: &'a mut Document, pub(super) out: Vec>, - /// 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 { + 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 { 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 = 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 { 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 { 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 { 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). diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 7d7d75a161..229a4d4b42 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -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 { 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 { + 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> { diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 650a4275ab..efcd043208 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -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::>(), 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:?}"); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 25201db87e..07571ad320 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "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 { "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 Result>> { + 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> { @@ -898,6 +914,7 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result { 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 { 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>, + guide_label: Option>, lock: Option, center_mark: Option, cross_hairs: Option, @@ -1013,6 +1032,23 @@ struct ArtboardEdit<'a> { art: Vec, } +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 { // 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 { 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 { 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 { 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 { 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; } diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 48e2d17938..a6d2cbf518 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -1303,7 +1303,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { 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 { 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 }); diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 0a4c93dc5e..8ea016db65 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -115,7 +115,7 @@ pub fn specs() -> Vec { "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 { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); converted.push(id); } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index d8f0681cc0..20dc187ab5 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -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 diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 04b1ce6857..9f50507aff 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "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 comma or full stop; no effect with kinsoku \"none\"), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), 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, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), 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, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{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, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), 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, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), 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, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment)", has_doc, set_format ), @@ -786,6 +786,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { } }; 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 { 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 { 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 { 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(()) })?; diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 2b529a84bb..d00ba7192c 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -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 { "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) -> Option { 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 = (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 { 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 { 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 = (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 { (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 { 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) { diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index a8306d25c7..3da73c0385 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -135,7 +135,7 @@ pub fn specs() -> Vec { "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 { } } -/// 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> { 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> { 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 { + s.trim().parse::().ok().filter(|v| v.is_finite()) +} + fn ids_json(ids: &[NodeId]) -> Value { json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) } @@ -703,7 +719,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result { /// 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 { - 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 { 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 { 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 { 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()); diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 3e15c563fe..011dfc131c 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -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> { /// 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 { 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 diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 7759a57f00..f7c7003b11 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -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", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index ef8b156b69..783ce0e919 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -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 { + 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 { "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 { + 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 { + 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, 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 { + 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 { let all = s.prefs.to_json(); match str_param(p, "key") { @@ -789,6 +896,7 @@ fn set(s: &mut Session, p: &Value) -> Result { 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 { 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(); diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 44de123fa9..76e09641f9 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/printadvanced.rs b/crates/engine/src/cmd/printadvanced.rs index d181541c3d..537658447b 100644 --- a/crates/engine/src/cmd/printadvanced.rs +++ b/crates/engine/src/cmd/printadvanced.rs @@ -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; } diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b8b5448817..493ba68db7 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "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 entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -45,6 +45,33 @@ pub fn specs() -> Vec { 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 { 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 { _ => 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 { Ok(json!({"stopped": s.script_request_stop()})) } +fn console_lines(s: &mut Session, _: &Value) -> Result { + Ok(s.script_console().to_json()) +} + +fn console_clear(s: &mut Session, _: &Value) -> Result { + 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 { + 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 { + 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 = 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, diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 0f16246dff..4ef1e6bc6a 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -252,6 +252,18 @@ pub(crate) fn selectable_ids(d: &Document, iso: Option) -> BTreeSet, 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, 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, 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, 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))) } } } diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index eaa5b8c545..fe2816ed16 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -753,7 +753,7 @@ fn add(s: &mut Session, p: &Value) -> Result { 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 => { diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index fe3f1149da..02767aef39 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -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 = sword.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let shield: Vec = shield.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let potion: Vec = potion.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let key: Vec = 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 { }; // 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 = 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 { 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); diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index b6d20999a0..79dcee7135 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -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 { @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "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>> { 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::>()?; 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 { } /// 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 { 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 { // 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 { } } 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, _| { diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 3fd8e8f231..89ec47b276 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -976,12 +976,12 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { } 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; diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 73c938dc1a..ab0c7d342e 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -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); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 2257b1a8ae..6d29550fa0 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -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 { @@ -249,16 +249,16 @@ fn ruby(s: &mut Session, p: &Value) -> Result { 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 { 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 = 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 { 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 { fn set_style(s: &mut Session, p: &Value) -> Result { 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 { 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); diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 77068d125f..8d0d2b8eee 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -94,6 +94,7 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[ "view.separationsPreview", "prefs.set", "prefs.reset", + "prefs.import", "text.addFontFiles", ]; diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index d0e4862404..08b8a2f294 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -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>, + /// 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, /// 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(), } } diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c6daff9e41..3f0a641e2e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -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, +} + +/// 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), 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::*; diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 14df8529d7..c474e25756 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -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), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 043158c582..091348a6bd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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, + /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder + /// ([`Session::attach_scripts_dir`]). + scripts_dir: Option, /// 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, + /// 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, diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 9ea86a21ea..aa8b5c7f42 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -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, diff --git a/crates/engine/src/script/console.rs b/crates/engine/src/script/console.rs new file mode 100644 index 0000000000..a0e3ee6d01 --- /dev/null +++ b/crates/engine/src/script/console.rs @@ -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, host_calls: u64, slowest: Vec }, +} + +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 = 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::(), + } + } +} + +/// 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, + pub entry: Entry, +} + +/// A bounded store of console lines. +#[derive(Clone, Debug, Default)] +pub struct Console { + lines: VecDeque, + 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 { + &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 = 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 = + 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 { + 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) + } +} diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs new file mode 100644 index 0000000000..1faf624f16 --- /dev/null +++ b/crates/engine/src/script/dialogs.rs @@ -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, + /// `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), +} + +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, 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 { + 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>, + answers: RefCell>, + waiting: RefCell>, + /// The error that ended the run when an answer could not reach the script. + failed: RefCell>, + records: RefCell>, + record_bytes: Cell, + count: Cell, + truncated: Cell, +} + +impl Dialogs { + pub(crate) fn new(framed: bool, realm: &Realm, answers: Vec) -> 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 { + 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 { + 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) { + 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) -> 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 { + 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 { + 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"))) + } + } +} diff --git a/crates/engine/src/script/dollar.rs b/crates/engine/src/script/dollar.rs new file mode 100644 index 0000000000..3e6b005844 --- /dev/null +++ b/crates/engine/src/script/dollar.rs @@ -0,0 +1,307 @@ +//! The members of a script's `$` object besides `$.write`, `$.writeln`, `$.evalFile`, `$.fileName` +//! and `$.includePath`, from the Dollar object +//! page (), and +//! the locale the global `localize` reads +//! (). +//! +//! 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 { + 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)> { + 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 { + 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) -> Data { + Data::String(s.into()) +} + +/// The members `$` has besides `write`, `writeln`, `evalFile`, `fileName` and `includePath`. +pub(super) fn members(host: &Rc, info: RunInfo, localization: &Rc) -> 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 Data>| HostItem::Getter(function(move |_| Ok(f()))); + let property = |get: Rc Data>, set: Rc 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"; diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs new file mode 100644 index 0000000000..d071195df6 --- /dev/null +++ b/crates/engine/src/script/folder.rs @@ -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 }, +} + +/// 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, + /// 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> { + let mut found: Vec = 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::::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> = 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> { + 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) +} diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs new file mode 100644 index 0000000000..70bfeac56a --- /dev/null +++ b/crates/engine/src/script/include.rs @@ -0,0 +1,442 @@ +//! A script's preprocessor lines, read before it runs, as the public guide lists them +//! (): +//! `#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` (: +//! 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>, + segments: Vec, +} + +/// 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, 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, + 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, + pub strict: Option, +} + +/// 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, + dir: Option, +} + +/// 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, + include_path: Vec, + files: usize, + bytes: usize, + probes: usize, + /// The real paths of the files open now, for cycles. + chain: Vec, + /// How many of them are below the script. + levels: usize, + /// The files `$.evalFile` is running, the script first. + frames: Vec, +} + +/// 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, + line: u32, + column: u32, + after_cr: bool, + map: SourceMap, + strict: Option, +} + +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 { + 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 { + 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 { + 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) -> 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 { + #[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 { + 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 { + 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, value: &str) -> Result { + 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), (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, 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, dir: Option, text: &str, script: bool) -> Result { + 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, + dir: Option<&Path>, + text: &str, + script: bool, + name: &mut Option, + ) -> Result<(), Failure> { + let index = out.map.files.len(); + out.map.files.push(shown.clone()); + let units: Vec = 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(()) + } +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 9d0a47fbff..213cff53fd 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -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, pub source: String, pub args: Map, 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, } 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, +} 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(key: &JobKey, f: impl FnOnce(&mut Job) -> T) -> Option { - 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>, log_bytes: Cell, written: RefCell>, + /// The run's number in its session, and the script's name, which its console lines carry. + run: u64, + name: Arc, + /// The run's own output and error, for its report. + console: RefCell, + /// The line `$.write` has not ended yet. + pending: RefCell, + counts: Counts, + /// Each command `vc.run` ran: its calls, its total time and its longest call, in nanoseconds. + commands: RefCell>, + /// The time the run's slices took, in nanoseconds. + run_nanos: Cell, + /// `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, + /// Where the lines of the script's expanded source came from. + script_map: RefCell, + /// The same for each source `$.evalFile` gave, in order. + eval_maps: RefCell>, + /// 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, u32, u32)>>, + /// When the run started, where the platform has a clock. + started: Option, + /// The time since [`Host::started`] at which a `$.sleep` ends. + wake_at: Cell>, + /// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]). + can_wait: Rc>, + /// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one). + eval_strict: Cell>, +} + +/// A run's host calls by kind, as its report gives them in `hostCallCounts`. +#[derive(Default)] +struct Counts { + vc_run: Cell, + document_reads: Cell, + command_list_reads: Cell, + vc_log: Cell, + console_writes: Cell, +} + +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) { + c.set(c.get().saturating_add(1)); +} + +/// Now, where the platform has a clock (not in a wasm build). +fn clock() -> Option { + #[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 { + 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 { + #[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 { + 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, 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, args: Vec) -> std::result::Result 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) -> std::result::Result 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, info: dollar::RunInfo, localization: &Rc) -> 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) -> std::result::Result { + 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) -> std::result::Result + 'static) -> HostFunction { Rc::new(f) } @@ -795,6 +1097,7 @@ fn vc_object(host: &Rc, 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, 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, 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>) { + 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, e: &RunError) -> (RunError, Option>) { + 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 { @@ -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 { + 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 { + 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 { 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 { 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> { 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 { - 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 = 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::Result std::result::Result 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 = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; + /// Tests: the `JSINCLUDE` folders in place of the environment's. + pub(crate) static TEST_JSINCLUDE: RefCell>> = const { RefCell::new(None) }; + /// Tests: the time since a run started, in place of its clock's. + pub(crate) static TEST_ELAPSED: Cell> = const { Cell::new(None) }; + /// Tests: runs have no clock, as in a wasm build. + pub(crate) static TEST_NO_CLOCK: Cell = const { Cell::new(false) }; } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 54d84507c5..e34eb711bd 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -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, diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index f6fe8ff5bc..01ebc46526 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -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)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f6e32d719e..9c6de6a89e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -130,6 +130,7 @@ mod place; mod placed_document; mod plugins; mod prefs; +mod prefs_file; mod previewbounds; mod print; mod printadvanced; @@ -149,6 +150,11 @@ mod repeat_edit; mod save; mod saveoptions; mod scalestrokes; +mod script_console; +mod script_dialogs; +mod script_dollar; +mod script_folder; +mod script_include; mod script_run; mod scripts; mod select_ids_first; @@ -3243,7 +3249,7 @@ fn reshape_falloff_follows_arc_length_on_open_paths() { .as_u64() .unwrap(), ); - s.execute("path.reshape", &json!({"id": id.0, "x": 300.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 300.0, "y": 0.0, "dx": 0.0, "dy": 100.0, "radius": 250.0})).unwrap(); let pts: Vec<_> = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect(); assert!((pts[3].y - 100.0).abs() < 1e-6, "grabbed end moves full delta: {pts:?}"); assert!(pts[0].y.abs() < 1e-6, "far end stays put: {pts:?}"); @@ -3251,6 +3257,604 @@ fn reshape_falloff_follows_arc_length_on_open_paths() { assert!(pts[1].y < pts[2].y, "nearer anchors move more: {pts:?}"); } +/// An open path for the Reshape tests. +fn reshape_open_path(s: &mut Session, anchors: Value) -> NodeId { + NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].as_u64().unwrap()) +} + +/// The anchors of the path's first subpath. +fn reshape_anchors(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.clone() +} + +/// The share of the drag an anchor takes at `u` of the way from an end to the grabbed point. +fn reshape_share(u: f64) -> f64 { + u * u * (3.0 - 2.0 * u) +} + +/// Six anchors 100 apart along a zigzag 300 wide and 80 high. +fn reshape_zigzag() -> Value { + json!([{"x": 0, "y": 0}, {"x": 60, "y": 80}, {"x": 120, "y": 0}, {"x": 180, "y": 80}, {"x": 240, "y": 0}, {"x": 300, "y": 80}]) +} + +#[test] +fn reshape_of_an_end_stretches_an_open_path_to_its_other_end() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_zigzag()); + let before = reshape_anchors(&s, id); + s.execute("path.reshape", &json!({"id": id.0, "x": 300.0, "y": 80.0, "dx": 20.0, "dy": 50.0})).unwrap(); + let after = reshape_anchors(&s, id); + assert_eq!(after.len(), 6); + let moved: Vec = after.iter().zip(&before).map(|(a, b)| a.p - b.p).collect(); + assert_eq!(moved[0], vectorcraft_geom::Vec2::ZERO, "the other end stays in place: {moved:?}"); + for (i, m) in moved.iter().enumerate() { + let share = reshape_share(i as f64 / 5.0); + assert!((m.x - 20.0 * share).abs() < 1e-9 && (m.y - 50.0 * share).abs() < 1e-9, "anchor {i} takes {share} of the drag: {moved:?}"); + } + assert!(moved.windows(2).all(|w| w[0].y < w[1].y), "each anchor moves less than the one after it: {moved:?}"); + // The path has no handles, and gets none. + assert!(after.iter().all(|a| a.h_in == a.p && a.h_out == a.p), "{after:?}"); +} + +#[test] +fn reshape_of_a_middle_anchor_leaves_both_ends_of_an_open_path_in_place() { + let mut s = session(); + let id = reshape_open_path(&mut s, json!([{"x": 0, "y": 0}, {"x": 30, "y": 0}, {"x": 200, "y": 0}, {"x": 230, "y": 0}, {"x": 400, "y": 0}])); + s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!(y.len(), 5, "the grab was on an anchor, so none is added"); + assert_eq!((y[0], y[2], y[4]), (0.0, 100.0, 0.0), "{y:?}"); + // Each side is measured from its own end: 30 of 200 on the left, 170 of 200 on the right. + assert!((y[1] - 100.0 * reshape_share(0.15)).abs() < 1e-9, "{y:?}"); + assert!((y[3] - 100.0 * reshape_share(0.85)).abs() < 1e-9, "{y:?}"); +} + +#[test] +fn reshape_keeps_the_handles_of_a_smooth_anchor_in_line() { + let mut s = session(); + let id = reshape_open_path( + &mut s, + json!([ + {"x": 0, "y": 0, "out": [40, 0]}, + {"x": 100, "y": 0, "in": [60, 0], "out": [140, 0], "smooth": true}, + {"x": 200, "y": 0, "in": [160, 0]} + ]), + ); + s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + let a = reshape_anchors(&s, id); + // The control polygon is 200 long and the middle anchor is halfway: it takes half the drag, + // and its handles, 40 either side, take 0.2 and 0.8 of it. + assert!((a[1].p.y - 50.0).abs() < 1e-9 && (a[1].h_in.y - 20.0).abs() < 1e-9 && (a[1].h_out.y - 80.0).abs() < 1e-9, "{a:?}"); + let (to_in, to_out) = (a[1].h_in - a[1].p, a[1].h_out - a[1].p); + assert!(to_in.cross(to_out).abs() < 1e-9 && to_in.dot(to_out) < 0.0, "the handles stay opposite each other: {a:?}"); + // The end that stays keeps its handle, and the grabbed end's handle moves with it. + assert_eq!((a[0].p, a[0].h_out), (Point::new(0.0, 0.0), Point::new(40.0, 0.0))); + assert_eq!((a[2].p, a[2].h_in), (Point::new(200.0, 100.0), Point::new(160.0, 100.0))); +} + +/// A `radius` still bounds the reach on an open path, as it did before the path stretched to its ends. +#[test] +fn reshape_with_a_radius_moves_only_the_anchors_within_it() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_zigzag()); + s.execute("path.reshape", &json!({"id": id.0, "x": 300.0, "y": 80.0, "dx": 0.0, "dy": 50.0, "radius": 150.0})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!(&y[..4], &[0.0, 80.0, 0.0, 80.0], "anchors 200 or more along the path stay: {y:?}"); + assert!(y[4] > 0.0 && y[4] < 50.0 && y[5] == 130.0, "{y:?}"); +} + +#[test] +fn reshape_measures_an_open_path_along_its_control_polygon() { + let mut s = session(); + // The first segment's control polygon is 60 + 100 + 60 long, its chord 100 and its arc 150 to + // 160; the second segment is a line 100 long. + let id = reshape_open_path(&mut s, json!([{"x": 0, "y": 0, "out": [0, 60]}, {"x": 100, "y": 0, "in": [100, 60]}, {"x": 200, "y": 0}])); + s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + let a = reshape_anchors(&s, id); + let u: f64 = 220.0 / 320.0; + assert!((a[1].p.y - 100.0 * reshape_share(u)).abs() < 1e-9, "{a:?}"); + // The in handle lies 160 along the polygon, and takes the share on the tangent line at its anchor. + let handle = reshape_share(u) + 6.0 * u * (1.0 - u) * (160.0 / 320.0 - u); + assert!((a[1].h_in.y - 60.0 - 100.0 * handle).abs() < 1e-9, "{a:?}"); + // The end that stays keeps its handle. + assert_eq!((a[0].p, a[0].h_out), (Point::new(0.0, 0.0), Point::new(0.0, 60.0))); +} + +#[test] +fn reshape_of_a_point_on_a_segment_stretches_an_open_path_from_the_new_anchor() { + let mut s = session(); + let id = reshape_open_path(&mut s, json!([{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 200, "y": 0}, {"x": 300, "y": 0}])); + s.execute("path.reshape", &json!({"id": id.0, "x": 250.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + let p: Vec = reshape_anchors(&s, id).iter().map(|a| a.p).collect(); + assert_eq!(p.len(), 5, "the grab adds an anchor: {p:?}"); + assert_eq!((p[0], p[3], p[4]), (Point::new(0.0, 0.0), Point::new(250.0, 100.0), Point::new(300.0, 0.0)), "{p:?}"); + assert!((p[1].y - 100.0 * reshape_share(0.4)).abs() < 1e-9 && (p[2].y - 100.0 * reshape_share(0.8)).abs() < 1e-9, "{p:?}"); +} + +#[test] +fn reshape_of_an_end_of_a_two_anchor_path_moves_only_that_end() { + let mut s = session(); + let id = reshape_open_path(&mut s, json!([{"x": 0, "y": 0, "out": [30, 0]}, {"x": 100, "y": 0, "in": [70, 0]}])); + s.execute("path.reshape", &json!({"id": id.0, "x": 100.0, "y": 0.0, "dx": 10.0, "dy": 50.0})).unwrap(); + let a = reshape_anchors(&s, id); + assert_eq!((a[0].p, a[0].h_out), (Point::new(0.0, 0.0), Point::new(30.0, 0.0))); + assert_eq!((a[1].p, a[1].h_in), (Point::new(110.0, 50.0), Point::new(80.0, 50.0))); +} + +#[test] +fn reshape_keeps_smooth_anchors_on_both_sides_of_the_grabbed_one_in_line() { + let mut s = session(); + // Smooth anchors with handles of unequal length, on a curve, before and after the grabbed anchor. + let id = reshape_open_path( + &mut s, + json!([ + {"x": 0, "y": 0}, + {"x": 100, "y": 50, "in": [80, 40], "out": [160, 80], "smooth": true}, + {"x": 250, "y": 0, "in": [220, 0], "out": [290, 0], "smooth": true}, + {"x": 400, "y": 60, "in": [340, 90], "out": [420, 50], "smooth": true}, + {"x": 500, "y": 0} + ]), + ); + let before = reshape_anchors(&s, id); + s.execute("path.reshape", &json!({"id": id.0, "x": 250.0, "y": 0.0, "dx": 35.0, "dy": -80.0})).unwrap(); + let a = reshape_anchors(&s, id); + let drag = vectorcraft_geom::Vec2::new(35.0, -80.0); + assert_eq!((a[2].p - before[2].p, a[2].h_in - before[2].h_in, a[2].h_out - before[2].h_out), (drag, drag, drag)); + for i in [1, 3] { + let (to_in, to_out) = (a[i].h_in - a[i].p, a[i].h_out - a[i].p); + assert!(to_in.cross(to_out).abs() < 1e-9 && to_in.dot(to_out) < 0.0, "anchor {i}'s handles stay opposite each other: {a:?}"); + let moved = a[i].p - before[i].p; + assert!( + moved.cross(drag).abs() < 1e-9 && moved.hypot() > 1.0 && moved.hypot() < drag.hypot() - 1.0, + "anchor {i} takes part of the drag: {a:?}" + ); + // The handle on the grabbed anchor's side moves farther than its anchor, and the other one less. + let (h_in, h_out) = ((a[i].h_in - before[i].h_in).hypot(), (a[i].h_out - before[i].h_out).hypot()); + let (nearer, farther) = if i == 1 { (h_out, h_in) } else { (h_in, h_out) }; + assert!(nearer > moved.hypot() + 1.0 && farther < moved.hypot() - 1.0, "anchor {i}: {a:?}"); + } + assert_eq!((a[0].p, a[4].p), (before[0].p, before[4].p)); +} + +#[test] +fn reshape_moves_a_long_handle_against_the_drag_to_keep_its_anchor_smooth() { + let mut s = session(); + let id = + reshape_open_path(&mut s, json!([{"x": 0, "y": 0}, {"x": 100, "y": 0, "in": [10, 0], "out": [190, 0], "smooth": true}, {"x": 400, "y": 0}])); + s.execute("path.reshape", &json!({"id": id.0, "x": 400.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + let a = reshape_anchors(&s, id); + // The anchor is a quarter of the way along and takes 0.15625 of the drag. The tangent line + // there has slope 1.125, and each handle lies 0.225 of the way from the anchor: the in handle + // takes 0.15625 - 0.253125, a share below 0, and the out handle 0.15625 + 0.253125. + assert!((a[1].p.y - 15.625).abs() < 1e-9 && (a[1].h_in.y + 9.6875).abs() < 1e-9 && (a[1].h_out.y - 40.9375).abs() < 1e-9, "{a:?}"); + let (to_in, to_out) = (a[1].h_in - a[1].p, a[1].h_out - a[1].p); + assert!(to_in.cross(to_out).abs() < 1e-9 && to_in.dot(to_out) < 0.0, "the handles stay opposite each other: {a:?}"); +} + +#[test] +fn reshape_refuses_a_negative_radius() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_zigzag()); + let before = reshape_anchors(&s, id); + let steps = s.doc().unwrap().history.undo.len(); + let e = s.execute("path.reshape", &json!({"id": id.0, "x": 300.0, "y": 80.0, "dx": 0.0, "dy": 50.0, "radius": -50.0})).unwrap_err(); + assert!(e.to_string().contains("`radius` must be 0 or more"), "{e}"); + assert_eq!(reshape_anchors(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); +} + +#[test] +fn reshape_by_no_distance_on_an_anchor_records_no_undo_step() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_zigzag()); + let before = reshape_anchors(&s, id); + let steps = s.doc().unwrap().history.undo.len(); + for params in [json!({"id": id.0, "x": 300.0, "y": 80.0}), json!({"id": id.0, "x": 120.0, "y": 0.0, "dx": 0.0, "dy": 0.0, "radius": 40.0})] { + s.execute("path.reshape", ¶ms).unwrap(); + } + assert_eq!(reshape_anchors(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + // A drag that moves the anchor is still one step. + s.execute("path.reshape", &json!({"id": id.0, "x": 300.0, "y": 80.0, "dx": 0.0, "dy": 1.0})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); +} + +/// Seven anchors 70 apart along a line, from x 0 to x 420. +fn reshape_line_of_seven() -> Value { + json!([{"x": 0, "y": 0}, {"x": 70, "y": 0}, {"x": 140, "y": 0}, {"x": 210, "y": 0}, {"x": 280, "y": 0}, {"x": 350, "y": 0}, {"x": 420, "y": 0}]) +} + +#[test] +fn reshape_with_two_focal_points_moves_the_anchors_between_them_whole() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("path.reshape", &json!({"id": id.0, "x": 280.0, "y": 0.0, "dx": 0.0, "dy": 100.0, "focal": [[0, 2]]})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!(&y[2..5], &[100.0, 100.0, 100.0], "both focal points and the anchor between them: {y:?}"); + assert_eq!((y[0], y[6]), (0.0, 0.0), "the ends stay: {y:?}"); + // Each side stretches from its own end to its nearer focal point, 140 along the path. + assert!((y[1] - 100.0 * reshape_share(0.5)).abs() < 1e-9 && (y[5] - 100.0 * reshape_share(0.5)).abs() < 1e-9, "{y:?}"); +} + +#[test] +fn reshape_of_a_closed_path_selected_whole_moves_all_of_it() { + let mut s = session(); + let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let before = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().clone(); + s.execute("path.reshape", &json!({"id": r.0, "x": 0.0, "y": 0.0, "dx": 15.0, "dy": -40.0, "focal": []})).unwrap(); + let after = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().clone(); + assert_eq!(after.anchor_count(), before.anchor_count(), "a grab on an anchor adds none"); + let drag = vectorcraft_geom::Vec2::new(15.0, -40.0); + for ((_, _, a), (_, _, b)) in after.anchors().zip(before.anchors()) { + assert_eq!((a.p - b.p, a.h_in - b.h_in, a.h_out - b.h_out), (drag, drag, drag), "{after:?}"); + } +} + +#[test] +fn reshape_leaves_the_anchors_that_are_not_selected_in_place() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 350.0, "y": 0.0, "dx": 0.0, "dy": 100.0, "focal": []})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!((y[0], y[1], y[5], y[6]), (0.0, 0.0, 100.0, 0.0), "{y:?}"); + // The stretch runs from the last anchor that is not selected, 280 from the focal point. + for i in 2..5 { + let u = (i as f64 - 1.0) / 4.0; + assert!((y[i] - 100.0 * reshape_share(u)).abs() < 1e-9, "anchor {i} takes {u} of the way: {y:?}"); + } +} + +/// A step with neither `focal` nor `radius`, as one recorded before focal points, plays as it did +/// then: the selection does not matter, and a closed path follows with the default falloff. +#[test] +fn reshape_without_focal_or_radius_keeps_the_earlier_rule() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 350.0, "y": 0.0, "dx": 0.0, "dy": 100.0})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!((y[0], y[5], y[6]), (0.0, 100.0, 0.0), "{y:?}"); + // Anchor 1 is not selected and still takes its share, measured from the end 350 away. + for i in 1..5 { + let u = i as f64 / 5.0; + assert!((y[i] - 100.0 * reshape_share(u)).abs() < 1e-9, "anchor {i} takes {u} of the way: {y:?}"); + } + // `focal: null` is the same as leaving it out. + let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("path.reshape", &json!({"id": r.0, "x": 0.0, "y": 0.0, "dx": 0.0, "dy": -40.0, "focal": null})).unwrap(); + let pts: Vec = s.doc().unwrap().doc.node(r).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect(); + assert!(pts.contains(&Point::new(0.0, -40.0)), "{pts:?}"); + assert!(pts.contains(&Point::new(100.0, 100.0)), "the far corner stays: {pts:?}"); +} + +#[test] +fn reshape_of_a_partly_selected_closed_path_stretches_between_the_anchors_that_stay() { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 200, "y": 0}, {"x": 200, "y": 100}, {"x": 100, "y": 100}, {"x": 0, "y": 100}], "closed": true}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + // Anchors 5, 0, 1 and 2 are selected; 3 and 4 stay. The walk runs 4, 5, 0, 1, 2, 3. + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 5], [0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 0.0, "y": 0.0, "dx": 0.0, "dy": -50.0, "focal": []})).unwrap(); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!((y[0], y[3], y[4]), (-50.0, 100.0, 100.0), "{y:?}"); + // From anchor 4 to the focal point is 200: anchor 5 is halfway. From anchor 3 back to it is + // 300: anchor 2 is a third of the way and anchor 1 two thirds. + let want = [(5, 100.0 + -50.0 * reshape_share(0.5)), (2, -50.0 * reshape_share(1.0 / 3.0)), (1, -50.0 * reshape_share(2.0 / 3.0))]; + for (i, w) in want { + assert!((y[i] - w).abs() < 1e-9, "anchor {i}: {y:?}"); + } +} + +#[test] +fn reshape_of_a_segment_keeps_the_selected_anchors_and_selects_the_new_one() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3], [0, 4], [0, 5]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 245.0, "y": 0.0, "dx": 0.0, "dy": 60.0, "focal": [[0, 5]]})).unwrap(); + let a = reshape_anchors(&s, id); + assert_eq!(a.len(), 8, "the grab adds an anchor between 210 and 280"); + let selected: Vec<(usize, usize)> = s.doc().unwrap().selection.partial(id).unwrap().iter().copied().collect(); + assert_eq!(selected, vec![(0, 3), (0, 4), (0, 5), (0, 6)], "the same points stay selected, with the new one"); + // The focal point given before the anchor was added still names the anchor at 350. + let y: Vec = a.iter().map(|a| a.p.y).collect(); + assert_eq!(&y[4..7], &[60.0, 60.0, 60.0], "{y:?}"); + assert_eq!((y[0], y[1], y[2], y[7]), (0.0, 0.0, 0.0, 0.0), "{y:?}"); +} + +#[test] +fn reshape_of_a_segment_with_a_selected_anchor_index_past_the_end_does_not_panic() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + let past = usize::MAX; + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, past]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 175.0, "y": 0.0, "dx": 0.0, "dy": 10.0})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 105.0, "y": 0.0, "dx": 0.0, "dy": 10.0})).unwrap(); + assert_eq!(reshape_anchors(&s, id).len(), 9); +} + +#[test] +fn reshape_of_a_segment_keeps_a_selected_segment_as_its_two_halves() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 2], [0, 4]], "mode": "set"})).unwrap(); + s.execute("path.reshape", &json!({"id": id.0, "x": 175.0, "y": 0.0, "dx": 0.0, "dy": 0.0})).unwrap(); + let st = s.doc().unwrap(); + let segments: Vec<(usize, usize)> = st.selection.segments[&id].iter().copied().collect(); + assert_eq!(segments, vec![(0, 2), (0, 3), (0, 5)]); + let anchors: Vec<(usize, usize)> = st.selection.partial(id).unwrap().iter().copied().collect(); + assert_eq!(anchors, vec![(0, 2), (0, 3), (0, 4), (0, 5), (0, 6)], "the new anchor moves with the segment's ends"); +} + +#[test] +fn reshape_moves_only_the_subpaths_with_a_focal_point() { + let mut s = session(); + let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L100 0 L200 0 M0 100 L100 100 L200 100"})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 0.0, "dx": 0.0, "dy": 40.0, "focal": []})).unwrap(); + let pd = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone(); + let y: Vec> = pd.subpaths.iter().map(|sp| sp.anchors.iter().map(|a| a.p.y).collect()).collect(); + assert_eq!(y[1], vec![100.0, 100.0, 100.0], "{y:?}"); + assert_eq!((y[0][0], y[0][2]), (0.0, 40.0), "{y:?}"); + // A focal point on the other subpath stretches that one too. + s.execute("path.reshape", &json!({"id": id.0, "x": 200.0, "y": 40.0, "dx": 0.0, "dy": 10.0, "focal": [[1, 1]]})).unwrap(); + let pd = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone(); + assert_eq!(pd.subpaths[1].anchors.iter().map(|a| a.p.y).collect::>(), vec![100.0, 110.0, 100.0]); +} + +#[test] +fn reshape_refuses_a_focal_point_that_is_not_an_anchor() { + let mut s = session(); + let id = reshape_open_path(&mut s, reshape_line_of_seven()); + let before = reshape_anchors(&s, id); + for (focal, want) in [ + (json!([[0, 7]]), "`focal` names [0, 7], which is not an anchor of the path"), + (json!([[1, 0]]), "`focal` names [1, 0], which is not an anchor of the path"), + (json!([[0, -1]]), "invalid anchor index -1"), + (json!({"0": 1}), "`focal` must be an array of [subpath, anchor] pairs"), + ] { + let e = s.execute("path.reshape", &json!({"id": id.0, "x": 420.0, "y": 0.0, "dx": 0.0, "dy": 10.0, "focal": focal})).unwrap_err(); + assert!(e.to_string().contains(want), "{e}"); + } + assert_eq!(reshape_anchors(&s, id), before); + let steps = s.doc().unwrap().history.undo.len(); + // An empty `focal` chooses the focal-point rule too, so it cannot go with `radius` either. + for focal in [json!([[0, 2]]), json!([])] { + let e = + s.execute("path.reshape", &json!({"id": id.0, "x": 420.0, "y": 0.0, "dx": 0.0, "dy": 10.0, "focal": focal, "radius": 50.0})).unwrap_err(); + assert!(e.to_string().contains("`focal` and `radius` cannot be used together"), "{focal}: {e}"); + } + assert_eq!(reshape_anchors(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); +} + +/// The line of seven, selected whole, with the Reshape tool picked. +fn reshape_tool_on_a_line(s: &mut Session) -> NodeId { + let id = reshape_open_path(s, reshape_line_of_seven()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.select_tool("reshape", ViewInfo::default()).unwrap(); + id +} + +/// Presses at `a`, drags to `b` unless it is `a` (a click), and releases, with Shift when `shift`. +fn reshape_gesture(s: &mut Session, a: (f64, f64), b: (f64, f64), shift: bool) { + let v = ViewInfo::default(); + let mods = vectorcraft_tools::Mods { shift, ..vectorcraft_tools::Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, a.0, a.1).with_mods(mods), v).unwrap(); + if a != b { + s.pointer(&PointerEvent::new(PointerKind::Drag, b.0, b.1).with_mods(mods), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, b.0, b.1).with_mods(mods), v).unwrap(); +} + +/// Where the Reshape tool draws its highlighted focal points. +fn reshape_highlights(s: &mut Session) -> Vec { + s.overlays(ViewInfo::default()) + .into_iter() + .filter_map(|o| match o { + vectorcraft_tools::Overlay::Anchor { p, filled: true, .. } => Some(p), + _ => None, + }) + .collect() +} + +#[test] +fn reshape_tool_shift_click_adds_focal_points_that_a_drag_moves_together() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), true); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 0.0), Point::new(280.0, 0.0)]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a click on an anchor is not an edit"); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 100.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert_eq!(&y[2..5], &[100.0, 100.0, 100.0], "{y:?}"); + assert!((y[1] - 50.0).abs() < 1e-9 && (y[5] - 50.0).abs() < 1e-9 && y[0] == 0.0 && y[6] == 0.0, "{y:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "the drag is one step"); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 100.0), Point::new(280.0, 100.0)], "the focal points stay highlighted"); +} + +#[test] +fn reshape_tool_shift_click_on_a_focal_point_removes_it_and_a_click_starts_again() { + for (clicks, want) in [ + // Shift-click 140 again: only 280 is a focal point. + (vec![(140.0, false), (280.0, true), (140.0, true)], vec![Point::new(280.0, 0.0)]), + // A click without Shift: only 350 is a focal point. + (vec![(140.0, false), (280.0, true), (350.0, false)], vec![Point::new(350.0, 0.0)]), + ] { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + for (x, shift) in clicks { + reshape_gesture(&mut s, (x, 0.0), (x, 0.0), shift); + } + assert_eq!(reshape_highlights(&mut s), want); + let at = (want[0].x, 0.0); + reshape_gesture(&mut s, at, (at.0, 100.0), false); + let full = reshape_anchors(&s, id).iter().filter(|a| a.p.y == 100.0).count(); + assert_eq!(full, 1, "only the dragged focal point moves whole: {:?}", reshape_anchors(&s, id)); + } +} + +#[test] +fn reshape_tool_focal_point_stays_its_anchor_when_another_anchor_moves_onto_it() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), false); + // Anchor 2 now lies where the focal point, anchor 4, lies. + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 280.0, "y": 0.0})).unwrap(); + // A Shift-click adds the last anchor, and a drag from it moves it and anchor 4 whole. + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 0.0), true); + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 100.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[4] == 100.0 && y[6] == 100.0 && y[2] < 100.0, "{y:?}"); +} + +#[test] +fn reshape_tool_anchor_added_before_a_focal_point_keeps_it_highlighted() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), false); + // A Shift-click on the segment from 70 to 140 adds anchor 2, before the focal point. + reshape_gesture(&mut s, (105.0, 0.0), (105.0, 0.0), true); + assert_eq!(reshape_anchors(&s, id).len(), 8); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(280.0, 0.0), Point::new(105.0, 0.0)]); + // A drag from the added anchor moves both focal points whole. + reshape_gesture(&mut s, (105.0, 0.0), (105.0, 40.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[2] == 40.0 && y[5] == 40.0, "{y:?}"); +} + +#[test] +fn reshape_tool_focal_point_moved_by_another_edit_is_not_passed_to_another_anchor() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), false); + // The focal point, anchor 4, moves away, and anchor 2 takes its old place. + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 4, "x": 280.0, "y": 50.0})).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 280.0, "y": 0.0})).unwrap(); + assert_eq!(reshape_highlights(&mut s), vec![]); + // A Shift-click adds the last anchor, and a drag from it moves it alone as the focal point. + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 0.0), true); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(420.0, 0.0)]); + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 100.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[6] == 100.0 && y[2] < 100.0, "{y:?}"); +} + +#[test] +fn reshape_tool_drag_from_an_anchor_that_is_not_highlighted_moves_only_it_whole() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + reshape_gesture(&mut s, (350.0, 0.0), (350.0, 100.0), false); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[2] < 100.0 && y[5] == 100.0, "{y:?}"); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(350.0, 100.0)]); +} + +#[test] +fn reshape_tool_click_on_a_segment_adds_a_highlighted_anchor() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + reshape_gesture(&mut s, (245.0, 0.0), (245.0, 0.0), true); + assert_eq!(reshape_anchors(&s, id).len(), 8); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "adding the anchor is one step"); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 0.0), Point::new(245.0, 0.0)]); + reshape_gesture(&mut s, (245.0, 0.0), (245.0, 60.0), false); + let a = reshape_anchors(&s, id); + assert_eq!((a[2].p.y, a[3].p.y, a[4].p.y), (60.0, 60.0, 60.0), "{a:?}"); + // Undo takes back the drag, then the added anchor. The highlights stay where the drag left + // them, where no anchor is now, so none shows. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(reshape_anchors(&s, id).len(), 7); + assert!(reshape_highlights(&mut s).is_empty()); +} + +#[test] +fn reshape_tool_escape_during_a_drag_keeps_the_path_and_its_focal_points() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + let before = reshape_anchors(&s, id); + let steps = s.doc().unwrap().history.undo.len(); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + reshape_gesture(&mut s, (280.0, 0.0), (280.0, 0.0), true); + let v = ViewInfo::default(); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 0.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 90.0), v).unwrap(); + assert_ne!(reshape_anchors(&s, id), before, "the preview moves the path"); + s.tool_key(ToolKey::Escape, vectorcraft_tools::Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 90.0), v).unwrap(); + assert_eq!(reshape_anchors(&s, id), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(140.0, 0.0), Point::new(280.0, 0.0)]); +} + +#[test] +fn reshape_tool_shift_drag_from_an_anchor_that_is_not_highlighted_moves_only_it() { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + reshape_gesture(&mut s, (140.0, 0.0), (140.0, 0.0), false); + // Shift keeps the drag's angle; the highlighted anchor at 140 does not move whole with it. + reshape_gesture(&mut s, (350.0, 0.0), (350.0, 100.0), true); + let y: Vec = reshape_anchors(&s, id).iter().map(|a| a.p.y).collect(); + assert!(y[5] == 100.0 && y[2] < 100.0, "{y:?}"); + assert_eq!(reshape_highlights(&mut s), vec![Point::new(350.0, 100.0)]); +} + +#[test] +fn reshape_tool_click_on_a_curved_segment_highlights_the_anchor_it_adds() { + // Points on the curve from 0 to 300, away from its anchors, each clicked from off it on a + // new copy of the path. + let c = vectorcraft_geom::CubicBez::new(Point::new(0.0, 0.0), Point::new(40.0, -90.0), Point::new(230.0, 110.0), Point::new(300.0, 0.0)); + for k in 1..60 { + let t = 0.05 + 0.015 * f64::from(k); + for off in [(0.3, -0.2), (-2.1, 1.7), (2.6, 2.2)] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [{"x": 0, "y": 0, "out": [40, -90]}, {"x": 300, "y": 0, "in": [230, 110]}, {"x": 600, "y": 0}]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.select_tool("reshape", ViewInfo::default()).unwrap(); + let q = vectorcraft_geom::ParamCurve::eval(&c, t); + reshape_gesture(&mut s, (q.x + off.0, q.y + off.1), (q.x + off.0, q.y + off.1), false); + let a = reshape_anchors(&s, id); + assert_eq!(a.len(), 4, "t {t}, {off:?}"); + assert_eq!(reshape_highlights(&mut s), vec![a[1].p], "t {t}, {off:?}"); + } + } +} + +#[test] +fn reshape_tool_leaves_a_locked_or_hidden_path_alone() { + for command in ["object.lock", "object.hide"] { + let mut s = session(); + let id = reshape_tool_on_a_line(&mut s); + let before = reshape_anchors(&s, id); + s.execute(command, &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).ok(); + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 0.0), false); + reshape_gesture(&mut s, (420.0, 0.0), (420.0, 60.0), false); + assert_eq!(reshape_anchors(&s, id), before, "{command}"); + assert!(reshape_highlights(&mut s).is_empty(), "{command}"); + } +} + #[test] fn graph_tool_drag_creates_a_graph_and_asks_for_data() { let mut s = session(); diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 8d70237276..8d12c83719 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -647,6 +647,28 @@ fn edits_change_the_active_row_of_the_first_selected_object() { assert!(!e.contains("internal error"), "{e}"); } +/// After an aligned Remove Item or Duplicate Item, the active row follows the rows that changed in +/// the first selected object, also when that object paints above the others. +#[test] +fn aligned_remove_and_duplicate_keep_the_active_row_of_the_first_selected_object() { + let mut s = session(); + let (_, b) = reversed_pair(&mut s); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); // b's red fill + // a's row 0 is b's white fill, row 1, so b's red fill stays at row 0. + run(&mut s, "appearance.removeItem", json!({"indices": [0], "aligned": true})); + assert_eq!(node(&s, b).appearance.items.len(), 2); + assert_eq!(s.appearance_item(), Some(0)); + assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#ff0000"); + + let mut s = session(); + let (_, b) = reversed_pair(&mut s); + run(&mut s, "appearance.setActiveItem", json!({"index": 1})); // b's white fill, a's row 0 + // The copy goes above b's white fill, at 2; the active row stays on the original. + run(&mut s, "appearance.duplicateItem", json!({"indices": [0], "aligned": true})); + assert_eq!(node(&s, b).appearance.items.len(), 4); + assert_eq!(s.appearance_item(), Some(1)); +} + /// `effect.apply`'s reply names the new effect by its index in the object whose row `item` is, /// also when the objects painted after it already have effects there. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 638b7a1f4b..b86cf89ee7 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1321,6 +1321,106 @@ fn break_link_counts_the_instances_mask_art() { assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "it stays an instance"); } +/// A hidden, a locked and a plain instance of one symbol in a group, the group selected. +fn group_with_hidden_and_locked_instances(s: &mut Session) -> (NodeId, String) { + let (shown, name, _) = make_symbol(s); + let hidden = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap()); + let locked = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 100})).unwrap()["id"].as_u64().unwrap()); + select(s, &[shown, hidden, locked]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(hidden).unwrap().visible = false; + doc.node_mut(locked).unwrap().locked = true; + select(s, &[group]); + (group, name) +} + +/// The visibility and lock state of the children of `group`, in paint order. +fn shown_and_locked(s: &Session, group: NodeId) -> Vec<(bool, bool)> { + let g = node(s, group); + let NodeKind::Group { children, .. } = &g.kind else { panic!("a group: {}", g.kind_label()) }; + assert!(children.iter().all(|c| !matches!(c.kind, NodeKind::SymbolInstance { .. })), "every instance is expanded"); + children.iter().map(|c| (c.visible, c.locked)).collect() +} + +/// Break Link to Symbol on a selected group keeps a hidden instance's art hidden and a locked +/// instance's art locked, and selects only the art that can be selected. +#[test] +fn break_link_keeps_hidden_and_locked_instances_hidden_and_locked() { + let mut s = session(); + let (group, _) = group_with_hidden_and_locked_instances(&mut s); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 3, "{r}"); + assert_eq!(shown_and_locked(&s, group), vec![(true, false), (false, false), (true, true)]); + let d = &s.doc().unwrap().doc; + let selected: Vec = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(selected.len(), 1, "{selected:?}"); + assert!(selected.iter().all(|id| d.node(*id).is_some_and(|n| n.visible && !n.locked)), "{selected:?}"); +} + +/// Break Link to Symbol on a selected group does not select the art of a shown, unlocked instance +/// that sits in a hidden or a locked group inside it. +#[test] +fn break_link_leaves_art_in_hidden_or_locked_groups_unselected() { + let mut s = session(); + let (shown, name, _) = make_symbol(&mut s); + let subgroup = |s: &mut Session, y: i64| { + let id = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": y})).unwrap()["id"].as_u64().unwrap()); + select(s, &[id]); + NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) + }; + let hidden = subgroup(&mut s, 200); + let locked = subgroup(&mut s, 100); + select(&mut s, &[shown, hidden, locked]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(hidden).unwrap().visible = false; + doc.node_mut(locked).unwrap().locked = true; + select(&mut s, &[group]); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 3, "{r}"); + let d = &s.doc().unwrap().doc; + let selected: Vec = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(selected.len(), 1, "{selected:?}"); + let a = d.ancestry(selected[0]).unwrap(); + assert!(!a.contains(&hidden) && !a.contains(&locked), "{a:?}"); +} + +/// Break Link to Symbol on an instance just placed on a locked artboard selects the art that +/// replaces it, which stays new art there. The art of an older instance there, named by id, is not +/// selected. +#[test] +fn break_link_keeps_new_art_on_a_locked_artboard_selected() { + let mut s = session(); + let (old, name, _) = make_symbol(&mut s); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + select(&mut s, &[old]); + s.execute("object.move", &json!({"dx": 1000, "dy": 0})).unwrap(); + assert!(s.doc().unwrap().selection.objects.is_empty(), "moved onto the locked artboard"); + let inst = NodeId(s.execute("symbol.place", &json!({"name": name, "x": 1100, "y": 100})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [inst], "placed art is selected"); + let r = s.execute("symbol.breakLink", &json!({})).unwrap(); + let art: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(art.len(), 1, "{r}"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), art, "the art that replaces it"); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), art, "the art stays editable"); + let r = s.execute("symbol.breakLink", &json!({"ids": [old.0]})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 1, "{r}"); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the older instance's art"); +} + +/// Delete Symbol, expanding the instances, keeps a hidden instance's art hidden and a locked +/// instance's art locked. +#[test] +fn delete_symbol_keeps_hidden_and_locked_instances_hidden_and_locked() { + let mut s = session(); + let (group, name) = group_with_hidden_and_locked_instances(&mut s); + s.execute("symbol.delete", &json!({"name": name})).unwrap(); + assert_eq!(shown_and_locked(&s, group), vec![(true, false), (false, false), (true, true)]); +} + #[test] fn delete_duplicate_and_replace_symbols() { let mut s = session(); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index df3a5f0667..fcf9b63636 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2380,6 +2380,82 @@ fn add_anchor_point_selects_the_path_it_was_added_to() { assert!(selected_anchors(&s, kept).is_empty(), "a path selected as a whole stays so"); } +fn path_from(s: &mut Session, d: &str) -> NodeId { + NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()) +} + +fn selected_segments(s: &Session, id: NodeId) -> Vec<(usize, usize)> { + s.doc().unwrap().selection.segments.get(&id).map(|set| set.iter().copied().collect()).unwrap_or_default() +} + +fn selected_points(s: &Session, id: NodeId) -> Vec { + let pd = path(s, id); + selected_anchors(s, id).iter().filter_map(|&(si, ai)| pd.subpaths.get(si)?.anchors.get(ai)).map(|a| a.p).collect() +} + +#[test] +fn add_anchor_point_keeps_the_same_anchors_selected() { + // The direct-selected anchors after the one added are numbered one higher, so the selection + // stays on the same points; one undo step restores the path and the selection. + let mut s = session(); + let id = path_from(&mut s, "M0 0 L70 0 L140 0 L210 0 L280 0 L350 0 L420 0"); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, 5]], "mode": "set"})).unwrap(); + let before = selected_points(&s, id); + let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 2, "t": 0.5})).unwrap(); + assert_eq!(r["anchor"], 3); + assert_eq!(selected_anchors(&s, id), [(0, 1), (0, 6)], "the anchor at 350 is now number 6"); + assert_eq!(selected_points(&s, id), before); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 7); + assert_eq!(selected_anchors(&s, id), [(0, 1), (0, 5)]); +} + +#[test] +fn add_anchor_point_on_a_selected_segment_keeps_both_halves_and_the_new_anchor_selected() { + let mut s = session(); + let id = path_from(&mut s, "M0 0 L70 0 L140 0 L210 0 L280 0 L350 0 L420 0"); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 2], [0, 4]], "mode": "set"})).unwrap(); + s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 2, "t": 0.5})).unwrap(); + assert_eq!(selected_segments(&s, id), [(0, 2), (0, 3), (0, 5)]); + assert_eq!(selected_anchors(&s, id), [(0, 2), (0, 3), (0, 4), (0, 5), (0, 6)], "the new anchor is selected with the segment's ends"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 7); + assert_eq!(selected_segments(&s, id), [(0, 2), (0, 4)]); +} + +#[test] +fn add_anchor_point_on_the_closing_segment_keeps_it_selected_as_two_halves() { + let mut s = session(); + let id = path_from(&mut s, "M0 0 L100 0 L100 100 L0 100 Z"); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 3]], "mode": "set"})).unwrap(); + let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 3, "t": 0.5})).unwrap(); + assert_eq!(r["anchor"], 4); + assert_eq!(selected_segments(&s, id), [(0, 3), (0, 4)]); + assert_eq!(selected_anchors(&s, id), [(0, 0), (0, 3), (0, 4)]); + assert_eq!(selected_points(&s, id), [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(0.0, 50.0)]); +} + +#[test] +fn add_anchor_point_renumbers_only_the_subpath_it_was_added_to() { + let mut s = session(); + let id = path_from(&mut s, "M0 0 L100 0 L200 0 M0 100 L100 100 L200 100"); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2], [1, 1], [1, 2]], "mode": "set"})).unwrap(); + let before = selected_points(&s, id); + s.execute("path.insertAnchor", &json!({"id": id.0, "subpath": 1, "segment": 0, "t": 0.5})).unwrap(); + assert_eq!(selected_anchors(&s, id), [(0, 2), (1, 2), (1, 3)]); + assert_eq!(selected_points(&s, id), before); +} + +#[test] +fn add_anchor_point_with_a_selected_anchor_index_past_the_end_does_not_panic() { + // `select.anchors` takes any index, so a selected one can name no anchor. + let mut s = session(); + let id = path_from(&mut s, "M0 0 L70 0 L140 0 L210 0"); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1], [0, usize::MAX]], "mode": "set"})).unwrap(); + s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "t": 0.5})).unwrap(); + assert_eq!(selected_anchors(&s, id), [(0, 2), (0, usize::MAX)]); +} + fn selected_anchors(s: &Session, id: NodeId) -> Vec<(usize, usize)> { s.doc().unwrap().selection.anchors.get(&id).map(|set| set.iter().copied().collect()).unwrap_or_default() } diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 090cb98285..038b8844bb 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -75,6 +75,29 @@ fn symbol_instance_tint_survives_expanding_an_object_effect() { assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); } +/// The canvas tints a symbol's art with the instance fill before the instance's color adjustment, +/// and expanding gives the same colors. +#[test] +fn symbol_instance_tint_comes_before_a_color_adjustment_when_expanded() { + let mut s = session(); + square(&mut s); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Tinted Square"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let fill = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": fill, "color": "#00ff00", "opacity": 50})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}})); + let before = render(&s); + assert_ne!(before.pixel(100, 100), [255, 255, 255, 255], "the symbol is visible"); + assert!(expandable(&s)); + + run(&mut s, "effect.expandAppearance", json!({})); + assert!(!matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. })); + let after = render(&s); + let (b, a) = (before.pixel(100, 100), after.pixel(100, 100)); + assert!(b.iter().zip(a.iter()).all(|(x, y)| x.abs_diff(*y) <= 8), "expanding changed the color from {b:?} to {a:?}"); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); +} + /// An instance fill with an opacity of 0 does not tint the symbol's art, so expanding keeps the /// art's global swatch link. #[test] diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index 2e08b99c89..84e4724fe6 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -350,6 +350,31 @@ fn gradients_rasterize_and_flat_areas_stay_vector() { } } +#[test] +fn a_long_rasterized_area_is_placed_whole() { + let _settings = settings_lock(); + let mut s = session(); + // 5569 pt long: more than the renderer's 32,768 pixels a side at the 64 Mpx limit's scale. + let g = rect(&mut s, 10.0, 10.0, 100.0, 5569.0, "#000000"); + run( + &mut s, + "paint.setFill", + json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ); + run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40})); + let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "lineArtPpi": 1200, "gradientPpi": 1200})); + assert_eq!(rasterized, 1); + let mut placed = vec![]; + node(&s, ids[0]).walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + placed.push((im.height, im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))))); + } + }); + let [(height, b)] = placed[..] else { panic!("one image: {placed:?}") }; + assert!(height <= vectorcraft_render::MAX_RASTER_SIDE, "{height} pixels"); + assert!(b.y0 <= 10.0 && b.y1 >= 5579.0, "the image covers the strip: {b:?}"); +} + #[test] fn flatten_says_when_an_image_could_not_be_decoded() { let _settings = settings_lock(); diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 9a9aafcbac..fefed0ad11 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -368,6 +368,31 @@ fn a_transparent_image_is_flattened_with_the_art_under_it_which_stays() { assert_eq!(colour_at(page, 10.0, 20.0), [255, 0, 0], "the square outside the image"); } +/// A transparent image longer than the renderer draws at its own resolution (32,768 pixels a +/// side) is flattened whole, at a lower resolution. +#[test] +fn a_long_transparent_image_is_flattened_whole() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 4600})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 4600})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let p = json!({"name": "i.png", "dataBase64": vectorcraft_format::base64_encode(&png(2000, 1600, [0, 0, 0, 128])), "at": [50, 50]}); + s.execute("file.place", &p).unwrap(); + // 10 × 4500 pt: about 600 ppi, so 37,500 pixels long. + s.execute("object.setBounds", &json!({"x": 10, "y": 10, "width": 10, "height": 4500, "reference": 0})).unwrap(); + let before = [colour_at(&s.doc().unwrap().doc, 15.0, 100.0), colour_at(&s.doc().unwrap().doc, 15.0, 4400.0)]; + assert!(before.iter().all(|c| c[0] < 200), "the image darkens the red: {before:?}"); + let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7"})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("flattened with the art under them")), "{r}"); + s.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap(); + let d = &s.doc().unwrap().doc; + let after = [colour_at(d, 15.0, 100.0), colour_at(d, 15.0, 4400.0)]; + for (a, b) in before.iter().zip(&after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 3), "{before:?} {after:?}"); + } +} + /// A `size`×`size` PNG of a black disk of radius `r` pixels with an anti-aliased edge, clear /// around it, 72 ppi. fn disk(size: u32, r: f64) -> Vec { diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 951a9ec31a..7f70d24ff0 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -349,6 +349,41 @@ fn perceptual_spot_gradients_with_rgb_stops_in_a_cmyk_document_export_as_device_ assert!(r.warnings.iter().any(|w| w.contains("spot")), "RGB destination: {:?}", r.warnings); } +#[test] +fn classic_spot_gradients_with_rgb_stops_in_a_cmyk_document_export_as_device_n_shadings() { + let (mut s, _) = setup(); + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}]})); + let (pdf, warnings) = pdf_of(&s); + assert!(!pdf.contains("/DeviceN") && warnings.iter().any(|w| w.contains("spot")), "an RGB document drops the ink: {warnings:?}"); + // A CMYK document, or a conversion to a CMYK destination, writes the RGB stop in CMYK: a + // DeviceN shading that keeps the ink. + let mut cmyk = doc(&s).clone(); + cmyk.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let plain = vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() }; + let mut converted = plain.clone(); + converted.settings.output = vectorcraft_pdf::OutputSettings { + conversion: vectorcraft_pdf::ColorConversion::Destination, + destination: vectorcraft_pdf::DOCUMENT_CMYK.into(), + ..Default::default() + }; + for (what, d, opts) in [("CMYK document", &cmyk, &plain), ("CMYK destination", doc(&s), &converted)] { + let r = vectorcraft_pdf::export_with_report(d, opts).unwrap(); + let pdf = String::from_utf8_lossy(&r.bytes); + assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Ink]/DeviceCMYK"), "{what}: a DeviceN shading with Ink"); + assert!(!r.warnings.iter().any(|w| w.contains("spot")), "{what}: {:?}", r.warnings); + } + // A conversion to an RGB destination keeps the RGB stop in RGB, in a CMYK document too. + let mut to_rgb = plain.clone(); + to_rgb.settings.output = vectorcraft_pdf::OutputSettings { + conversion: vectorcraft_pdf::ColorConversion::Destination, + destination: vectorcraft_color::cms::SRGB.into(), + ..Default::default() + }; + let r = vectorcraft_pdf::export_with_report(&cmyk, &to_rgb).unwrap(); + assert!(!String::from_utf8_lossy(&r.bytes).contains("/DeviceN"), "RGB destination: no DeviceN shading"); + assert!(r.warnings.iter().any(|w| w.contains("spot")), "RGB destination: {:?}", r.warnings); +} + #[test] fn spot_gradients_drawn_as_images_warn() { let (mut s, _) = setup(); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 763cf22edb..e1def8a6fa 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1461,6 +1461,42 @@ fn rasterize_replaces_selection_with_image() { assert_eq!(selected(&s), vec![img]); } +/// Rasterize refuses art that would be longer than the renderer draws (32,768 pixels a side), and +/// the art stays as it was; at a resolution that fits, the image covers all of it. +#[test] +fn rasterize_refuses_an_image_longer_than_the_renderer_draws() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 5569.0); + sel(&mut s, &[a]); + let vb = s.doc().unwrap().doc.bounds_of(&[a], true).unwrap(); + let before = (undo_len(&s), node(&s, a)); + let e = s.execute("object.rasterize", &json!({"ppi": 600, "padding": 0})).unwrap_err().to_string(); + assert!(e.contains("too large"), "{e}"); + assert_eq!((undo_len(&s), node(&s, a)), before); + let img = id_of(&s.execute("object.rasterize", &json!({"ppi": 400, "padding": 0})).unwrap()); + let n = node(&s, img); + let NodeKind::Image(im) = &n.kind else { panic!() }; + assert!(im.height <= vectorcraft_render::MAX_RASTER_SIDE, "{} pixels", im.height); + let b = n.geometric_bounds().unwrap(); + assert!(close(b.y0, vb.y0) && b.y1 >= vb.y1, "{b:?} covers {vb:?}"); +} + +/// Art that snaps to exactly 32,768 pixels a side is rasterized, wherever it is on the canvas. +#[test] +fn rasterize_takes_art_that_snaps_to_32768_pixels_a_side() { + let scale = 400.0 / 72.0; + for y in [100_000.0, 250_000.0, 333_333.3, 777_777.7] { + let mut s = session(); + let probe = rect(&mut s, 10.0, y, 100.0, 5898.0); + let vb = s.doc().unwrap().doc.bounds_of(&[probe], true).unwrap(); + let h = 5898.0 + (32_767.8 / scale - vb.height()); + let a = rect(&mut s, 200.0, y, 100.0, h); + sel(&mut s, &[a]); + let r = s.execute("object.rasterize", &json!({"ppi": 400, "padding": 0})).unwrap_or_else(|e| panic!("at y = {y}: {e}")); + assert_eq!(r["height"].as_u64(), Some(u64::from(vectorcraft_render::MAX_RASTER_SIDE)), "at y = {y}: {r}"); + } +} + /// Rasterize refuses a resolution given as text or as another value that is not a number, and the /// selected art stays as it was. #[test] @@ -4294,6 +4330,77 @@ fn guides_dragged_out_of_a_ruler_snap_and_take_the_artboard_tool_s_artboard() { ); } +/// With Preferences › Guides & Grid › Artboard Guides with Cmd/Ctrl + Ruler Drag on, Cmd/Ctrl held +/// when a guide is dragged out of a ruler makes a guide of the view's active artboard (one undo +/// step), shown and made only where it lies within that artboard; with the Artboard tool it makes +/// a canvas guide instead. The key counts on the drag's first event only. With the preference off, +/// Cmd/Ctrl changes nothing. +#[test] +fn cmd_ruler_drags_make_guides_of_the_active_artboard_when_the_preference_is_on() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let mut s = session(); + s.execute("artboard.new", &json!({"x": 900, "y": 0, "width": 400, "height": 300})).unwrap(); + let v = ViewInfo { artboard: 1, ..ViewInfo::default() }; + let cmd = Mods { cmd: true, ..Mods::default() }; + let ev = |kind, x, y, mods| PointerEvent::new(kind, x, y).with_mods(mods); + let owners = |s: &mut Session| -> Vec { + let list = s.execute("guide.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().map(|g| g.get("artboard").cloned().unwrap_or(Value::Null)).collect() + }; + let drag = |s: &mut Session, view: ViewInfo, vertical: bool, at: f64, first: Mods| { + let (x, y) = if vertical { (at, 30.0) } else { (1000.0, at) }; + s.ruler_guide(vertical, &ev(PointerKind::Drag, x, y, first), true, view).unwrap(); + // Letting go of the key during the drag keeps the kind of guide. + s.ruler_guide(vertical, &ev(PointerKind::Up, x, y, Mods::default()), true, view).unwrap(); + }; + + // Off by default: a Cmd/Ctrl drag makes a canvas guide. + assert!(!s.prefs.cmd_ruler_drag_artboard_guides); + drag(&mut s, v, true, 1010.0, cmd); + assert_eq!(owners(&mut s), [Value::Null]); + + s.execute("prefs.set", &json!({"key": "cmdRulerDragArtboardGuides", "value": true})).unwrap(); + let n = undo_len(&s); + drag(&mut s, v, true, 1020.0, cmd); + drag(&mut s, v, false, 120.0, cmd); + assert_eq!(guides(&s)[1..], [(true, 1020.0), (false, 120.0)]); + assert_eq!(owners(&mut s)[1..], [json!(1), json!(1)]); + assert_eq!(undo_len(&s), n + 2); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(owners(&mut s)[1..], [json!(1), json!(1)], "redo keeps the artboard"); + + // Outside the active artboard (left of it, and below it): no preview, no guide, no undo step. + let n = undo_len(&s); + s.ruler_guide(true, &ev(PointerKind::Drag, 500.0, 30.0, cmd), true, v).unwrap(); + assert_eq!(guides(&s).len(), 3, "no preview"); + s.ruler_guide(true, &ev(PointerKind::Up, 500.0, 30.0, cmd), true, v).unwrap(); + drag(&mut s, v, false, 450.0, cmd); + assert_eq!((guides(&s).len(), undo_len(&s)), (3, n)); + // Dragged in and out again: the preview goes and nothing is made. + s.ruler_guide(true, &ev(PointerKind::Drag, 1100.0, 30.0, cmd), true, v).unwrap(); + assert_eq!(guides(&s).len(), 4, "the preview within the artboard"); + s.ruler_guide(true, &ev(PointerKind::Drag, 700.0, 30.0, Mods::default()), true, v).unwrap(); + s.ruler_guide(true, &ev(PointerKind::Up, 700.0, 30.0, Mods::default()), true, v).unwrap(); + assert_eq!((guides(&s).len(), undo_len(&s)), (3, n)); + + // An active artboard the document doesn't have: nothing is made. + drag(&mut s, ViewInfo { artboard: 7, ..v }, true, 1030.0, cmd); + assert_eq!((guides(&s).len(), undo_len(&s)), (3, n)); + + // Without the key: a canvas guide, as before. + drag(&mut s, v, true, 1040.0, Mods::default()); + assert_eq!(owners(&mut s)[3], Value::Null); + + // The Artboard tool: Cmd/Ctrl makes a canvas guide, and a plain drag an artboard guide. + s.select_tool("artboard", v).unwrap(); + s.set_tool_option("active", &json!(1)); + drag(&mut s, v, true, 400.0, cmd); + drag(&mut s, v, true, 1050.0, Mods::default()); + assert_eq!(guides(&s)[4..], [(true, 400.0), (true, 1050.0)]); + assert_eq!(owners(&mut s)[4..], [Value::Null, json!(1)]); +} + /// Guides saved before guides had layers are put on a layer when the document opens. #[test] fn guides_from_older_files_are_put_on_a_layer() { diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 239d6bee7b..4d549c31ef 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -2,7 +2,7 @@ use serde_json::json; use vectorcraft_color::{Color, GradientKind, Paint}; -use vectorcraft_doc::{AppearanceItem, NodeKind}; +use vectorcraft_doc::{AppearanceItem, LayerColor, NodeKind}; use crate::*; @@ -1387,6 +1387,128 @@ fn artboard_video_display_options_are_set_in_one_undo_step() { assert_eq!(video(&s, 1), (false, 10.0), "10 is in range"); } +/// Artboard Options' guide label: `artboard.setProps {guideLabel}` takes a layer color's name or +/// `#rrggbb` and null clears it, each change one undo step, also on a locked artboard (whose +/// rectangle stays locked) and for several artboards in one list; a value equal to the artboard's +/// adds no undo step. `artboard.new` takes it, a duplicate and an undone delete keep it, and +/// `inspect_document` reports it. A bad value anywhere in a list changes nothing. +#[test] +fn artboard_guide_labels_are_set_and_cleared_in_one_undo_step() { + let mut s = session(); + s.execute("artboard.new", &json!({})).unwrap(); + let label = |s: &Session, i: usize| s.doc().unwrap().doc.artboards[i].guide_label; + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + assert_eq!((label(&s, 0), label(&s, 1)), (None, None), "no label by default"); + let u0 = undo(&s); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "Red"})).unwrap(); + assert_eq!((label(&s, 0), label(&s, 1)), (None, Some(LayerColor::Preset(1))), "only that artboard"); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "#12aBcd"})).unwrap(); + assert_eq!(label(&s, 1), Some(LayerColor::Custom([0x12, 0xab, 0xcd]))); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": null})).unwrap(); + assert_eq!(label(&s, 1), None, "null clears it"); + assert_eq!(undo(&s), u0 + 3, "one undo step each"); + for was in [Some(LayerColor::Custom([0x12, 0xab, 0xcd])), Some(LayerColor::Preset(1)), None] { + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(label(&s, 1), was); + } + s.execute("edit.redo", &json!({})).unwrap(); + // The same label again, or a list that changes nothing: no undo step. + let u = undo(&s); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": "Red"})).unwrap(); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": null}, {"index": 1, "guideLabel": "Red"}]})).unwrap(); + assert_eq!(undo(&s), u, "nothing changed, no undo step"); + // A locked artboard takes a label; its rectangle stays locked. + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let rect0 = s.doc().unwrap().doc.artboards[0].rect; + s.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Gold"})).unwrap(); + assert_eq!(label(&s, 0), Some(LayerColor::Preset(15))); + assert!(s.execute("artboard.setProps", &json!({"index": 0, "x": 999, "guideLabel": "Teal"})).is_err()); + assert_eq!((s.doc().unwrap().doc.artboards[0].rect, label(&s, 0)), (rect0, Some(LayerColor::Preset(15)))); + let u = undo(&s); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Teal"}, {"index": 1, "guideLabel": "#000000"}]})).unwrap(); + assert_eq!((label(&s, 0), label(&s, 1)), (Some(LayerColor::Preset(11)), Some(LayerColor::Custom([0, 0, 0]))), "each its own"); + assert_eq!(undo(&s), u + 1, "in one undo step"); + let doc = crate::inspect::document(&s); + assert_eq!((doc["artboards"][0]["guideLabel"].clone(), doc["artboards"][1]["guideLabel"].clone()), (json!("Teal"), json!("#000000"))); + s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": null})).unwrap(); + assert!(crate::inspect::document(&s)["artboards"][1].get("guideLabel").is_none(), "no label isn't reported"); + let copy = s.execute("artboard.duplicate", &json!({"index": 0})).unwrap()["index"].as_u64().unwrap() as usize; + assert_eq!(label(&s, copy), Some(LayerColor::Preset(11)), "a duplicate keeps it"); + let made = s.execute("artboard.new", &json!({"guideLabel": "Violet"})).unwrap()["index"].as_u64().unwrap() as usize; + assert_eq!(label(&s, made), Some(LayerColor::Preset(14)), "a new artboard takes it"); + let plain = s.execute("artboard.new", &json!({})).unwrap()["index"].as_u64().unwrap() as usize; + assert_eq!(label(&s, plain), None); + s.execute("artboard.delete", &json!({"index": made})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(label(&s, made), Some(LayerColor::Preset(14)), "undoing a delete brings it back"); + let before = s.doc().unwrap().doc.clone(); + let bads = [ + json!("red"), + json!(" Red"), + json!("#12345"), + json!("#1234567"), + json!("#12345678"), + json!("#fff"), + json!("#gg0000"), + json!(1), + json!([1, 2, 3]), + json!({"Preset": 1}), + json!(true), + ]; + for bad in bads { + assert!(s.execute("artboard.setProps", &json!({"index": 1, "guideLabel": bad})).is_err(), "{bad}"); + assert!(s.execute("artboard.new", &json!({"guideLabel": bad})).is_err(), "{bad}"); + assert!( + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Red"}, {"index": 1, "guideLabel": bad}]})).is_err(), + "{bad}" + ); + } + assert!(s.execute("artboard.setProps", &json!({"artboards": [{"index": 1, "guideLabel": "Red"}, {"index": 1, "guideLabel": "Red"}]})).is_err()); + assert!(s.execute("artboard.setProps", &json!({"artboards": [{"index": 1, "guideLabel": "Red"}, {"index": 99, "guideLabel": "Red"}]})).is_err()); + assert_eq!(*s.doc().unwrap().doc, *before, "a bad value changes nothing"); +} + +/// The native format keeps the guide label, as `{"Preset": n}` or `{"Custom": [r, g, b]}`. An +/// artboard without one is written as before labels could be set, and a preset outside the layer +/// colors in a file reads as no label. Exports leave the label out. +#[test] +fn artboard_guide_labels_round_trip_through_the_native_format() { + let mut s = session(); + rect(&mut s); + s.execute("artboard.new", &json!({})).unwrap(); + let save = |s: &Session| vectorcraft_format::save(&s.doc().unwrap().doc, false); + let before = save(&s); + let plain = (*s.doc().unwrap().doc).clone(); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": "Green"}, {"index": 1, "guideLabel": "#102030"}]})).unwrap(); + let bytes = save(&s); + let saved: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let ab = |i: usize| saved["document"]["artboards"][i]["guide_label"].clone(); + assert_eq!((ab(0), ab(1)), (json!({"Preset": 2}), json!({"Custom": [16, 32, 48]}))); + let back = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(back.artboards, s.doc().unwrap().doc.artboards); + // Screen-only: SVG and PDF exports are the same as without the labels. + let on = (*s.doc().unwrap().doc).clone(); + assert_eq!(vectorcraft_svg::export(&on, &Default::default()), vectorcraft_svg::export(&plain, &Default::default())); + let options = vectorcraft_pdf::PdfOptions { created: Some(0), ..Default::default() }; + assert_eq!(crate::export_pdf(&on, &options).unwrap(), crate::export_pdf(&plain, &options).unwrap()); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "guideLabel": null}, {"index": 1, "guideLabel": null}]})).unwrap(); + assert_eq!(save(&s), before, "without labels, the file is as it was"); + // A file's labels as another writer might put them: a preset past the layer colors reads as + // none, and a label that isn't a layer color at all is refused. + let mut edited = saved.clone(); + edited["document"]["artboards"][0]["guide_label"] = json!({"Preset": 27}); + edited["document"]["artboards"][1]["guide_label"] = json!({"Preset": 26}); + let back = vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).unwrap(); + assert_eq!((back.artboards[0].guide_label, back.artboards[1].guide_label), (None, Some(LayerColor::Preset(26)))); + for bad in [json!({"Preset": 256}), json!({"Custom": [1, 2]}), json!("Red"), json!({"Custom": [1, 2, 300]})] { + edited["document"]["artboards"][0]["guide_label"] = bad.clone(); + assert!(vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).is_err(), "{bad}"); + } + edited["document"]["artboards"][0]["guide_label"] = json!(null); + let back = vectorcraft_format::load(&serde_json::to_vec(&edited).unwrap()).unwrap(); + assert_eq!(back.artboards[0].guide_label, None); +} + /// The native format keeps Show Video Safe Areas and the Video Ruler Pixel Aspect Ratio. A /// document whose artboards hide the safe areas and have square pixels is written byte for byte as /// before they could be set, a file written without the two keys opens with the safe areas off diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 57094355c0..72aa559ae0 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -863,6 +863,8 @@ fn path_commands_refuse_a_param_of_the_wrong_type() { for (cmd, p, want) in [ ("object.path.offsetPath", json!({"offset": true}), number("offset", "true")), ("object.path.offsetPath", json!({"offset": "wide"}), number("offset", "\"wide\"")), + ("object.path.offsetPath", json!({"offset": "10abc"}), number("offset", "\"10abc\"")), + ("object.path.offsetPath", json!({"offset": 5, "miterLimit": "4x"}), number("miterLimit", "\"4x\"")), ("object.path.offsetPath", json!({"offset": 5, "joins": 3}), "`joins` must be a string".to_string()), ("object.path.offsetPath", json!({"offset": 5, "joins": "pointy"}), "`joins` must be one of miter, round, bevel".to_string()), ("object.path.offsetPath", json!({"offset": 5, "miterLimit": [4]}), number("miterLimit", "[4]")), diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rs index 6a6022fdb3..0ce9b0bf09 100644 --- a/crates/engine/src/tests/persp_select.rs +++ b/crates/engine/src/tests/persp_select.rs @@ -262,6 +262,45 @@ fn snap_moves_objects_at_different_depths_by_one_plane_offset() { assert!(on_line(moved.y0) || on_line(moved.y1), "{moved:?}"); } +/// The anchors of `flat` and `far` after a snapped move of both on the left plane, where `flat` +/// starts flat (attached by the move, or first with `attach_first`) and `far` sits 50 pt deeper. +fn move_with_a_flat_first_object(attach_first: bool, constrain: bool) -> Vec { + let (mut s, _) = persp_session(); + let rect = |s: &mut Session, x: f64| { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 380, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()) + }; + s.execute("perspective.plane.move", &json!({"plane": "left", "offset": 50})).unwrap(); + let far = rect(&mut s, 150.0); + s.execute("perspective.attach", &json!({"ids": [far.0], "plane": "left"})).unwrap(); + s.execute("perspective.plane.move", &json!({"plane": "left", "offset": 0})).unwrap(); + let flat = rect(&mut s, 240.0); + if attach_first { + s.execute("perspective.attach", &json!({"ids": [flat.0], "plane": "left"})).unwrap(); + } + s.execute("perspective.grid.snap", &json!({"on": true})).unwrap(); + let h = grid(&s).homography_at(Plane::Left, 0.0).unwrap(); + let (from, to) = (h.apply(Point::new(100.0, 100.0)).unwrap(), h.apply(Point::new(137.3, 121.7)).unwrap()); + s.execute( + "perspective.move", + &json!({"ids": [flat.0, far.0], "plane": "left", "from": [from.x, from.y], "to": [to.x, to.y], "constrain": constrain}), + ) + .unwrap(); + assert_eq!(attached(&s, flat).map(|a| a.0), Some(Plane::Left)); + let doc = &s.doc().unwrap().doc; + [flat, far].iter().flat_map(|id| doc.node(*id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect::>()).collect() +} + +#[test] +fn snap_reads_a_flat_first_object_as_attached_by_the_move() { + for constrain in [false, true] { + let (moved, attached_first) = (move_with_a_flat_first_object(false, constrain), move_with_a_flat_first_object(true, constrain)); + assert_eq!(moved.len(), attached_first.len()); + for (a, b) in moved.iter().zip(&attached_first) { + assert!(a.distance(*b) < 1e-6, "constrain {constrain}: {moved:?} vs {attached_first:?}"); + } + } +} + #[test] fn constrained_move_uses_each_objects_plane() { let (mut s, right) = persp_session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index aca18dee1e..04e7b7784e 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -980,6 +980,174 @@ fn painted_pieces_keep_to_the_effects_budget() { assert!((350..=100_000).contains(&paths), "{paths} paths"); } +/// A clock for a document's deferrals that reads `step` milliseconds later each time it is read; +/// the test changes the step as it goes. +fn stepping_clock(step: &std::sync::Arc) -> vectorcraft_plugins::deferred::Clock { + let (now, step) = (std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)), step.clone()); + std::sync::Arc::new(move || Some(now.fetch_add(step.load(std::sync::atomic::Ordering::Relaxed), std::sync::atomic::Ordering::Relaxed))) +} + +/// While a document is drawn on screen, the plug-in effects of its first view share a time budget. +/// A stage left out draws its input art, is listed by `effect.deferredStatus`, and stays left out +/// on later drawings; Effect › Refresh Deferred Effects runs it again with a fresh budget, and an +/// export draws every stage. Another document has a budget of its own. +#[test] +fn the_first_view_defers_plug_in_effects_past_its_budget() { + let mut s = session(); + let a = rect(&mut s, 10.0, "#ff0000"); + let b = rect(&mut s, 30.0, "#ff0000"); + for (id, x) in [("test.engine.deferred.a", 100.0), ("test.engine.deferred.b", 140.0)] { + let out = json!({"objects": [{"path": square_at(x)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&tpl::manifest(id, "effect", "{}"), &out)); + } + run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.deferred.a"})); + run(&mut s, "effect.apply", json!({"ids": [b.0], "effect": "plugin.test.engine.deferred.b"})); + // Each reading is 3 s later: the first run's result comes back after the budget, and the + // second run doesn't start. + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + let img = fx.view(|| drawn(&s)); + fx.first_view_done(); + assert_eq!((img.pixel(15, 15), img.pixel(35, 15), img.pixel(110, 50), img.pixel(150, 50)), (RED, RED, WHITE, WHITE), "the input art"); + assert_eq!(fx.take_report(), Some(2)); + let status = run(&mut s, "effect.deferredStatus", json!({})); + let listed = |id: NodeId, plugin: &str| json!({"objectId": id.0, "effectIndex": 0, "pluginId": plugin, "reason": "budget"}); + assert_eq!(status, json!({"budgetMs": 2000, "effects": [listed(a, "test.engine.deferred.a"), listed(b, "test.engine.deferred.b")]})); + assert_eq!(fx.view(|| drawn(&s)).pixel(110, 50), WHITE, "a later drawing leaves it deferred"); + + // Refreshed with a fresh budget, in which the clock stands still. + assert!(s.execute("effect.refreshDeferred", &json!({"ids": ["a"]})).is_err()); + assert!(s.execute("effect.refreshDeferred", &json!({"ids": [999_999]})).is_err(), "not an object of the document"); + step.store(0, std::sync::atomic::Ordering::Relaxed); + let refreshed = run(&mut s, "effect.refreshDeferred", json!({"ids": [a.0]})); + assert_eq!(refreshed, json!({"refreshed": 1, "stillDeferred": 0, "failed": 0})); + let img = fx.view(|| drawn(&s)); + assert_eq!((img.pixel(110, 50), img.pixel(150, 50)), (RED, WHITE)); + assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([listed(b, "test.engine.deferred.b")])); + + // An export draws every stage; the view then uses the result. + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + assert!(svg.contains(r#">(); + assert_eq!(places, [(a.0, None, 1), (a.0, None, 2), (b.0, Some(0), 1), (b.0, Some(0), 2)]); +} + +/// A refresh that does not draw a stage (its object, or a group holding it, is hidden) leaves it +/// deferred, and a stage whose effect has been removed or hidden, or whose object has been removed, +/// is no longer listed and does not enable Effect › Refresh Deferred Effects. +#[test] +fn refresh_keeps_stages_it_did_not_draw_and_drops_removed_ones() { + let mut s = session(); + let a = rect(&mut s, 10.0, "#ff0000"); + let b = rect(&mut s, 30.0, "#ff0000"); + let c = rect(&mut s, 50.0, "#ff0000"); + let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.kept", "effect", "{}"), &out)); + run(&mut s, "effect.apply", json!({"ids": [a.0, b.0, c.0], "effect": "plugin.test.engine.deferred.kept"})); + run(&mut s, "select.set", json!({"ids": [c.0]})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + fx.view(|| drawn(&s)); + fx.first_view_done(); + let listed = |s: &mut Session| { + run(s, "effect.deferredStatus", json!({}))["effects"].as_array().unwrap().iter().map(|e| e["objectId"].as_u64().unwrap()).collect::>() + }; + assert_eq!(listed(&mut s), [a.0, b.0, c.0]); + + s.execute("object.hide", &json!({"ids": [a.0, g.0]})).unwrap(); + step.store(0, std::sync::atomic::Ordering::Relaxed); + let refreshed = run(&mut s, "effect.refreshDeferred", json!({"ids": [a.0, c.0]})); + assert_eq!(refreshed, json!({"refreshed": 0, "stillDeferred": 2, "failed": 0}), "a hidden object is not drawn"); + assert_eq!(listed(&mut s), [a.0, b.0, c.0]); + + run(&mut s, "effect.remove", json!({"ids": [a.0], "index": 0})); + assert_eq!(listed(&mut s), [b.0, c.0], "its effect was removed"); + run(&mut s, "effect.setParams", json!({"ids": [b.0], "index": 0, "visible": false})); + assert_eq!(listed(&mut s), [c.0], "its effect was hidden"); + s.execute("edit.clear", &json!({"ids": [b.0, g.0]})).unwrap(); + assert_eq!(listed(&mut s), Vec::::new(), "its object was deleted"); + assert!(s.execute("effect.refreshDeferred", &json!({})).is_err(), "nothing is deferred"); +} + +/// A deferred stage in a symbol's art is listed by the object in that art, and a refresh runs it +/// where the symbol is placed. +#[test] +fn deferred_stages_in_symbol_art_are_listed_and_refreshed() { + let mut s = session(); + let a = rect(&mut s, 10.0, "#ff0000"); + let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string(); + install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.symbol", "effect", "{}"), &out)); + run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.deferred.symbol"})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let instance = run(&mut s, "symbol.new", json!({"name": "Deferred"}))["id"].as_u64().unwrap(); + let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000)); + let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step)); + s.doc_mut().unwrap().plugin_effects = fx.clone(); + fx.view(|| drawn(&s)); + fx.first_view_done(); + assert_eq!(fx.take_report(), Some(1)); + let effects = run(&mut s, "effect.deferredStatus", json!({}))["effects"].clone(); + let object = effects[0]["objectId"].as_u64().unwrap(); + assert_eq!(effects.as_array().map(Vec::len), Some(1), "{effects}"); + assert!(object != instance && s.doc().unwrap().doc.node(NodeId(object)).is_none(), "an object of the symbol's art: {effects}"); + + step.store(0, std::sync::atomic::Ordering::Relaxed); + assert_eq!(run(&mut s, "effect.refreshDeferred", json!({})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0})); + assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([])); +} + /// `CRAFT_PLUGIN_PAINTS_WASM=` saves a test live effect to try in the app /// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its /// object's stroke is 5 pt wide, and hands the geometry back otherwise. diff --git a/crates/engine/src/tests/prefs_file.rs b/crates/engine/src/tests/prefs_file.rs new file mode 100644 index 0000000000..7693ad0d5c --- /dev/null +++ b/crates/engine/src/tests/prefs_file.rs @@ -0,0 +1,169 @@ +//! Preferences files: `prefs.export` writes the preferences as JSON and `prefs.import` checks and +//! applies such a file. + +use serde_json::{Value, json}; +use vectorcraft_doc::Unit; + +use crate::cmd::prefscmds::{PREF_GROUPS, PREF_SPECS, PREFS_FORMAT}; +use crate::*; + +fn is_bad_params(r: Result) -> bool { + matches!(r, Err(EngineError::BadParams { .. })) +} + +/// Folder preferences, which a preferences file leaves out. +const FOLDERS: [&str; 4] = ["fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"]; + +/// A preferences file holding `prefs`, as `prefs.export` writes one. +fn file(prefs: Value) -> String { + json!({"format": PREFS_FORMAT, "version": 1, "prefs": prefs}).to_string() +} + +/// A session whose preferences differ from the defaults in every kind of value. +fn changed() -> Session { + let mut s = Session::new(); + let values = json!({ + "showToolTips": false, + "keyboardIncrement": 2.5, + "historyStates": 42, + "uiAccent": "green", + "guideColor": "#12ab34", + "unitsGeneral": "inches", + "eyedropper": {"sampleSize": 5}, + }); + s.execute("prefs.set", &json!({"values": values})).unwrap(); + s +} + +/// The preferences a preferences file holds, read from a session. +fn in_file(s: &Session) -> Value { + let all = s.prefs.to_json(); + let keys = PREF_SPECS.iter().map(|sp| sp.key).filter(|k| !FOLDERS.contains(k)).chain(PREF_GROUPS.iter().copied()); + Value::Object(keys.map(|k| (k.to_string(), all[k].clone())).collect()) +} + +#[test] +fn exported_preferences_import_unchanged() { + let mut s = changed(); + s.prefs.fonts_folder = "/fonts/here".into(); + let r = s.execute("prefs.export", &json!({})).unwrap(); + let text = r["data"].as_str().unwrap().to_string(); + let written: Value = serde_json::from_str(&text).unwrap(); + assert_eq!((written["format"].as_str(), written["version"].as_u64()), (Some(PREFS_FORMAT), Some(1))); + let prefs = written["prefs"].as_object().unwrap(); + assert_eq!(r["count"], json!(prefs.len())); + assert_eq!(prefs.len(), PREF_SPECS.len() - FOLDERS.len() + PREF_GROUPS.len()); + for k in FOLDERS { + assert!(!prefs.contains_key(k), "{k} is left out"); + } + assert!(!prefs.contains_key("printPresets"), "saved presets are left out"); + assert_eq!(prefs["uiAccent"], "green"); + + // Into a session with defaults and a document in millimeters. + let mut t = Session::new(); + t.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + t.execute("document.setUnits", &json!({"units": "Millimeters"})).unwrap(); + let undo = t.doc().unwrap().history.undo.len(); + let r = t.execute("prefs.import", &json!({"data": text})).unwrap(); + assert_eq!(r["imported"], json!(prefs.len())); + assert_eq!(in_file(&t), in_file(&s), "export then import gives the same preferences"); + assert_eq!(t.prefs.units_general, "inches"); + assert_eq!(t.doc().unwrap().doc.units, Unit::Millimeters, "the document's units stay as they are"); + assert_eq!(t.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(t.prefs.fonts_folder, "", "folders are not carried over"); + + // Through a file, too. + let path = std::env::temp_dir().join(format!("vc-prefs-{}.json", std::process::id())).to_string_lossy().to_string(); + assert_eq!(s.execute("prefs.export", &json!({"path": path})).unwrap()["path"], json!(path)); + let mut u = Session::new(); + u.execute("prefs.import", &json!({"path": path})).unwrap(); + let _ = std::fs::remove_file(&path); + assert_eq!(in_file(&u), in_file(&s)); +} + +/// A file written by hand, not by `prefs.export`: so the two sides cannot agree on a wrong layout. +#[test] +fn a_hand_written_file_sets_what_it_names_and_leaves_the_rest() { + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "historyStates", "value": 77})).unwrap(); + let text = r##"{ + "format": "vectorcraft-preferences", + "version": 1, + "prefs": {"uiAccent": "Violet", "keyboardIncrement": "3 pt", "guideColor": "#ABCDEF", "pathfinder": {}} + }"##; + assert_eq!(s.execute("prefs.import", &json!({"data": text})).unwrap(), json!({"imported": 4})); + assert_eq!(s.prefs.ui_accent, "violet"); + assert_eq!(s.prefs.keyboard_increment, 3.0); + assert_eq!(s.prefs.guide_color, "#abcdef"); + assert_eq!(s.prefs.history_states, 77, "a preference the file leaves out keeps its value"); +} + +#[test] +fn a_bad_preferences_file_is_refused_and_nothing_changes() { + let mut s = changed(); + let before = s.prefs.to_json().to_string(); + let too_large = " ".repeat((1 << 20) + 1); + let cases: Vec<(Value, &str)> = vec![ + (json!({"data": ""}), "not a preferences file"), + (json!({"data": "{\"format\": "}), "not a preferences file"), + (json!({"data": "[]"}), "not a preferences file: no JSON object"), + (json!({"data": "{\"version\": 1, \"prefs\": {}}"}), "no `format`"), + (json!({"data": "{\"format\": \"vcprintpresets\", \"version\": 1, \"prefs\": {}}"}), "(format `vcprintpresets`)"), + (json!({"data": "{\"format\": \"vectorcraft-preferences\", \"prefs\": {\"uiAccent\": \"blue\"}}"}), "no `version`"), + (json!({"data": "{\"format\": \"vectorcraft-preferences\", \"version\": 0, \"prefs\": {\"uiAccent\": \"blue\"}}"}), "no `version`"), + (json!({"data": file(json!({"uiAccent": "blue"})).replace("\"version\":1", "\"version\":2")}), "newer version of VectorCraft (version 2)"), + (json!({"data": "{\"format\": \"vectorcraft-preferences\", \"version\": 1}"}), "no `prefs`"), + (json!({"data": file(json!({}))}), "holds no preferences"), + (json!({"data": file(json!({"uiAccent": "blue", "noSuchPreference": 1}))}), "unknown preference `noSuchPreference`"), + (json!({"data": file(json!({"uiAccent": "blue", "showToolTips": 3}))}), "`showToolTips` must be true or false"), + (json!({"data": file(json!({"uiAccent": "blue", "historyStates": 5000}))}), "`historyStates` must be a whole number between 5 and 1000"), + (json!({"data": file(json!({"uiAccent": "blue", "eyedropper": 5}))}), "`eyedropper` must be an object"), + (json!({"data": file(json!({"uiAccent": "blue", "fontsFolder": "/fonts"}))}), "`fontsFolder` names a folder"), + (json!({"data": too_large}), "larger than 1 MB"), + (json!({"data": 5}), "`data` must be a string"), + (json!({"path": "/a.json", "data": file(json!({"uiAccent": "blue"}))}), "give `path` or `data`"), + (json!({}), "give `path` or `data`"), + ]; + for (params, says) in cases { + let r = s.execute("prefs.import", ¶ms); + let e = r.as_ref().map_err(ToString::to_string).unwrap_err(); + assert!(e.contains(says), "{params}: {e}"); + assert!(is_bad_params(r), "{params}"); + assert_eq!(s.prefs.to_json().to_string(), before, "{params}: nothing changes"); + } +} + +/// `prefs.import` as a step of a batch is an error, and the preferences stay as they are. +#[test] +fn prefs_import_is_refused_as_a_batch_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let before = s.prefs.to_json(); + let steps = json!({"commands": [{"command": "prefs.import", "params": {"data": file(json!({"uiAccent": "green"}))}}]}); + let e = s.execute("command.batch", &steps).unwrap_err().to_string(); + assert!(e.contains("`prefs.import` runs on its own"), "{e}"); + assert_eq!(s.prefs.to_json(), before); +} + +#[test] +fn a_file_over_the_limit_is_refused_before_it_is_parsed() { + let mut s = Session::new(); + let before = s.prefs.to_json().to_string(); + let path = std::env::temp_dir().join(format!("vc-prefs-large-{}.json", std::process::id())); + // A valid file padded past 1 MB: refused for its size, not read for its preferences. + let mut text = file(json!({"uiAccent": "pink"})); + text.push_str(&" ".repeat(1 << 20)); + std::fs::write(&path, text).unwrap(); + let e = s.execute("prefs.import", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string(); + let _ = std::fs::remove_file(&path); + assert!(e.contains("larger than 1 MB"), "{e}"); + assert_eq!(s.prefs.to_json().to_string(), before); + // Nor is such a file written: a preferences file over 1 MB could not be imported again. + s.prefs.hyphenation_exceptions = "x".repeat(1 << 20); + let e = s.execute("prefs.export", &json!({})).unwrap_err().to_string(); + assert!(e.contains("larger than 1 MB"), "{e}"); + s.prefs.hyphenation_exceptions.clear(); + let missing = std::env::temp_dir().join("vc-prefs-no-such-file.json"); + assert!(s.execute("prefs.import", &json!({"path": missing.to_string_lossy()})).is_err()); + assert_eq!(s.prefs.to_json().to_string(), before); +} diff --git a/crates/engine/src/tests/printadvanced.rs b/crates/engine/src/tests/printadvanced.rs index 99cfcd3733..8faa2f7adf 100644 --- a/crates/engine/src/tests/printadvanced.rs +++ b/crates/engine/src/tests/printadvanced.rs @@ -130,6 +130,28 @@ fn print_as_bitmap_prints_an_image_of_each_artboard() { assert!(crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().is_none()); } +/// Print as Bitmap of an artboard longer than the renderer draws at the raster effects resolution +/// (32,768 pixels a side) prints an image of all of it, at a lower resolution. +#[test] +fn print_as_bitmap_prints_all_of_a_long_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 9000, "height": 100})).unwrap(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 9000, "height": 100})).unwrap(); + let set = settings(json!({"advanced": {"printAsBitmap": true}})); + let saved = s.prefs.flattener_presets.clone(); + let bitmap = crate::cmd::printadvanced::prepare("file.print", doc(&s), &set, &saved, false).unwrap().unwrap(); + let mut placed = vec![]; + bitmap.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + placed.push((im.width, im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))))); + } + }); + let [(width, b)] = placed[..] else { panic!("one image: {placed:?}") }; + assert!(width <= vectorcraft_render::MAX_RASTER_SIDE, "{width} pixels"); + assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}"); +} + /// Appearance of Black › Printing / Exporting (#394): Print as Bitmap draws pure CMYK black as RGB /// black when `rich_black` is on. #[test] diff --git a/crates/engine/src/tests/script_console.rs b/crates/engine/src/tests/script_console.rs new file mode 100644 index 0000000000..985e5b810e --- /dev/null +++ b/crates/engine/src/tests/script_console.rs @@ -0,0 +1,264 @@ +//! The Script Console: `$.write` and `$.writeln`, `vc.log` lines, the bounded store of a session +//! and of a run, errors with their place, the end and report lines, and the diagnostics a run's +//! report holds. + +use serde_json::{Value, json}; + +use crate::script::console::{CUT_MARK, MAX_CONSOLE_BYTES, MAX_CONSOLE_LINES, MAX_LINE_BYTES, MAX_NAME_BYTES}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// The session console's `(run, kind, text)` lines. +fn lines(s: &mut Session) -> Vec<(u64, String, String)> { + let c = s.execute("script.console", &json!({})).unwrap(); + c["lines"] + .as_array() + .unwrap() + .iter() + .map(|l| (l["run"].as_u64().unwrap(), l["kind"].as_str().unwrap().to_string(), l["text"].as_str().unwrap().to_string())) + .collect() +} + +fn texts(s: &mut Session, kind: &str) -> Vec { + lines(s).into_iter().filter(|(_, k, _)| k == kind).map(|(_, _, t)| t).collect() +} + +#[test] +fn write_and_writeln_join_their_values_and_break_lines() { + let mut s = Session::new(); + run(&mut s, "$.write('a', 1, null, undefined, 1/0); $.write('b\\r\\nc\\rd\\n'); $.writeln(); $.write('x\\r'); $.write('\\ny'); $.writeln([1, 2], {}); $.write('p\\r'); $.write(''); $.write('\\nq'); $.writeln(); $.write('\\0\\t\\u2028\\x7f')").unwrap(); + let want = ["a1nullundefinedInfinityb", "c", "d", "", "x", "y1,2[object Object]", "p", "q", "\u{2400}\u{2409}\u{2424}\u{2421}"]; + assert_eq!(texts(&mut s, "output"), want); + let report = s.script_report().unwrap(); + assert_eq!(report["console"]["lines"], json!(want), "the run's own console holds the same output"); + assert_eq!(report["hostCallCounts"]["consoleWrites"], 11); +} + +#[test] +fn an_endless_writeln_stays_within_the_line_limit_and_counts_what_it_dropped() { + let mut s = Session::new(); + let e = s.execute("script.run", &json!({"source": "while (1) $.writeln('x')", "name": "t.js", "maxFuel": 2_000_000})).unwrap_err(); + assert!(e.to_string().ends_with("(limit)"), "{e}"); + let c = s.execute("script.console", &json!({})).unwrap(); + let kept = c["lines"].as_array().unwrap().len(); + assert_eq!(kept, MAX_CONSOLE_LINES); + let report = s.script_report().unwrap().clone(); + let writes = report["hostCallCounts"]["consoleWrites"].as_u64().unwrap(); + assert!(writes > MAX_CONSOLE_LINES as u64 * 2, "{writes} writes"); + // The session console holds a start line, the output, an error, an end and a report line. + assert_eq!(c["droppedLines"].as_u64().unwrap(), writes + 4 - MAX_CONSOLE_LINES as u64); + assert_eq!(report["console"]["lines"].as_array().unwrap().len(), MAX_CONSOLE_LINES); + assert_eq!(report["console"]["droppedLines"].as_u64().unwrap(), writes + 1 - MAX_CONSOLE_LINES as u64); + assert!(report["fuelUsed"].as_u64().unwrap() > 1_900_000); + assert_eq!(report["hostCalls"].as_u64().unwrap(), writes); + let tail = lines(&mut s); + let ends: Vec<&str> = tail.iter().rev().take(3).map(|(_, k, t)| if k == "error" { "error" } else { t.as_str() }).collect(); + assert_eq!(ends[1], "ended: fuel"); + assert_eq!(ends[2], "error", "{tail:?}"); +} + +#[test] +fn long_lines_stay_within_the_byte_limit() { + let mut s = Session::new(); + let source = "var l = new Array(4000).join('y'); for (var i = 0; i < 400; i++) $.writeln(l)"; + run(&mut s, source).unwrap(); + let c = s.execute("script.console", &json!({})).unwrap(); + let bytes: usize = c["lines"].as_array().unwrap().iter().map(|l| l["text"].as_str().unwrap().len()).sum(); + assert!(bytes <= MAX_CONSOLE_BYTES, "{bytes}"); + let kept = c["lines"].as_array().unwrap().len(); + assert!(kept < 400 && kept > 200, "{kept} lines"); + assert!(c["droppedLines"].as_u64().unwrap() > 100); +} + +#[test] +fn a_huge_line_is_cut_at_a_character_boundary_and_counted() { + let mut s = Session::new(); + run(&mut s, "$.writeln(new Array(5000).join('é')); $.write(new Array(3000).join('a')); $.write(new Array(3000).join('b')); $.writeln('c'); $.writeln('ok')") + .unwrap(); + let out = texts(&mut s, "output"); + assert_eq!(out.len(), 3); + for line in &out[..2] { + assert!(line.len() <= MAX_LINE_BYTES && line.len() > MAX_LINE_BYTES - 8, "{}", line.len()); + assert!(line.ends_with(CUT_MARK)); + } + assert!(!out[1].contains('c'), "the rest of a cut line is left out until it ends"); + assert_eq!(out[2], "ok"); + let c = s.execute("script.console", &json!({})).unwrap(); + assert_eq!(c["truncatedLines"], 2); + assert_eq!(s.script_report().unwrap()["console"]["truncatedLines"], 2); +} + +#[test] +fn a_long_script_name_is_cut_in_every_line_and_shows_its_control_characters() { + let mut s = Session::new(); + let name = format!("a\nb{}", "é".repeat(100_000)); + s.execute("script.run", &json!({"source": "$.writeln('x'); $.writeln('y')", "name": name})).unwrap(); + let c = s.execute("script.console", &json!({})).unwrap(); + let names: Vec<&str> = c["lines"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(names.len(), 5); + for n in names { + assert!(n.len() <= MAX_NAME_BYTES && n.len() > MAX_NAME_BYTES - 8, "{}", n.len()); + assert!(n.starts_with("a\u{240a}b") && n.ends_with(CUT_MARK), "{n}"); + } + assert_eq!(s.script_report().unwrap()["name"].as_str().map(str::len), Some(name.len()), "the report keeps the name given"); +} + +#[test] +fn an_uncaught_error_shows_the_script_its_line_and_column() { + let mut s = Session::new(); + run(&mut s, "$.write('half');\n\n throw new Error('boom\\nsecond');").unwrap_err(); + let all = lines(&mut s); + let kinds: Vec<&str> = all.iter().map(|(_, k, _)| k.as_str()).collect(); + assert_eq!(kinds, ["start", "output", "error", "error", "end", "report"]); + assert_eq!(all[1].2, "half", "a line left unended still shows"); + assert_eq!(all[2].2, "t.js:3:3: Error: boom"); + assert_eq!(all[3].2, "second"); + assert_eq!(all[4].2, "ended: error"); + let report = s.script_report().unwrap(); + assert_eq!(report["console"]["lines"], json!(["half", "t.js:3:3: Error: boom", "second"])); + let mut s = Session::new(); + run(&mut s, "var = 1").unwrap_err(); + assert!(texts(&mut s, "error")[0].starts_with("t.js:1:"), "a syntax error has its place too"); + let mut s = Session::new(); + s.script_frames = true; + run(&mut s, "while (true) {}").unwrap(); + s.script_abandon(); + assert_eq!(texts(&mut s, "error"), ["t.js: location unavailable: limit reached: Interrupted"]); +} + +#[test] +fn the_result_and_the_report_agree_and_count_each_kind_of_host_call() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let source = "vc.run('shape.rectangle', {x:0,y:0,width:5,height:5}); vc.run('shape.rectangle', {x:9,y:0,width:5,height:5}); \ + try { vc.run('no.such', {}); } catch (e) {} var d = vc.document; var c = vc.commands; vc.log({a: 1}); vc.log('two\\nlines'); $.writeln('w');"; + let r = run(&mut s, source).unwrap(); + assert_eq!(&r, s.script_report().unwrap()); + assert_eq!(r["hostCallCounts"], json!({"vcRun": 3, "documentReads": 1, "commandListReads": 1, "vcLog": 2, "consoleWrites": 1})); + assert_eq!(r["timingAvailable"], true); + assert!(r["runTimeMs"].is_u64()); + let slow = r["slowestCommands"].as_array().unwrap(); + assert_eq!(slow.len(), 1, "an unknown command is not timed: {slow:?}"); + assert_eq!((slow[0]["id"].as_str(), slow[0]["calls"].as_u64()), (Some("shape.rectangle"), Some(2))); + assert!(slow[0]["maxMs"].as_u64() <= slow[0]["totalMs"].as_u64()); + assert_eq!(r["console"]["lines"], json!(["{\"a\":1}", "two", "lines", "w"])); + assert_eq!(texts(&mut s, "log"), ["{\"a\":1}", "two", "lines"]); + assert_eq!(texts(&mut s, "end"), ["ended: finished"]); + assert!(texts(&mut s, "report")[0].contains("host calls; slowest: shape.rectangle ×2"), "{:?}", texts(&mut s, "report")); + assert_eq!(r["log"], json!([{"a": 1}, "two\nlines"]), "the log keeps its values"); +} + +#[test] +fn a_stopped_run_reports_its_diagnostics_and_its_unended_line() { + let mut s = Session::new(); + s.script_frames = true; + run(&mut s, "$.write('so far'); vc.log(1); while (true) {}").unwrap(); + assert!(s.script_pump().is_none()); + assert_eq!(texts(&mut s, "log"), ["1"], "a line shows while the run goes on"); + s.execute("script.stop", &json!({})).unwrap(); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!(report["kind"], "stopped"); + for key in ["runTimeMs", "hostCallCounts", "slowestCommands", "console", "fuelUsed", "hostCalls", "timingAvailable"] { + assert!(!report[key].is_null(), "{key}: {report}"); + } + assert_eq!(report["hostCalls"], 2); + assert_eq!(texts(&mut s, "output"), ["so far"]); + assert_eq!(texts(&mut s, "end"), ["ended: stopped"]); +} + +/// A report line counts one host call in the singular, and gives a run without a clock as "time +/// unavailable". +#[test] +fn a_report_line_counts_one_host_call_in_the_singular_and_says_when_time_is_unavailable() { + use crate::script::console::{Entry, Slow}; + let report = |ms: Option, host_calls: u64| Entry::Report { ms, host_calls, slowest: vec![] }.text(); + assert_eq!(report(Some(3), 0), "3 ms, 0 host calls"); + assert_eq!(report(Some(3), 1), "3 ms, 1 host call"); + assert_eq!(report(Some(0), 2), "0 ms, 2 host calls"); + assert_eq!(report(None, 0), "time unavailable, 0 host calls"); + assert_eq!(report(None, 1), "time unavailable, 1 host call"); + assert_eq!(report(None, 2), "time unavailable, 2 host calls"); + let slowest = vec![Slow { id: "a.b".into(), calls: 1, total_ms: 4, max_ms: 4 }]; + assert_eq!(Entry::Report { ms: None, host_calls: 1, slowest }.text(), "time unavailable, 1 host call; slowest: a.b ×1 4 ms"); +} + +/// A run whose job is gone still ends its console entry, once, with its own number and name and no +/// report line: as stopped when it is abandoned, as an internal fault when a slice finds it gone. +/// The session can start the next run. +#[test] +fn a_run_whose_job_is_gone_still_ends_its_console_entry() { + for abandon in [true, false] { + let mut s = Session::new(); + s.script_frames = true; + run(&mut s, "$.writeln('one'); while (true) {}").unwrap(); + assert!(s.script_pump().is_none()); + assert!(script::forget_job(&s)); + if abandon { + assert!(s.script_abandon()); + } else { + let e = s.script_pump().unwrap().unwrap_err(); + assert_eq!(e.to_string(), "the script's run is no longer available"); + } + assert!(!s.script_running()); + let all = lines(&mut s); + let kinds: Vec<&str> = all.iter().map(|(_, k, _)| k.as_str()).collect(); + assert_eq!(kinds, ["start", "output", "end"], "{all:?}"); + assert_eq!(all[2].2, if abandon { "ended: stopped" } else { "ended: internal" }); + let c = s.execute("script.console", &json!({})).unwrap(); + assert_eq!((c["lines"][2]["run"].as_u64(), c["lines"][2]["name"].as_str()), (Some(1), Some("t.js"))); + assert!(!s.script_abandon() && s.script_pump().is_none(), "nothing is left to end"); + assert_eq!(lines(&mut s).len(), 3, "the entry ends once"); + s.script_frames = false; + run(&mut s, "$.writeln('two')").unwrap(); + assert_eq!(texts(&mut s, "end").last().map(String::as_str), Some("ended: finished"), "the next run starts"); + assert_eq!(lines(&mut s).last().map(|l| l.0), Some(2)); + } +} + +#[test] +fn runs_are_numbered_a_busy_run_adds_nothing_and_clear_keeps_the_report() { + let mut s = Session::new(); + for _ in 0..3 { + run(&mut s, "for (var i = 0; i < 1000; i++) $.writeln(i)").unwrap(); + } + let all = lines(&mut s); + assert_eq!(all.len(), MAX_CONSOLE_LINES); + assert_eq!(all.last().map(|l| l.0), Some(3)); + s.script_frames = true; + run(&mut s, "$.writeln('four'); while (true) {}").unwrap(); + assert!(s.script_pump().is_none()); + let before = lines(&mut s); + assert!(matches!(run(&mut s, "$.writeln('five')"), Err(EngineError::Busy))); + assert_eq!(lines(&mut s), before, "a refused run adds no line"); + assert_eq!(s.execute("script.console.clear", &json!({})).unwrap()["cleared"], MAX_CONSOLE_LINES); + let c = s.execute("script.console", &json!({})).unwrap(); + assert_eq!((c["lines"].as_array().map(Vec::len), c["droppedLines"].as_u64()), (Some(0), Some(0))); + s.execute("script.stop", &json!({})).unwrap(); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!(report["console"]["lines"][0], "four", "a clear leaves the running script's own console"); + assert_eq!(texts(&mut s, "end"), ["ended: stopped"], "the run goes on writing after a clear"); + assert_eq!(lines(&mut s)[0].0, 4); + let mut other = Session::new(); + assert!(lines(&mut other).is_empty(), "each session has its own console"); +} + +#[test] +fn the_slowest_commands_are_the_longest_in_all_then_by_id() { + let times = std::collections::HashMap::from([ + ("a.one", (1, 5_000_000, 5_000_000)), + ("b.two", (3, 9_000_000, 4_000_000)), + ("c.three", (1, 5_000_000, 5_000_000)), + ("d", (1, 1, 1)), + ("e", (1, 2, 2)), + ("f", (1, 3, 3)), + ]); + let slow = script::slowest(×); + let ids: Vec<&str> = slow.iter().map(|c| c.id.as_str()).collect(); + assert_eq!(ids, ["b.two", "a.one", "c.three", "f", "e"]); + assert_eq!((slow[0].calls, slow[0].total_ms, slow[0].max_ms), (3, 9, 4)); +} diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs new file mode 100644 index 0000000000..7572ca52f0 --- /dev/null +++ b/crates/engine/src/tests/script_dialogs.rs @@ -0,0 +1,289 @@ +//! `alert`, `confirm` and `prompt` in a script: their arguments and results, the answers a run with +//! nobody to ask takes from `answers`, the wait in the app, Stop, and the report's `dialogs`. + +use serde_json::{Value, json}; + +use crate::script::{DialogAnswer, DialogKind, ScriptDialog, dialogs}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn art(s: &Session) -> (String, usize) { + let d = &s.documents()[0]; + (format!("{:?}", d.doc.layers), d.history.undo.len()) +} + +fn headless(s: &mut Session, source: &str, answers: Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "d.js", "answers": answers})) +} + +/// A run in the app of `source`, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "d.js"})).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +fn answers(list: &[Value]) -> Value { + Value::Array(list.to_vec()) +} + +#[test] +fn notification_signatures_and_returns() { + let mut s = one_doc(); + let source = "vc.log(typeof alert('a')); alert(42, 'Title', 1);\ + vc.log(confirm('c')); vc.log(confirm('n', true, undefined));\ + vc.log(prompt('p', 'pre')); vc.log(prompt({toString: function () { return 'own'; }}, '', 'T'));"; + let r = headless( + &mut s, + source, + answers(&[ + json!({"kind": "alert", "value": "ok"}), + json!({"kind": "alert", "value": "ok"}), + json!({"kind": "confirm", "value": true}), + json!({"kind": "confirm", "value": false}), + json!({"kind": "prompt", "value": "typed"}), + json!({"kind": "prompt", "value": null}), + ]), + ) + .unwrap(); + assert_eq!(r["log"], json!(["undefined", true, false, "typed", null]), "{r}"); + assert_eq!( + r["dialogs"], + json!([ + {"kind": "alert", "message": "a", "title": "Script Alert", "errorIcon": false, "answer": "ok"}, + {"kind": "alert", "message": "42", "title": "Title", "errorIcon": true, "answer": "ok"}, + {"kind": "confirm", "message": "c", "title": "Script Alert", "noAsDefault": false, "answer": true}, + {"kind": "confirm", "message": "n", "title": "Script Alert", "noAsDefault": true, "answer": false}, + {"kind": "prompt", "message": "p", "title": "Script Alert", "preset": "pre", "answer": "typed"}, + {"kind": "prompt", "message": "own", "title": "T", "preset": "", "answer": null}, + ]) + ); + assert_eq!((r["dialogCount"].clone(), r["dialogsTruncated"].clone()), (json!(6), json!(false))); + let has = headless(&mut s, "vc.log(vc.api.has('dialogs'));", json!([])).unwrap(); + assert_eq!(has["log"], json!([true])); +} + +#[test] +fn headless_answers_follow_call_order() { + let mut s = one_doc(); + let source = "var out = []; [1, 2].forEach(function (i) { out.push(confirm('q' + i)); }); out.push(prompt('r', 'x')); vc.log(out.join());"; + let r = headless( + &mut s, + source, + answers(&[json!({"kind": "confirm", "value": false}), json!({"kind": "confirm", "value": true}), json!({"kind": "prompt", "value": "z"})]), + ) + .unwrap(); + assert_eq!(r["log"], json!(["false,true,z"]), "a callback of a built-in takes its answer too: {r}"); + assert_eq!(headless(&mut s, "1", json!({})).unwrap()["dialogCount"], 0, "an empty object is an empty list"); +} + +#[test] +fn missing_or_mismatched_answer_rolls_back() { + let mut s = one_doc(); + let before = art(&s); + let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + for (source, given, says) in [ + (format!("{edit} try {{ alert('x'); }} catch (e) {{ vc.log('caught'); }}"), json!([]), "no answer left"), + (format!("{edit} alert('x');"), answers(&[json!({"kind": "confirm", "value": true})]), "is for confirm, not alert"), + (format!("{edit} alert('x');"), answers(&[json!({"kind": "alert", "value": "ok"}), json!({"kind": "alert", "value": "ok"})]), "1 answer"), + ] { + let e = headless(&mut s, &source, given).unwrap_err().to_string(); + assert!(e.contains(says), "{e}"); + assert_eq!(art(&s), before, "{source}"); + let report = s.script_report().unwrap(); + assert_eq!(report["kind"], "limit", "{report}"); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught"); + assert_eq!(report["dialogCount"], 1); + } + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "ok"); + headless(&mut s, "alert('x')", json!([])).unwrap_err(); + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing"); +} + +#[test] +fn invalid_answers_are_rejected_before_run() { + let mut s = one_doc(); + let before = art(&s); + let many: Vec = (0..=dialogs::MAX_ANSWERS).map(|_| json!({"kind": "alert", "value": "ok"})).collect(); + let big: Vec = (0..80).map(|_| json!({"kind": "prompt", "value": "x".repeat(16_000)})).collect(); + for given in [ + json!({"a": 1}), + json!("ok"), + json!([1]), + json!([{"kind": "alert"}]), + json!([{"kind": "alert", "value": true}]), + json!([{"kind": "confirm", "value": "yes"}]), + json!([{"kind": "prompt", "value": 3}]), + json!([{"kind": "prompt", "value": "x".repeat(dialogs::MAX_PROMPT_BYTES + 1)}]), + json!([{"kind": "other", "value": "ok"}]), + json!([{"kind": "alert", "value": "ok", "extra": 1}]), + Value::Array(many), + Value::Array(big), + ] { + let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + let r = s.execute("script.run", &json!({"source": source, "answers": given})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}"); + assert_eq!(art(&s), before); + } + s.script_frames = true; + let r = s.execute("script.run", &json!({"source": "1", "answers": [{"kind": "alert", "value": "ok"}]})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "a run in the app takes no answers: {r:?}"); + assert!(!s.script_running()); +} + +#[test] +fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { + let mut s = one_doc(); + framed( + &mut s, + "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); var a = confirm('Go?', true, 'Ask'); var b = prompt('Name', 'n'); vc.log([a, b]);", + ); + let want = ScriptDialog { + kind: DialogKind::Confirm, + message: "Go?".into(), + title: Some("Ask".into()), + error_icon: false, + no_as_default: true, + preset: String::new(), + }; + assert_eq!(s.script_dialog(), Some(want)); + assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert!(!s.script_answer(DialogAnswer::Confirm(true)), "nothing waits until the run goes on"); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_dialog().unwrap().preset, "n"); + assert!(!s.script_answer(DialogAnswer::Prompt(Some("x".repeat(dialogs::MAX_PROMPT_BYTES + 1))))); + assert!(s.script_answer(DialogAnswer::Prompt(Some("Ann".into())))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, "Ann"]])); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a finished run is one undo step"); + assert_eq!(r["dialogs"][1]["answer"], "Ann"); +} + +#[test] +fn prompt_cancel_returns_null() { + let mut s = one_doc(); + framed(&mut s, "vc.log(prompt('Name', '') === null);"); + assert!(s.script_answer(DialogAnswer::Prompt(None))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([true])); +} + +#[test] +fn dialog_loop_stops_or_exhausts() { + let mut s = one_doc(); + let before = art(&s); + let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); while (1) { alert('x'); }"; + let three: Vec = (0..3).map(|_| json!({"kind": "alert", "value": "ok"})).collect(); + let e = headless(&mut s, source, Value::Array(three)).unwrap_err().to_string(); + assert!(e.contains("no answer left"), "{e}"); + assert_eq!(s.script_report().unwrap()["dialogCount"], 4); + assert_eq!(art(&s), before); + framed(&mut s, source); + for _ in 0..3 { + assert!(s.script_answer(DialogAnswer::Ok)); + assert!(pump(&mut s).is_none()); + } + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert_eq!(s.script_dialog(), None, "a run asked to stop no longer waits"); + assert!(!s.script_answer(DialogAnswer::Ok)); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), report["dialogCount"].as_u64()), (Some("stopped"), Some(4)), "{report}"); + assert_eq!(report["dialogs"][3]["answer"], "stop"); + assert_eq!(art(&s), before, "Stop at the first or any later dialog leaves no undo step"); + framed(&mut s, source); + assert!(s.script_abandon(), "quitting while a dialog waits abandons the run"); + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "stop"); + assert_eq!(art(&s), before); +} + +#[test] +fn dialog_text_limits_and_controls() { + let mut s = one_doc(); + let source = format!( + "var out = [];\ + function t(f) {{ try {{ f(); out.push('opened'); }} catch (e) {{ out.push(e.name); }} }}\ + t(function () {{ alert('x'); }});\ + t(function () {{ alert(new Array({m}).join('m')); }});\ + t(function () {{ alert('m', new Array({t}).join('t')); }});\ + t(function () {{ prompt('m', new Array({m}).join('p')); }});\ + t(function () {{ alert(); }});\ + t(function () {{ prompt('m'); }});\ + t(function () {{ alert({{toString: function () {{ throw new Error('no'); }}}}); }});\ + t(function () {{ alert(undefined); }});\ + vc.log(out.join());", + m = dialogs::MAX_MESSAGE_BYTES + 2, + t = dialogs::MAX_TITLE_BYTES + 2, + ); + let r = headless(&mut s, &source, answers(&[json!({"kind": "alert", "value": "ok"}), json!({"kind": "alert", "value": "ok"})])).unwrap(); + assert_eq!(r["log"], json!(["opened,RangeError,RangeError,RangeError,TypeError,TypeError,Error,opened"]), "{r}"); + assert_eq!(r["dialogs"][1]["message"], "undefined", "an explicit undefined message is a message"); + assert_eq!(dialogs::shown_text("a\r\nb\rc\nd\te\u{7}\u{7f}", true), "a\nb\nc\nd\u{2409}e\u{2407}\u{2421}"); + assert_eq!(dialogs::shown_text("a\nb", false), "a\u{240a}b", "a title stays on one line"); + assert_eq!(dialogs::cut_to("aé", 2), "a", "a cut keeps whole characters"); +} + +#[test] +fn dialog_transcript_on_success_and_failure() { + let mut s = one_doc(); + let r = headless(&mut s, "alert('one'); throw new Error('later');", answers(&[json!({"kind": "alert", "value": "ok"})])).unwrap_err(); + assert!(r.to_string().contains("later")); + let report = s.script_report().unwrap(); + assert_eq!(report["dialogs"], json!([{"kind": "alert", "message": "one", "title": "Script Alert", "errorIcon": false, "answer": "ok"}])); + let ok = headless(&mut s, "1", json!([])).unwrap(); + assert_eq!((ok["dialogs"].clone(), ok["dialogCount"].clone()), (json!([]), json!(0))); +} + +#[test] +fn dialog_wait_does_not_spend_fuel() { + let mut s = one_doc(); + framed(&mut s, "alert('x'); 1"); + for _ in 0..20 { + assert!(s.script_pump().is_none(), "the run waits"); + } + assert!(s.script_answer(DialogAnswer::Ok)); + let r = pump(&mut s).unwrap().unwrap(); + let mut t = one_doc(); + let plain = headless(&mut t, "alert('x'); 1", answers(&[json!({"kind": "alert", "value": "ok"})])).unwrap(); + assert_eq!((r["fuelUsed"].clone(), r["hostCalls"].clone()), (plain["fuelUsed"].clone(), plain["hostCalls"].clone()), "{r}"); +} + +#[test] +fn second_run_is_busy_while_dialog_waits() { + let mut s = one_doc(); + framed(&mut s, "alert('x');"); + assert!(s.execute("script.run", &json!({"source": "1"})).is_err()); + assert!(s.script_dialog().is_some(), "the first run still waits"); + assert!(s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 1, "height": 1})).is_err(), "edits are refused while it waits"); +} + +#[test] +fn a_dialog_in_a_callback_throws_in_the_app() { + let mut s = one_doc(); + s.script_frames = true; + let source = "var m = ''; [1].forEach(function () { try { alert('x'); } catch (e) { m = e.message; } }); vc.log(m);"; + s.execute("script.run", &json!({"source": source})).unwrap(); + let r = pump(&mut s).unwrap().unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}"); + assert_eq!(r["dialogCount"], 0); +} diff --git a/crates/engine/src/tests/script_dollar.rs b/crates/engine/src/tests/script_dollar.rs new file mode 100644 index 0000000000..d5b9624500 --- /dev/null +++ b/crates/engine/src/tests/script_dollar.rs @@ -0,0 +1,247 @@ +//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize` and +//! `toSource`, and what of them one run keeps to itself. + +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::script::{TEST_ELAPSED, TEST_NO_CLOCK}; +use crate::*; + +/// The values `source` gives `vc.log`, in a run of its text. +fn logged(s: &mut Session, source: &str) -> Value { + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_or_else(|e| panic!("{source}: {e}"))["log"].clone() +} + +/// The one value `expr` gives, logged. +fn value(s: &mut Session, expr: &str) -> Value { + logged(s, &format!("vc.log({expr});"))[0].clone() +} + +/// The name of the error `statement` throws and its message, as `Name: message`. +fn thrown(s: &mut Session, statement: &str) -> String { + value(s, &format!("(function () {{ try {{ {statement}; return 'no error'; }} catch (e) {{ return e.name + ': ' + e.message; }} }})()")) + .as_str() + .unwrap_or_default() + .to_string() +} + +#[test] +fn each_member_has_its_value() { + let mut s = Session::new(); + let version = env!("CARGO_PKG_VERSION"); + let os = 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" + }; + for (expr, want) in [ + ("$.about()", json!(format!("VectorCraft script engine {version}"))), + ("$.appEncoding", json!("UTF-8")), + ("$.build", json!(version)), + ("$.buildDate", json!(null)), + ("$.decimalPoint", json!(".")), + ("$.engineName", json!("VectorCraft")), + ("$.error", json!(null)), + ("$.flags", json!(0)), + ("$.gc() === undefined", json!(true)), + ("$.global === this", json!(true)), + ("typeof $.hiresTimer === 'number' && $.hiresTimer >= 0", json!(true)), + ("$.level", json!(0)), + ("\n$.line", json!(2)), + ("$.locale", json!("en")), + ("$.localize", json!(false)), + ("$.memCache", json!(0)), + ("$.os", json!(os)), + ("$.screens.length", json!(0)), + ("$.stack", json!("[global]:1\n")), + ("$.strict", json!(false)), + ("$.version", json!(version)), + ("typeof $.getenv + typeof $.setenv + typeof $.sleep", json!("functionfunctionfunction")), + ("vc.api.has('dollar')", json!(true)), + ] { + assert_eq!(value(&mut s, expr), want, "{expr}"); + } + assert_eq!(thrown(&mut s, "$.bp()"), "Error: $.bp: scripts here have no debugger"); + assert_eq!(thrown(&mut s, "$.colorPicker(0)"), "Error: $.colorPicker: scripts cannot show a dialog yet"); +} + +#[test] +fn read_only_members_keep_their_values_and_settable_ones_check_what_they_are_given() { + let mut s = Session::new(); + assert_eq!(value(&mut s, "($.build = 'x', $.level = 3, $.os = 'y', [$.build === 'x', $.level, $.os === 'y'])"), json!([false, 0, false])); + assert!(thrown(&mut s, "(function () { 'use strict'; $.version = '9'; })()").starts_with("TypeError")); + assert!(thrown(&mut s, "(function () { 'use strict'; $.error = null; })()").starts_with("TypeError")); + assert_eq!(value(&mut s, "($.appEncoding = 'utf-8', $.appEncoding)"), json!("UTF-8")); + assert!(thrown(&mut s, "$.appEncoding = 'ISO-8859-1'").starts_with("RangeError")); + assert!(thrown(&mut s, "$.appEncoding = 8").starts_with("TypeError")); + assert!(thrown(&mut s, "$.memCache = 1024").starts_with("Error")); + assert_eq!(value(&mut s, "($.flags = 512, [$.flags, $.localize])"), json!([512, true])); + assert_eq!(value(&mut s, "($.flags = 512, $.flags = 0, [$.flags, $.localize])"), json!([0, false])); + for bad in ["$.flags = 2", "$.flags = 513", "$.flags = -512"] { + assert!(thrown(&mut s, bad).starts_with("RangeError"), "{bad}"); + } + assert!(thrown(&mut s, "$.flags = '512'").starts_with("TypeError")); + assert!(thrown(&mut s, "$.localize = 1").starts_with("TypeError")); +} + +#[test] +fn the_locale_starts_as_the_interfaces_and_a_change_lasts_one_run() { + let mut s = Session::new(); + for (ui, want) in [("de", "de"), ("pt-br", "pt_BR"), ("zh-hant", "zh_TW"), ("zh-hans", "zh_CN"), ("auto", "en"), ("x", "en")] { + s.ui_language = Some(ui.into()); + assert_eq!(value(&mut s, "$.locale"), json!(want), "{ui}"); + } + s.ui_language = None; + s.prefs.interface_language = "fr".into(); + assert_eq!(value(&mut s, "$.locale"), json!("fr"), "without a language from the app, the preference"); + s.ui_language = Some("de".into()); + let lookup = "localize({en: 'e', de: 'd', fr: 'f', fr_CA: 'c'})"; + assert_eq!(value(&mut s, &format!("[{lookup}, $.decimalPoint]")), json!(["d", ","])); + let changed = format!( + "$.locale = 'FR-ca'; var a = [$.locale, {lookup}]; $.locale = 'fr'; a.push({lookup}); $.locale = null; a.push($.locale, {lookup}); a" + ); + assert_eq!(value(&mut s, &format!("(function () {{ {changed}; return a; }})()")), json!(["fr_CA", "c", "f", "de", "d"])); + assert_eq!(value(&mut s, "($.locale = '', $.locale)"), json!("de"), "an empty locale is the interface's"); + assert_eq!(value(&mut s, "($.locale = 'en_US', $.locale)"), json!("en_US")); + assert_eq!(value(&mut s, "$.locale"), json!("de"), "the next run starts with the interface's again"); + for bad in ["$.locale = 'german'", "$.locale = 'de_DE_x'", "$.locale = 'd'"] { + assert!(thrown(&mut s, bad).starts_with("RangeError"), "{bad}"); + } + assert!(thrown(&mut s, "$.locale = 5").starts_with("TypeError")); +} + +#[test] +fn localized_to_string_is_on_only_while_the_run_turns_it_on() { + let mut s = Session::new(); + s.ui_language = Some("de".into()); + let text = "String({en: 'Open', de: 'Öffnen'})"; + assert_eq!(value(&mut s, text), json!("[object Object]")); + assert_eq!(value(&mut s, &format!("($.localize = true, {text})")), json!("Öffnen")); + assert_eq!(value(&mut s, text), json!("[object Object]"), "the next run starts with it off"); + assert_eq!(value(&mut s, "localize('%1 of %2', 3, 7)"), json!("3 of 7"), "localize works with it off"); +} + +#[test] +fn to_source_writes_plain_data() { + let mut s = Session::new(); + assert_eq!(value(&mut s, "toSource({a: [1, 'x'], b: null})"), json!(r#"({"a":[1, "x"], "b":null})"#)); + assert_eq!(value(&mut s, "[true, 2].toSource()"), json!("[true, 2]")); + assert!(thrown(&mut s, "var o = {}; o.o = o; toSource(o)").starts_with("TypeError")); + assert!(thrown(&mut s, "toSource(vc)").starts_with("TypeError"), "a host object is not plain data"); +} + +#[test] +fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() { + let mut s = Session::new(); + for name in ["HOME", "PATH", "USERPROFILE", "TEMP", "lang", ""] { + assert_eq!(value(&mut s, &format!("$.getenv('{name}')")), json!(null), "{name}"); + } + let process = std::env::var("OS").ok(); + let before = value(&mut s, "$.getenv('OS')"); + if let Some(os) = process.as_deref().filter(|v| v.len() <= 64 && v.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-@".contains(&b))) { + assert_eq!(before, json!(os)); + } + assert_eq!(value(&mut s, "($.setenv('OS', 'Test-1'), $.getenv('OS'))"), json!("Test-1")); + assert_eq!(std::env::var("OS").ok(), process, "the process's environment stays as it was"); + assert_eq!(value(&mut s, "$.getenv('OS')"), before, "the next run reads the process's value again"); + assert!(thrown(&mut s, "$.setenv('HOME', 'x')").starts_with("Error")); + assert!(thrown(&mut s, "$.setenv('LANG', 'a b')").starts_with("RangeError")); + assert!(thrown(&mut s, &format!("$.setenv('LANG', '{}')", "a".repeat(65))).starts_with("RangeError")); + assert!(thrown(&mut s, "$.setenv('LANG')").starts_with("TypeError")); + assert!(thrown(&mut s, "$.getenv(1)").starts_with("TypeError")); +} + +#[test] +fn error_line_and_stack_follow_the_running_code() { + let mut s = Session::new(); + let source = "try { null.x; } catch (e) {}\nfunction where() {\n return [$.line, $.stack, $.error instanceof TypeError];\n}\nvc.log(where());"; + assert_eq!(logged(&mut s, source)[0], json!([3, "[global]:5\nwhere:3\n", true])); + assert_eq!(value(&mut s, "$.error"), json!(null), "each run starts without one"); +} + +#[test] +fn sleep_waits_between_slices_until_its_time_has_passed() { + let mut s = Session::new(); + s.script_frames = true; + TEST_ELAPSED.set(Some(Duration::ZERO)); + s.execute("script.run", &json!({"source": "vc.log(1); $.sleep(250); vc.log(2);", "name": "t.js"})).unwrap(); + let logs = + |s: &mut Session| s.execute("script.console", &json!({})).unwrap()["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "log").count(); + assert!(s.script_pump().is_none()); + assert_eq!(logs(&mut s), 1); + TEST_ELAPSED.set(Some(Duration::from_millis(249))); + assert!(s.script_pump().is_none()); + assert!(s.script_pump().is_none()); + assert_eq!(logs(&mut s), 1, "the run waits"); + assert_eq!(s.script_sleep_left(), Some(Duration::from_millis(1)), "the app can wait this long before the next frame"); + TEST_ELAPSED.set(Some(Duration::from_millis(250))); + let r = s.script_pump().unwrap().unwrap(); + assert_eq!(r["log"], json!([1, 2])); + TEST_ELAPSED.set(None); +} + +#[test] +fn a_sleeping_run_stops_when_asked() { + let mut s = Session::new(); + s.script_frames = true; + TEST_ELAPSED.set(Some(Duration::ZERO)); + s.execute("script.run", &json!({"source": "$.sleep(1000); vc.log(2);", "name": "t.js"})).unwrap(); + assert!(s.script_pump().is_none()); + assert_eq!(s.script_sleep_left(), Some(Duration::from_secs(1))); + s.execute("script.stop", &json!({})).unwrap(); + assert_eq!(s.script_sleep_left(), None, "a run asked to stop does not wait"); + assert!(s.script_pump().unwrap().is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + TEST_ELAPSED.set(None); +} + +#[test] +fn sleep_takes_milliseconds_from_0_to_1000() { + let mut s = Session::new(); + assert_eq!(value(&mut s, "($.sleep(0), $.sleep(1), 'woke')"), json!("woke")); + for bad in ["$.sleep(-1)", "$.sleep(1001)"] { + assert!(thrown(&mut s, bad).starts_with("RangeError"), "{bad}"); + } + for bad in ["$.sleep()", "$.sleep('5')", "$.sleep(NaN)", "$.sleep(Infinity)"] { + assert!(thrown(&mut s, bad).starts_with("TypeError"), "{bad}"); + } +} + +#[test] +fn sleep_throws_where_the_run_cannot_wait_instead_of_running_on() { + let mut s = Session::new(); + s.script_frames = true; + TEST_ELAPSED.set(Some(Duration::ZERO)); + let source = "var o = {}; Object.defineProperty(o, 'x', { get: function () { $.sleep(250); vc.log('after'); return 1; } }); + try { o.x; } catch (e) { vc.log(e.name + ': ' + e.message); } + try { [1].map(function () { $.sleep(250); vc.log('after'); }); } catch (e) { vc.log(e.name + ': ' + e.message); } + [1].map(function () { $.sleep(0); }); + vc.log('done');"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + let r = s.script_pump().expect("the run does not wait").unwrap(); + TEST_ELAPSED.set(None); + let message = "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"; + assert_eq!(r["log"], json!([message, message, "done"])); +} + +#[test] +fn sleep_throws_where_the_run_cannot_wait_without_a_clock_too() { + let mut s = Session::new(); + TEST_NO_CLOCK.set(true); + let source = "var o = {}; Object.defineProperty(o, 'x', { get: function () { $.sleep(250); return 1; } }); + try { o.x; vc.log('no error'); } catch (e) { vc.log(e.name); } + $.sleep(250); + vc.log('done');"; + let log = logged(&mut s, source); + TEST_NO_CLOCK.set(false); + assert_eq!(log, json!(["Error", "done"]), "the script's own code does not wait without a clock"); +} diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs new file mode 100644 index 0000000000..b176b4f143 --- /dev/null +++ b/crates/engine/src/tests/script_folder.rs @@ -0,0 +1,324 @@ +//! The Scripts folder: what a listing holds and leaves out, its order and labels, its limits, the +//! read of a listed script, `script.listInstalled` and the automation read root. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde_json::json; + +use crate::script::folder::{self, Entry, Limits, Listing}; +use crate::*; + +/// A fresh folder for the files of test `name`, holding an empty `Scripts` folder. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-script-folder-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Scripts")).unwrap(); + dir +} + +/// Writes the empty file `name` (folders included) under `root`. +fn touch(root: &Path, name: &str) -> PathBuf { + let path = root.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, "").unwrap(); + path +} + +/// Makes `link` lead to the folder `target`: a symbolic link, or on Windows a junction, which needs +/// no privilege. +fn link_folder(target: &Path, link: &Path) { + #[cfg(unix)] + std::os::unix::fs::symlink(target, link).unwrap(); + #[cfg(windows)] + { + let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().unwrap(); + assert!(made.status.success(), "mklink /J: {}", String::from_utf8_lossy(&made.stderr)); + } +} + +/// A listing's rows as text: `label`, or `label/` followed by the folder's rows in brackets. +fn rows(entries: &[Entry]) -> String { + let row = |e: &Entry| match e { + Entry::Script { label, .. } => label.clone(), + Entry::Folder { label, entries } => format!("{label}/[{}]", rows(entries)), + }; + entries.iter().map(row).collect::>().join(", ") +} + +/// A listing within `limits` that takes no time. +fn list(root: &Path, limits: Limits) -> Listing { + folder::list_with(root, &limits, &mut || Duration::ZERO) +} + +#[test] +fn scripts_and_subfolders_are_listed_by_name_without_the_extension() { + let dir = folder("names"); + let root = dir.join("Scripts"); + for name in + ["b.js", "A.JSX", "Dessin (été) #1.jsx", "v1.2 draft.Js", "Zeta/inner.jsx", "Zeta/Deep/x.js", "notes.txt", "x.jsxbin", "lib.jsxinc", "js"] + { + touch(&root, name); + } + std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap(); + let listing = folder::list(&root); + assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]"); + assert!(!listing.truncated && !listing.unreadable); + // Each script keeps the path the folder gave, whatever its label. + let paths: Vec<_> = + listing.scripts().into_iter().map(|(folders, label, path)| (folders.join("/"), label.to_string(), path.to_path_buf())).collect(); + assert_eq!(paths[0], (String::new(), "A".to_string(), root.join("A.JSX"))); + assert_eq!(paths[4], ("Zeta/Deep".to_string(), "x".to_string(), root.join("Zeta").join("Deep").join("x.js"))); + assert_eq!(paths.len(), 6); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_script_whose_label_another_row_has_shows_its_whole_file_name() { + let dir = folder("same"); + let root = dir.join("Scripts"); + for name in ["tidy.js", "tidy.jsx", "tidy.js.js", "tidy/x.js", "alone.jsx"] { + touch(&root, name); + } + // `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name. + assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut() { + let dir = folder("escapes"); + let root = dir.join("Scripts"); + // A right-to-left override, which would show the name backwards. + touch(&root, "a\u{202E}sj.js"); + let long = "n".repeat(200); + touch(&root, &format!("{long}.jsx")); + let listing = folder::list(&root); + let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect(); + assert_eq!(labels[0], "a\\u{202E}sj"); + assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1))); + assert!(folder::holds(&root, &root.join(format!("{long}.jsx")))); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn hidden_names_and_links_are_left_out() { + let dir = folder("hidden"); + let root = dir.join("Scripts"); + touch(&root, "shown.js"); + touch(&root, ".hidden.js"); + touch(&root, ".git/hook.js"); + let outside = touch(&dir, "Outside/secret.js"); + // A link out of the folder, and one back to the folder itself. + link_folder(outside.parent().unwrap(), &root.join("Out")); + link_folder(&root, &root.join("Loop")); + #[cfg(unix)] + std::os::unix::fs::symlink(&outside, root.join("linked.js")).unwrap(); + #[cfg(windows)] + { + let marked = touch(&root, "marked.js"); + assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success()); + } + let listing = folder::list(&root); + assert_eq!(rows(&listing.entries), "shown"); + assert!(!listing.truncated && !listing.unreadable); + // Nor is a file behind a link read as a listed script. + assert!(folder::read(&root, &root.join("shown.js"), 10).is_some()); + for path in [root.join("Out").join("secret.js"), root.join("Loop").join("shown.js"), root.join(".hidden.js"), root.join("linked.js")] { + assert!(folder::read(&root, &path, 10).is_none(), "{}", path.display()); + } + // A script, or the folder it is in, that Windows marks hidden after a listing is not read. + #[cfg(windows)] + { + assert!(folder::read(&root, &root.join("marked.js"), 10).is_none()); + let inner = touch(&root, "Sub/inner.js"); + assert!(folder::read(&root, &inner, 10).is_some()); + assert!(std::process::Command::new("attrib").arg("+h").arg(root.join("Sub")).status().unwrap().success()); + assert!(folder::read(&root, &inner, 10).is_none()); + } + let _ = std::fs::remove_dir_all(root.join("Out")); + let _ = std::fs::remove_dir_all(root.join("Loop")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreadable() { + let dir = folder("root"); + let root = dir.join("Scripts"); + touch(&root, "a.js"); + assert_eq!(folder::list(&dir.join("None")), Listing::default()); + let file = touch(&dir, "file"); + assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() }); + let link = dir.join("Link"); + link_folder(&root, &link); + assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() }); + assert!(folder::read(&link, &link.join("a.js"), 10).is_none()); + let _ = std::fs::remove_dir_all(&link); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn each_limit_stops_a_listing_with_what_it_found() { + let dir = folder("limits"); + let root = dir.join("Scripts"); + for n in 0..10 { + touch(&root, &format!("s{n}.js")); + } + let all = Limits::default(); + let entries = list(&root, Limits { entries: 4, ..all }); + assert_eq!((entries.scripts().len(), entries.truncated), (4, true)); + let scripts = list(&root, Limits { scripts: 3, ..all }); + assert_eq!((scripts.scripts().len(), scripts.truncated), (3, true)); + // The clock passes the time limit at the third entry. + let mut calls = 0; + let timed = folder::list_with(&root, &all, &mut || { + calls += 1; + if calls > 2 { all.time + Duration::from_millis(1) } else { Duration::ZERO } + }); + assert_eq!((timed.scripts().len(), timed.truncated), (2, true)); + let whole = list(&root, all); + assert_eq!((whole.scripts().len(), whole.truncated), (10, false)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() { + let dir = folder("depth"); + let root = dir.join("Scripts"); + touch(&root, "1/2/3/4/kept.js"); + touch(&root, "1/2/3/4/5/deeper.js"); + let listing = folder::list(&root); + assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]"); + assert!(listing.truncated); + assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js"))); + assert!(!folder::holds(&root, &root.join("1/2/3/4/5/deeper.js"))); + let two = folder("folders"); + let root = two.join("Scripts"); + touch(&root, "a/x.js"); + touch(&root, "b/y.js"); + let listing = list(&root, Limits { folders: 1, ..Limits::default() }); + assert_eq!(rows(&listing.entries), "a/[x]"); + assert!(listing.truncated); + assert!(!folder::list(&root).truncated); + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_dir_all(two); +} + +#[test] +fn a_folder_with_more_scripts_than_the_limit_lists_that_many() { + let dir = folder("many"); + let root = dir.join("Scripts"); + for n in 0..folder::MAX_SCRIPTS + 40 { + touch(&root, &format!("s{n:04}.js")); + } + let listing = list(&root, Limits::default()); + assert_eq!((listing.scripts().len(), listing.truncated), (folder::MAX_SCRIPTS, true)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_read_takes_only_a_script_that_is_still_a_file_under_the_folder() { + let dir = folder("read"); + let root = dir.join("Scripts"); + let script = touch(&root, "Sub/draw.jsx"); + std::fs::write(&script, "vc.log(1);").unwrap(); + assert_eq!(folder::read(&root, &script, 100).as_deref(), Some(&b"vc.log(1);"[..])); + assert_eq!(folder::read(&root, &script, 4).as_deref(), Some(&b"vc.l"[..])); + let outside = touch(&dir, "outside.js"); + touch(&root, "notes.txt"); + for path in [outside, root.join("Sub").join("..").join("..").join("outside.js"), root.join("notes.txt"), root.join("Sub"), root.join("gone.js")] { + assert!(folder::read(&root, &path, 100).is_none(), "{}", path.display()); + } + // A folder that took the script's place is not a script. + std::fs::remove_file(&script).unwrap(); + std::fs::create_dir(&script).unwrap(); + assert!(folder::read(&root, &script, 100).is_none()); + // Nor is the script read once a link stands in for its folder. + let other = touch(&dir, "Other/draw.jsx"); + std::fs::remove_dir_all(root.join("Sub")).unwrap(); + link_folder(other.parent().unwrap(), &root.join("Sub")); + assert!(folder::read(&root, &root.join("Sub").join("draw.jsx"), 100).is_none()); + let _ = std::fs::remove_dir_all(root.join("Sub")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() { + let dir = folder("command"); + let root = dir.join("Scripts"); + touch(&root, "Tidy Layers.jsx"); + touch(&root, "Export/All Artboards.js"); + let mut s = Session::new(); + assert_eq!( + s.execute("script.listInstalled", &json!({})).unwrap(), + json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}) + ); + s.attach_scripts_dir(root.clone()); + let text = |p: &Path| p.to_string_lossy().into_owned(); + assert_eq!( + s.execute("script.listInstalled", &json!({})).unwrap(), + json!({ + "folder": text(&root), + "scripts": [ + {"path": text(&root.join("Export").join("All Artboards.js")), "label": "All Artboards", "folders": ["Export"]}, + {"path": text(&root.join("Tidy Layers.jsx")), "label": "Tidy Layers", "folders": []}, + ], + "truncated": false, + "unreadable": false, + }) + ); + assert!(!find_command("script.listInstalled").unwrap().journal); + assert!(s.execute("script.listInstalled", &json!({"folder": "x"})).is_err()); + // A folder that is not there yet lists nothing, and the listing does not make it. + std::fs::remove_dir_all(&root).unwrap(); + assert_eq!(s.execute("script.listInstalled", &json!({})).unwrap()["scripts"], json!([])); + assert!(!root.exists()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_installed_script_is_read_as_script_run_reads_a_file() { + let dir = folder("installed"); + let root = dir.join("Scripts"); + let text = |p: &Path| p.to_string_lossy().into_owned(); + let mut s = Session::new(); + let script = touch(&root, "draw.jsx"); + std::fs::write(&script, "\u{feff}vc.log(1);").unwrap(); + assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED, "no folder is attached"); + s.attach_scripts_dir(root.clone()); + assert_eq!(s.installed_script(&text(&script)).unwrap(), "vc.log(1);"); + std::fs::write(&script, "@JSXBIN@ES@2.0@").unwrap(); + assert!(s.installed_script(&text(&script)).unwrap_err().to_string().contains("compiled script")); + std::fs::write(&script, [0xff, 0xfe]).unwrap(); + assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), "the script is not UTF-8 text"); + std::fs::write(&script, vec![b' '; script::MAX_SOURCE_BYTES + 1]).unwrap(); + assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::TOO_LARGE); + std::fs::remove_file(&script).unwrap(); + assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED); + let outside = touch(&dir, "outside.js"); + assert_eq!(s.installed_script(&text(&outside)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { + let dir = folder("roots"); + let root = dir.join("Scripts"); + let script = touch(&root, "draw.js"); + let work = dir.join("work"); + std::fs::create_dir_all(&work).unwrap(); + let mut s = Session::new(); + s.attach_scripts_dir(root.clone()); + let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap(); + let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err(); + assert!(e.to_string().contains("outside the read root"), "{e}"); + let e = crate::file_access::confine(Some(&roots), || s.installed_script(&script.to_string_lossy())).unwrap_err(); + assert!(e.to_string().contains("outside the read root"), "{e}"); + // A read root that holds the folder lets both through. + let roots = crate::file_access::AutomationRoots::new(&[&dir], &[]).unwrap().unwrap(); + crate::file_access::confine(Some(&roots), || { + assert_eq!(s.execute("script.listInstalled", &json!({})).unwrap()["scripts"][0]["label"], "draw"); + assert_eq!(s.installed_script(&script.to_string_lossy()).unwrap(), ""); + }); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs new file mode 100644 index 0000000000..0c9ab45b20 --- /dev/null +++ b/crates/engine/src/tests/script_include.rs @@ -0,0 +1,565 @@ +//! A script's preprocessor lines: `#include` and `//@include` in place, the folders they are looked +//! for in, the run's limits and scope, the other lines, `$.evalFile`, `$.fileName`, and errors at the +//! line of the file they are in. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::script::TEST_JSINCLUDE; +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder inside it for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-include-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + base +} + +fn write(path: &Path, text: &str) { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, text).unwrap(); +} + +/// Runs `main/main.jsx` in `base`, with the text `text`. +fn run(base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + write(&main, text); + Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +/// The report of the run that failed with `e`. +fn failed(base: &Path, text: &str) -> Value { + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write(&main, text); + let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})); + assert!(e.is_err(), "the run failed: {e:?}"); + s.script_report().unwrap().clone() +} + +#[test] +fn script_include_sibling_runs_in_place() { + let base = folder("sibling"); + write(&base.join("main/lib.jsxinc"), "var b = a + 1;"); + write(&base.join("main/two.jsxinc"), "b = b * 10;\r\n"); + let r = run(&base, "var a = 1;\n #include \"lib.jsxinc\"\n//@include 'two.jsxinc'\nvc.log(a + b);").unwrap(); + assert_eq!(r["log"], json!([21])); + // A file may be included again once its earlier inclusion has ended. + let r = run(&base, "var n = 0;\n#include \"three.jsxinc\"\n#include \"three.jsxinc\"\nvc.log(n);"); + assert!(r.is_err(), "three.jsxinc is missing"); + write(&base.join("main/three.jsxinc"), "n++;"); + let r = run(&base, "var n = 0;\n#include \"three.jsxinc\"\n#include three.jsxinc\nvc.log(n);").unwrap(); + assert_eq!(r["log"], json!([2])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_nested_include_uses_including_folder() { + let base = folder("nested"); + write(&base.join("main/sub/one.jsxinc"), "#include \"two.jsxinc\"\nvar one = two + 1;"); + write(&base.join("main/sub/two.jsxinc"), "var two = 2;"); + write(&base.join("main/two.jsxinc"), "var two = 200;"); + let r = run(&base, "#include \"sub/one.jsxinc\"\nvc.log(one);").unwrap(); + assert_eq!(r["log"], json!([3]), "two.jsxinc beside one.jsxinc, not beside the script"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_missing_include_reports_origin() { + let base = folder("missing"); + let report = failed(&base, "vc.log(1);\n\t#include \"nope.jsxinc\"\n"); + assert_eq!(report["kind"], "thrown"); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(2), Some(2))); + assert!(report["message"].as_str().unwrap().contains("include file not found: nope.jsxinc"), "{report}"); + assert_eq!(report["log"], json!([]), "nothing ran before the include was read"); + assert!(report.get("file").is_none(), "the line is the script's own"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_includepath_searches_in_order() { + let base = folder("includepath"); + write(&base.join("main/a/x.jsxinc"), "var x = 'a';"); + write(&base.join("main/b/x.jsxinc"), "var x = 'b';"); + write(&base.join("main/b/y.jsxinc"), "var y = 'b';"); + let r = run(&base, "#includepath \"a; b\"\n#include \"x.jsxinc\"\n#include \"y.jsxinc\"\nvc.log(x + y + $.includePath);").unwrap(); + assert_eq!(r["log"], json!(["aba;b"])); + // A later #includepath replaces the list. + let report = failed(&base, "#includepath \"b\"\n#includepath \"a\"\n#include \"y.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("include file not found: y.jsxinc"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_include_cycle_and_depth_stop() { + let base = folder("cycle"); + write(&base.join("main/a.jsxinc"), "#include \"b.jsxinc\""); + write(&base.join("main/b.jsxinc"), "\n#include \"a.jsxinc\""); + let report = failed(&base, "#include \"a.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("include cycle: a.jsxinc"), "{report}"); + assert_eq!(report["line"], 2); + assert!(report["file"].as_str().unwrap().ends_with("b.jsxinc"), "{report}"); + // A script that includes itself. + let report = failed(&base, "#include \"main.jsx\""); + assert!(report["message"].as_str().unwrap().contains("include cycle"), "{report}"); + for i in 0..20 { + write(&base.join(format!("main/d{i}.jsxinc")), &format!("#include \"d{}.jsxinc\"", i + 1)); + } + let report = failed(&base, "#include \"d0.jsxinc\""); + assert_eq!(report["kind"], "limit"); + assert!(report["message"].as_str().unwrap().contains("include depth limit (16) reached"), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("d15.jsxinc"), "the 17th level is refused: {report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere. +/// `false` when the system does not allow it here. +fn link_folder(target: &Path, link: &Path) -> bool { + #[cfg(windows)] + { + let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success()); + made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok() + } + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link).is_ok() + } + #[cfg(not(any(unix, windows)))] + { + let _ = (target, link); + false + } +} + +#[test] +fn script_include_link_out_of_the_folder_is_refused() { + let base = folder("junction"); + write(&base.join("outside/x.jsxinc"), "var leaked = 1;"); + // `mklink` reads a `/` in its paths as a switch, so each name is joined on its own. + if !link_folder(&base.join("outside"), &base.join("main").join("away")) { + eprintln!("skipped: a folder link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + assert!(std::fs::canonicalize(base.join("main/away/x.jsxinc")).unwrap().starts_with(std::fs::canonicalize(base.join("outside")).unwrap())); + let report = failed(&base, "#include \"away/x.jsxinc\"\nvc.log(leaked);"); + assert!(report["message"].as_str().unwrap().contains("script file read refused: away/x.jsxinc"), "{report}"); + let report = failed(&base, "$.evalFile('away/x.jsxinc');"); + assert!(report["message"].as_str().unwrap().contains("script file read refused: away/x.jsxinc"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_include_parent_component_refused() { + let base = folder("parent"); + write(&base.join("outside.jsxinc"), "var leaked = 1;"); + write(&base.join("main/sub/x.jsxinc"), "var x = 1;"); + let report = failed(&base, "#include \"../outside.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("script file read refused: ../outside.jsxinc"), "{report}"); + // Refused even where the path would come back inside the folder. + let report = failed(&base, "#include \"sub/../sub/x.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("script file read refused"), "{report}"); + let report = failed(&base, "#includepath \"..\"\n#include \"outside.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("script file read refused: outside.jsxinc"), "{report}"); + let absolute = base.join("outside.jsxinc").to_string_lossy().replace('\\', "/"); + let report = failed(&base, &format!("#include \"{absolute}\"")); + assert!(report["message"].as_str().unwrap().contains("script file read refused"), "an absolute path outside: {report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_jsinclude_outside_grants_ignored() { + let base = folder("jsinclude"); + write(&base.join("outside/x.jsxinc"), "var x = 'outside';"); + write(&base.join("main/lib/y.jsxinc"), "var y = 'lib';"); + TEST_JSINCLUDE.with(|t| *t.borrow_mut() = Some(vec![base.join("outside"), base.join("main/lib")])); + let report = failed(&base, "#include \"x.jsxinc\""); + let r = run(&base, "#include \"y.jsxinc\"\nvc.log(y);"); + TEST_JSINCLUDE.with(|t| *t.borrow_mut() = None); + assert!(report["message"].as_str().unwrap().contains("include file not found: x.jsxinc"), "passed over, not refused: {report}"); + assert_eq!(r.unwrap()["log"], json!(["lib"]), "a JSINCLUDE folder inside the script's folder is searched"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_target_other_app_does_not_route() { + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "#target someapp-12\n#target \"other\"\n//@target x\n#strict off\nvc.log(1);"})).unwrap(); + assert_eq!(r["log"], json!([1])); + for (source, message) in [ + ("#target\nvc.log(1);", "#target needs a value"), + ("#targetengine \"session\"", "unsupported script directive: #targetengine"), + ("#engine \"main\"", "unsupported script directive: #engine"), + ("#strict maybe", "#strict takes on or off"), + ("#frobnicate 1", "unknown script directive: #frobnicate"), + ("#include \"x.jsxinc", "unterminated quote in #include"), + ("#include \"x.jsxinc\"", "script file read refused: x.jsxinc"), + ] { + let e = s.execute("script.run", &json!({"source": format!("vc.log(0);\n{source}")})).unwrap_err().to_string(); + assert!(e.contains(message), "{source}: {e}"); + assert_eq!(s.script_report().unwrap()["line"], 2, "{source}"); + assert_eq!(s.script_report().unwrap()["log"], json!([]), "{source}"); + } + // An unknown `//@` name stays a comment. + assert_eq!(s.execute("script.run", &json!({"source": "//@frobnicate 1\nvc.log(2);"})).unwrap()["log"], json!([2])); +} + +#[test] +fn script_name_comes_from_the_script_line() { + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "#script \"First\"\n#script Second\nvc.log($.fileName);"})).unwrap(); + assert_eq!((r["name"].as_str(), r["log"].clone()), (Some("Second"), json!([""]))); + let r = s.execute("script.run", &json!({"source": "#script Second\n", "name": "given.js"})).unwrap(); + assert_eq!(r["name"], "given.js", "a name given to script.run wins"); + let base = folder("name"); + write(&base.join("main/lib.jsxinc"), "#script Inner\n"); + let r = run(&base, "#include \"lib.jsxinc\"").unwrap(); + assert_eq!(r["name"], "main.jsx", "an included file's #script line does not rename the run"); + let _ = std::fs::remove_dir_all(base); +} + +/// The script's `ro`, with a read-only `x`. +const READ_ONLY: &str = "var ro = {};\nObject.defineProperty(ro, 'x', {value: 1});\n"; + +#[test] +fn strict_on_runs_and_read_only_write_throws() { + let mut s = Session::new(); + for head in ["#strict on\n", "//@strict on\n", "#strict ON\n", "#strict off\n#strict on\n"] { + let source = format!("{head}{READ_ONLY}vc.log(1);\n ro.x = 2;\nvc.log(2);"); + let e = s.execute("script.run", &json!({"source": source})).unwrap_err().to_string(); + assert!(e.contains("TypeError: cannot assign to property 'x': it is read-only"), "{head}: {e}"); + let report = s.script_report().unwrap(); + assert_eq!(report["kind"], "thrown", "{head}"); + assert_eq!(report["log"], json!([1]), "{head}: the script ran up to the write"); + let line = head.lines().count() as u64 + 4; + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(line), Some(3)), "{head}: {report}"); + } + // The error can be caught, and every kind of assignment is checked. + let source = format!( + "#strict on\n{READ_ONLY}var out = [];\nfunction t(f) {{ try {{ f(); out.push('wrote'); }} catch (e) {{ out.push(e.name); }} }}\nt(function () {{ ro.x = 2; }});\nt(function () {{ ro['x'] += 1; }});\nt(function () {{ ro.x++; }});\nt(function () {{ undefined = 1; }});\nt(function () {{ [].concat.length = 0; }});\nvc.log(out);\nvc.log(ro.x);" + ); + let r = s.execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!(r["log"], json!([["TypeError", "TypeError", "TypeError", "TypeError", "TypeError"], 1])); + // Without the line, or with `#strict off` last, the write is ignored as before. + for head in ["", "#strict off\n", "#strict on\n#strict off\n"] { + let r = s.execute("script.run", &json!({"source": format!("{head}{READ_ONLY}ro.x = 2;\nvc.log(ro.x);")})).unwrap(); + assert_eq!(r["log"], json!([1]), "{head}"); + } +} + +#[test] +fn strict_on_rejects_getter_only_and_nonextensible_additions() { + let mut s = Session::new(); + let source = "#strict on\nvar out = [];\nfunction t(f) { try { f(); out.push('wrote'); } catch (e) { out.push(String(e)); } }\n\ + var g = {get v() { return 1; }}, set = {set v(x) { this.got = x; }};\n\ + t(function () { g.v = 2; });\n\ + t(function () { Object.preventExtensions({}).n = 1; });\n\ + t(function () { Object.seal({a: 1}).n = 1; });\n\ + t(function () { Object.freeze({a: 1}).a = 2; });\n\ + t(function () { vc.extra = 1; });\n\ + var open = {};\nt(function () { open.n = 1; });\nt(function () { set.v = 3; });\nt(function () { Object.seal({a: 1}).a = 2; });\n\ + vc.log(out);\nvc.log(open.n);\nvc.log(set.got);"; + let r = s.execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!( + r["log"], + json!([ + [ + "TypeError: cannot assign to property 'v': it has only a getter", + "TypeError: cannot assign to property 'n': the object is not extensible", + "TypeError: cannot assign to property 'n': the object is not extensible", + "TypeError: cannot assign to property 'a': it is read-only", + "TypeError: cannot assign to property 'extra': the object is not extensible", + "wrote", + "wrote", + "wrote" + ], + 1, + 3 + ]) + ); + let r = s.execute("script.run", &json!({"source": source.replacen("#strict on", "#strict off", 1)})).unwrap(); + assert_eq!(r["log"][0], json!(["wrote", "wrote", "wrote", "wrote", "wrote", "wrote", "wrote", "wrote"]), "off, nothing is refused"); +} + +#[test] +fn strict_on_does_not_enable_es5_early_errors() { + let mut s = Session::new(); + let source = "#strict on\nwith ({w: 1}) { vc.log(w); }\nfunction f(a, a) { return a; }\nvc.log(f(1, 2));\nvc.log(010);\nundeclared = 4;\nvc.log(undeclared);\n\ + vc.log((function () { return typeof this; })());\nvc.log(delete Object.prototype);\nvar eval2 = 5;\nvc.log((function () { arguments = 6; return arguments; })());"; + let r = s.execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!(r["log"], json!([1, 2, 8, 4, "object", false, 6])); + // 'use strict' still makes the code strict mode code. + let e = s.execute("script.run", &json!({"source": "#strict on\n'use strict';\nundeclared2 = 1;"})).unwrap_err().to_string(); + assert!(e.contains("ReferenceError"), "{e}"); + let e = s.execute("script.run", &json!({"source": "#strict on\n'use strict';\nwith ({}) {}"})).unwrap_err().to_string(); + assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{e}"); +} + +#[test] +fn strict_on_in_include_controls_expanded_run() { + let base = folder("strict"); + write(&base.join("main/on.jsxinc"), "#strict on\nvar inc = 1;"); + write(&base.join("main/off.jsxinc"), "//@strict off\n"); + write(&base.join("main/writes.jsxinc"), &format!("{READ_ONLY}\n ro.x = 2;\n")); + // An included file's line sets the checks for the script's own code too. + let report = failed(&base, &format!("#include \"on.jsxinc\"\n{READ_ONLY}ro.x = 2;")); + assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}"); + assert_eq!(report["line"], 4, "{report}"); + assert!(report.get("file").is_none(), "{report}"); + // A write in an included file is reported at its own line. + let report = failed(&base, "#strict on\n#include \"writes.jsxinc\""); + assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}"); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(4), Some(3)), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("writes.jsxinc"), "{report}"); + // The last line of the expanded run wins, wherever it is. + let r = run(&base, &format!("#strict on\n#include \"off.jsxinc\"\n{READ_ONLY}ro.x = 2;\nvc.log(ro.x);")).unwrap(); + assert_eq!(r["log"], json!([1])); + let report = failed(&base, &format!("#include \"off.jsxinc\"\n#strict on\n{READ_ONLY}ro.x = 2;")); + assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn strict_mode_in_eval_file_is_scoped() { + let base = folder("strict-eval"); + write( + &base.join("main/on.jsx"), + &format!( + "#strict on\n{READ_ONLY}function w(o) {{ o.x = 2; }}\nvar inner;\ntry {{ ro.x = 2; inner = 'wrote'; }} catch (e) {{ inner = e.name; }}\n" + ), + ); + write(&base.join("main/off.jsx"), &format!("#strict off\n{READ_ONLY}ro.x = 2;\n'off ran';")); + write(&base.join("main/plain.jsx"), &format!("{READ_ONLY}ro.x = 2;\n'plain ran';")); + // A file's own `#strict on` holds for its code, its functions included, and not the caller's. + let r = run( + &base, + "$.evalFile('on.jsx');\nvar after;\ntry { ro.x = 3; after = 'ignored'; } catch (e) { after = e.name; }\nvar called;\ntry { w(ro); called = 'wrote'; } catch (e) { called = e.name; }\nvc.log([inner, after, called]);", + ) + .unwrap(); + assert_eq!(r["log"], json!([["TypeError", "ignored", "TypeError"]])); + // A file without the line takes the caller's checks, and its own `#strict off` turns them off. + let r = run(&base, "#strict on\nvc.log($.evalFile('off.jsx'));\nvar e1;\ntry { ro.x = 2; } catch (e) { e1 = e.name; }\nvc.log(e1);").unwrap(); + assert_eq!(r["log"], json!(["off ran", "TypeError"]), "the caller keeps its own checks"); + let report = failed(&base, "#strict on\n$.evalFile('plain.jsx');"); + assert!(report["message"].as_str().unwrap().contains("it is read-only"), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("plain.jsx"), "{report}"); + assert_eq!(report["line"], 3, "{report}"); + assert_eq!(run(&base, "vc.log($.evalFile('plain.jsx'));").unwrap()["log"], json!(["plain ran"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_eval_file_returns_last_value_and_shares_globals() { + let base = folder("evalfile"); + write(&base.join("main/sub/e.jsx"), "var inner = $.fileName;\nfunction h(x) { return x * g; }\n#include \"f.jsxinc\"\ng + f;"); + write(&base.join("main/sub/f.jsxinc"), "var f = 40;"); + write(&base.join("main/empty.jsx"), ""); + let r = run( + &base, + "var g = 2;\nvar r = $.evalFile('sub/e.jsx', 1000);\nvc.log(r);\nvc.log(h(3));\nvc.log(/e\\.jsx$/.test(inner));\nvc.log(/main\\.jsx$/.test($.fileName));\nvc.log($.evalFile('empty.jsx') === undefined);", + ) + .unwrap(); + assert_eq!(r["log"], json!([42, 6, true, true, true])); + // Its errors can be caught; a file is evaluated again after it has returned. + let r = run( + &base, + "var g = 1; var out = [];\ntry { $.evalFile(''); } catch (e) { out.push(e.name); }\ntry { $.evalFile('nope.jsx'); } catch (e) { out.push(String(e)); }\ntry { $.evalFile('sub/e.jsx', -1); } catch (e) { out.push(e.name); }\ntry { $.evalFile('sub/e.jsx', Infinity); } catch (e) { out.push(e.name); }\nout.push($.evalFile('sub/e.jsx') + $.evalFile('sub/e.jsx'));\nvc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([["TypeError", "Error: include file not found: nope.jsx", "RangeError", "TypeError", 82]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_eval_file_outside_scope_refused() { + let base = folder("evaloutside"); + write(&base.join("outside.jsx"), "1;"); + let absolute = base.join("outside.jsx").to_string_lossy().replace('\\', "/"); + let script = format!( + "var out = [];\ntry {{ $.evalFile('../outside.jsx'); }} catch (e) {{ out.push(String(e)); }}\ntry {{ $.evalFile('{absolute}'); }} catch (e) {{ out.push(String(e)); }}\nvc.log(out);" + ); + let r = run(&base, &script).unwrap(); + let out = r["log"][0].as_array().unwrap(); + assert_eq!(out.len(), 2); + for e in out { + assert!(e.as_str().unwrap().starts_with("Error: script file read refused"), "{e}"); + } + // A script given as text has no folder to read from. + let e = Session::new().execute("script.run", &json!({"source": "$.evalFile('x.jsx');"})).unwrap_err().to_string(); + assert!(e.contains("script file read refused: x.jsx"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_directives_in_strings_and_block_comments_are_inert() { + let mut s = Session::new(); + let source = "#target x\nvar a = '#include \"nope.jsxinc\"';\n/*\n#include \"nope.jsxinc\"\n//@include \"nope.jsxinc\"\n*/\nvar b = 1; // #include \"nope.jsxinc\"\nvar c = 2; #include\nvc.log(a.length + b);"; + let e = s.execute("script.run", &json!({"source": source})).unwrap_err().to_string(); + // `#` after code on a line is not a preprocessor line: the script has a syntax error there. + assert!(e.contains("line 8"), "{e}"); + let source = source.replace("var c = 2; #include\n", ""); + assert_eq!(s.execute("script.run", &json!({"source": source})).unwrap()["log"], json!([23])); +} + +#[test] +fn script_included_error_has_local_file_and_line() { + let base = folder("errors"); + write(&base.join("main/lib.jsxinc"), "var x = 1;\n\n throw new Error('boom');\n"); + write(&base.join("main/bad.jsxinc"), "var y = 1;\nvar = 2;\n"); + write(&base.join("main/five.jsxinc"), "1;\n2;\n3;\n4;\n5;"); + write(&base.join("main/sub/thrower.jsx"), "\n\nthrow new Error('deep');"); + let mut s = Session::new(); + let report = failed(&base, "var z = 0;\n#include \"lib.jsxinc\""); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(3), Some(5)), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("lib.jsxinc"), "{report}"); + let report = failed(&base, "#include \"bad.jsxinc\""); + assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("bad.jsxinc"), "{report}"); + // A line of the script after an include keeps its own number. + let report = failed(&base, "#include \"five.jsxinc\"\n throw new Error('after');"); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(2), Some(3)), "{report}"); + assert!(report.get("file").is_none(), "{report}"); + let report = failed(&base, "#include \"five.jsxinc\"\nvar = 1;"); + assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}"); + // An included file that ends in a carriage return does not join the script's next line ending. + write(&base.join("main/cr.jsxinc"), "1;\r2;\r"); + let report = failed(&base, "#include \"cr.jsxinc\"\n\n throw new Error('after');"); + assert_eq!((report["line"].as_u64(), report["column"].as_u64()), (Some(3), Some(3)), "{report}"); + assert!(report.get("file").is_none(), "{report}"); + let report = failed(&base, "#include \"cr.jsxinc\"\r\nvar = 1;"); + assert_eq!((report["kind"].as_str(), report["line"].as_u64()), (Some("syntax"), Some(2)), "{report}"); + // An uncaught error in a file $.evalFile ran is at that file's line. + let report = failed(&base, "var a = 1;\n$.evalFile('sub/thrower.jsx');"); + assert_eq!(report["line"], 3, "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("thrower.jsx"), "{report}"); + // So is a file $.evalFile could not run: a syntax error, or a bad preprocessor line. + write(&base.join("main/sub/broken.jsx"), "var a = 1;\n\nvar = 2;"); + write(&base.join("main/sub/directive.jsx"), "\n#frobnicate 1"); + for (file, line) in [("broken.jsx", 3), ("directive.jsx", 2)] { + let report = failed(&base, &format!("var a = 1;\n$.evalFile('sub/{file}');")); + assert_eq!(report["line"], line, "{report}"); + assert!(report["file"].as_str().unwrap().ends_with(file), "{report}"); + } + // The console's error line names the file. + let main = base.join("main/main.jsx"); + write(&main, "#include \"lib.jsxinc\""); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err()); + let console = s.execute("script.console", &json!({})).unwrap(); + let error = console["lines"].as_array().unwrap().iter().find(|l| l["kind"] == "error").unwrap()["text"].as_str().unwrap().to_string(); + assert!(error.starts_with("main.jsx: ") && error.contains("lib.jsxinc:3:5: Error: boom"), "{error}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Pumps the run in the app until it ends or waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +#[test] +fn script_dialogs_in_included_and_evaluated_files() { + let base = folder("dialogs"); + write(&base.join("main/ask.jsxinc"), "var a = confirm('inc');\n"); + write(&base.join("main/ev.jsx"), "alert('ev'); 7"); + let text = "#include \"ask.jsxinc\"\nvar m = '';\ntry { m = $.evalFile('ev.jsx'); } catch (e) { m = e.message; }\nvc.log([a, m]);"; + let main = base.join("main/main.jsx"); + write(&main, text); + let path = main.to_string_lossy().to_string(); + // In the app, an included file's dialog waits as the script's own does; one in a file + // $.evalFile runs cannot wait there and throws an error the script can catch. + let mut s = Session::new(); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": path})).unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_dialog().unwrap().message, "inc"); + assert!(s.script_answer(crate::script::DialogAnswer::Confirm(true))); + let r = pump(&mut s).unwrap().unwrap(); + let m = r["log"][0][1].as_str().unwrap_or_default(); + assert_eq!(r["log"][0][0], true, "{r}"); + assert!(m.contains("alert") && m.contains("$.evalFile"), "the error names the call and why: {r}"); + assert_eq!(r["dialogCount"], 1, "{r}"); + // A run with nobody to ask takes both answers in order. + let mut s = Session::new(); + let answers = json!([{"kind": "confirm", "value": false}, {"kind": "alert", "value": "ok"}]); + let r = s.execute("script.run", &json!({"path": path, "answers": answers})).unwrap(); + assert_eq!((r["log"].clone(), r["dialogCount"].clone()), (json!([[false, 7]]), json!(2)), "{r}"); + // An error in an included file after its dialog is at that file's line, and the report keeps + // both the file and the dialog. + write(&base.join("main/ask.jsxinc"), "var a = confirm('inc');\nif (a) throw new Error('after');\n"); + let mut s = Session::new(); + s.script_frames = true; + s.execute("script.run", &json!({"path": path})).unwrap(); + assert!(pump(&mut s).is_none()); + assert!(s.script_answer(crate::script::DialogAnswer::Confirm(true))); + assert!(pump(&mut s).unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!(report["line"], 2, "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("ask.jsxinc"), "{report}"); + assert_eq!(report["dialogs"][0]["answer"], true, "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The line, column and file name of a failed run's report, and its console error line (the only +/// line of a run without output that starts with the script's name). +fn place(report: &Value) -> (u64, u64, Option<&str>, &str) { + let file = report.get("file").map(|f| f.as_str().unwrap().rsplit(['/', '\\']).next().unwrap()); + let lines = report["console"]["lines"].as_array().unwrap(); + let error = lines.iter().filter_map(Value::as_str).find(|l| l.starts_with("main.jsx")).unwrap(); + (report["line"].as_u64().unwrap(), report["column"].as_u64().unwrap(), file, error) +} + +#[test] +fn script_eval_file_error_caught_and_thrown_again_is_at_the_new_throw() { + let base = folder("rethrow"); + write(&base.join("main/sub/broken.jsx"), "var a = 1;\n\nvar = 2;"); + write(&base.join("main/sub/directive.jsx"), "\n#frobnicate 1"); + write(&base.join("main/sub/rethrow.jsx"), "var r = 1;\n throw saved;"); + write(&base.join("main/sub/outer.jsx"), "var q = 1;\n$.evalFile('broken.jsx');"); + write(&base.join("main/sub/outer2.jsx"), "try { $.evalFile('broken.jsx'); } catch (e) {\n\n throw e;\n}"); + let caught = "var saved;\ntry { $.evalFile('sub/broken.jsx'); } catch (e) { saved = e; }\n"; + let cases = [ + // Thrown again in the script, or in another file $.evalFile runs. + (format!("{caught}var b = 2;\n throw saved;"), (4, 3, None)), + (format!("{caught}$.evalFile('sub/rethrow.jsx');"), (2, 3, Some("rethrow.jsx"))), + // A new error whose message holds the failure's text, or is the same text. + (format!("{caught}throw new Error(saved.message);"), (3, 1, None)), + (format!("{caught}throw new SyntaxError(saved.message);"), (3, 1, None)), + // A second failure, caught, does not move the first one. + (format!("{caught}try {{ $.evalFile('sub/directive.jsx'); }} catch (e) {{}}\n throw saved;"), (4, 2, None)), + // A second failure, uncaught, is at its own file's place. + (format!("{caught}$.evalFile('sub/directive.jsx');"), (2, 1, Some("directive.jsx"))), + // An uncaught failure is at the file's place, through a finally block and from a nested file. + ("var a = 1;\ntry { $.evalFile('sub/broken.jsx'); } finally { a = 2; }".to_string(), (3, 5, Some("broken.jsx"))), + ("$.evalFile('sub/outer.jsx');".to_string(), (3, 5, Some("broken.jsx"))), + // Caught in a nested file and thrown again there. + ("$.evalFile('sub/outer2.jsx');".to_string(), (3, 5, Some("outer2.jsx"))), + // A failure caught in a run after one that failed with it, and a different error. + ("try { $.evalFile('sub/broken.jsx'); } catch (e) {}\nthrow new Error('other');".to_string(), (2, 1, None)), + ]; + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + for (text, (line, column, file)) in cases { + write(&main, &text); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "{text}"); + let report = s.script_report().unwrap().clone(); + let (l, c, f, error) = place(&report); + assert_eq!((report["kind"].as_str(), l, c, f), (Some("thrown"), line, column, file), "{text}\n{report}"); + let at = match file { + Some(f) => format!("{f}:{line}:{column}: "), + None => format!("main.jsx:{line}:{column}: "), + }; + assert!(error.starts_with("main.jsx") && error.contains(&at), "{error}"); + } + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index eba254116a..8294aa638a 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -166,7 +166,7 @@ fn an_error_names_the_script_its_place_and_kind() { let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); - assert!(run(&mut s, "#target x\n1").unwrap_err().to_string().contains("#target")); + assert!(run(&mut s, "#targetengine x\n1").unwrap_err().to_string().contains("unsupported script directive: #targetengine")); assert_eq!(s.script_report().unwrap()["line"], 1); } @@ -989,6 +989,15 @@ fn source_text() -> impl proptest::strategy::Strategy { Just("{".to_string()), Just("try {".to_string()), Just("} catch (e) {}".to_string()), + Just("\n#include \"x.jsxinc\"\n".to_string()), + Just("\n//@include 'x\n".to_string()), + Just("\n#includepath \";;..;\"\n".to_string()), + Just("\n#script \"\"\n".to_string()), + Just("\n#target\n".to_string()), + Just("\n#strict on\n".to_string()), + Just("\n#\u{0}\n".to_string()), + Just("try { $.evalFile('x.jsx', NaN); } catch (e) {}".to_string()), + "\n#[a-z]{0,12}[ -~]{0,20}\n", "[ -~]{0,30}", "\\PC{0,10}", ]; diff --git a/crates/engine/src/tests/smartguides.rs b/crates/engine/src/tests/smartguides.rs index 8bb6a0dfbf..7e2741c64f 100644 --- a/crates/engine/src/tests/smartguides.rs +++ b/crates/engine/src/tests/smartguides.rs @@ -89,6 +89,37 @@ fn a_pen_anchor_lines_up_with_another_objects_centre() { assert!((pts[2] - Point::new(100.0, 381.0)).hypot() < 1e-9, "{pts:?}"); } +/// View › Pixel Preview turns Smart Guides off in the tools: a moved square no longer lines up with +/// the other square's top and shows no guide, and a Rectangle tool corner no longer lands on its +/// anchor. +#[test] +fn pixel_preview_turns_smart_guides_off() { + for pixel in [false, true] { + let view = ViewInfo { pixel_preview: pixel, ..ViewInfo::default() }; + let mut s = session(); + let b = s.execute("shape.rectangle", &json!({"x": 400, "y": 300, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.select_tool("selection", view).unwrap(); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 425.0, 325.0), view).unwrap(); + for y in [300.0, 250.0, 200.0, 150.0, 128.0] { + s.pointer(&PointerEvent::new(PointerKind::Drag, 425.0, y), view).unwrap(); + } + let guides = s.overlays(view).into_iter().filter(|o| matches!(o, Overlay::Line { .. } | Overlay::Label { .. })).count(); + s.pointer(&PointerEvent::new(PointerKind::Up, 425.0, 128.0), view).unwrap(); + let top = s.doc().unwrap().doc.node(NodeId(b)).unwrap().geometric_bounds().unwrap().y0; + assert_eq!((top, guides > 0), if pixel { (103.0, false) } else { (100.0, true) }, "Pixel Preview {pixel}"); + + s.select_tool("rectangle", view).unwrap(); + for (kind, x, y) in + [(PointerKind::Down, 302.0, 297.0), (PointerKind::Drag, 250.0, 250.0), (PointerKind::Drag, 202.0, 203.0), (PointerKind::Up, 202.0, 203.0)] + { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + let r = made(&s); + assert_eq!((r.x0, r.y0), if pixel { (202.0, 203.0) } else { (200.0, 200.0) }, "Pixel Preview {pixel}"); + } +} + /// Preferences › Smart Guides › Construction Guides: on (the default), a Pen anchor near the /// 45° guide through the last one lands on it; off, it stays where it was clicked. #[test] diff --git a/crates/engine/src/tests/store.rs b/crates/engine/src/tests/store.rs index 37eafe6e46..b6ac7b0201 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -5,7 +5,7 @@ use serde_json::{Value, json}; use vectorcraft_color::cms; use crate::Session; -use crate::store::{MAX_PRESET_FILE, file_stem}; +use crate::store::{MAX_PRESET_FILE, file_stem, holds}; fn fresh_dir(tag: &str) -> std::path::PathBuf { let dir = vectorcraft_testkit::temp_dir(&format!("store-{tag}")); @@ -128,6 +128,47 @@ fn a_folder_that_does_not_exist_yet_takes_the_presets_the_preferences_held() { assert_eq!(saved_names(&mut b), ["From Preferences"]); } +/// Serves `0` bytes without end and counts how many were read. +struct Endless(u64); + +impl std::io::Read for Endless { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.0 > 1 << 24 { + return Err(std::io::Error::other("read too far")); + } + buf.fill(0); + self.0 += buf.len() as u64; + Ok(buf.len()) + } +} + +#[test] +fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() { + let mut old = Endless(0); + assert!(!holds(&mut old, &[0; 10])); + assert_eq!(old.0, 11); + assert!(holds(&[1, 2, 3][..], &[1, 2, 3])); + assert!(!holds(&[1, 2, 3, 4][..], &[1, 2, 3])); + assert!(!holds(&[1, 2][..], &[1, 2, 3])); + assert!(holds(&[][..], &[])); +} + +#[test] +fn a_saved_preset_replaces_an_oversized_file_in_its_place() { + let dir = fresh_dir("oversized-put").join("PDF Presets"); + let mut a = Session::new(); + a.attach_pdf_preset_store(dir.clone()); + a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap(); + let file = dir.join(format!("{}.vcpdfpresets", file_stem("Web"))); + let saved = std::fs::read(&file).unwrap(); + let mut oversized = saved.clone(); + oversized.resize(usize::try_from(MAX_PRESET_FILE).unwrap() * 2, b' '); + std::fs::write(&file, &oversized).unwrap(); + + a.execute("pdf.preset.save", &json!({"name": "Web"})).unwrap(); + assert_eq!(std::fs::read(&file).unwrap(), saved); +} + #[test] fn damaged_unsafe_and_oversized_preset_files_are_skipped() { let dir = fresh_dir("damaged").join("PDF Presets"); diff --git a/crates/engine/src/tests/stylelib.rs b/crates/engine/src/tests/stylelib.rs index 43838ff8e0..5124fb4502 100644 --- a/crates/engine/src/tests/stylelib.rs +++ b/crates/engine/src/tests/stylelib.rs @@ -41,8 +41,9 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() let mut s = session(); let list = run(&mut s, "graphicStyle.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert!(libs.len() >= 7 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); + assert!(libs.len() >= 8 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}"); + assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}"); for l in libs { let id = l["id"].as_str().unwrap(); let g = run(&mut s, "graphicStyle.library", json!({"library": id})); @@ -60,6 +61,9 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() let game = run(&mut s, "graphicStyle.library", json!({"library": "game-hud"})); let game_names: Vec<&str> = game["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(game_names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]); + let status = run(&mut s, "graphicStyle.library", json!({"library": "status-effects"})); + let status_names: Vec<&str> = status["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(status_names, ["Poison Tint", "Freeze Edge", "Burn Aura", "Stun Pulse", "Stealth Fade", "Shield Buff"]); let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0); let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "game-hud", "name": "Mana Glow", "apply": true, "ids": [id.0]})); assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec!["Mana Glow"], Some("Mana Glow"))); @@ -67,6 +71,12 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#3498db").unwrap())); assert_eq!(node.appearance.stroke_paint(), Paint::None); assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.outerGlow"]); + let id2 = rect(&mut s, 60.0, 20.0, 40.0, 30.0); + let r2 = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "status-effects", "name": "Poison Tint", "apply": true, "ids": [id2.0]})); + assert_eq!((names(&r2["added"]), r2["applied"].as_str()), (vec!["Poison Tint"], Some("Poison Tint"))); + let node2 = doc(&s).node(id2).unwrap(); + assert_eq!(node2.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#2ecc71").unwrap())); + assert_eq!(node2.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.outerGlow"]); // By name in any case. assert_eq!(run(&mut s, "graphicStyle.library", json!({"library": "shadows and glows"}))["id"], "shadows-glows"); assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err()); diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index fcb4581c2c..92f1e49873 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -207,6 +207,163 @@ fn deleting_a_filter_in_use_leaves_the_effect_drawing_nothing() { assert_eq!(drawn(&s, a), json!(SHIFT_MORE)); } +/// The `(name, xml)` of every `svg.filter` effect on the document's objects. +fn filter_effects(s: &Session) -> Vec<(String, String)> { + let mut out = vec![]; + s.doc().unwrap().doc.walk(|n| { + for e in n.appearance.effects.iter().filter(|e| e.id == vectorcraft_render::effects::SVG_FILTER) { + out.push((e.params["name"].as_str().unwrap().to_string(), e.params["xml"].as_str().unwrap().to_string())); + } + }); + out +} + +/// Pasted art whose filter has a name the document gives another filter keeps its own filter +/// under a free name, so editing or deleting the document's filter leaves it alone. Pasted back +/// into the document it came from, it takes the document's filter as it is now. +#[test] +fn pasted_art_keeps_a_filter_another_of_its_name_would_replace() { + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + let svg = format!( + r#"{SHIFT_MORE}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 1); + assert_eq!(pasted[0].0, "Shift 2", "renamed: {pasted:?}"); + assert!(pasted[0].1.contains("id=\"Shift 2\"") && pasted[0].1.contains("dx=\"9\""), "its own filter: {pasted:?}"); + assert_eq!(names(&mut s), ["Shift"]); + run(&mut s, "svgFilter.delete", json!({"name": "Shift"})); + assert_eq!(filter_effects(&s), pasted, "the document's filter leaves it alone"); + // The same filter as the document's keeps its name. + let mut t = session(); + run(&mut t, "svgFilter.define", json!({"xml": SHIFT})); + let svg = format!( + r#"{SHIFT}"# + ); + run(&mut t, "clipboard.importSvg", json!({"svg": svg})); + run(&mut t, "edit.pasteInPlace", json!({})); + assert_eq!(filter_effects(&t), [("Shift".to_string(), SHIFT.to_string())]); + // Copied, then the filter edited: pasted back, the copy draws the edited filter. + let mut u = session(); + let a = rect(&mut u, 10.0); + run(&mut u, "svgFilter.define", json!({"xml": SHIFT})); + run(&mut u, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]})); + run(&mut u, "select.set", json!({"ids": [a.0]})); + run(&mut u, "edit.copy", json!({})); + run(&mut u, "svgFilter.define", json!({"xml": SHIFT_MORE, "replace": "Shift"})); + run(&mut u, "edit.pasteInPlace", json!({})); + let both = filter_effects(&u); + assert_eq!(both, [("Shift".to_string(), SHIFT_MORE.to_string()), ("Shift".to_string(), SHIFT_MORE.to_string())]); +} + +/// A pasted filter at the size limit, which "Shift 2" would make too long to draw, keeps its own +/// definition under a free name no longer than its own (a free letter for a one-letter name), and +/// its id is that name. +#[test] +fn pasted_art_with_a_filter_at_the_size_limit_still_draws_when_renamed() { + for (name, held, renamed) in [("Shift", SHIFT, "Shif"), ("S", r#""#, "a")] { + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": held})); + let (open, close) = (format!(r#""#); + let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len())); + assert!(vectorcraft_render::effects::svg_filter::check(&big).is_ok()); + let svg = format!( + r#"{big}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 1); + assert_eq!(pasted[0].0, renamed, "renamed: {}", pasted[0].0); + assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok(renamed.to_string()), "the pasted filter draws under its name"); + assert!(pasted[0].1.contains("dx=\"9\""), "its own filter"); + assert_eq!(names(&mut s), [name]); + } +} + +/// A pasted filter is not renamed to a name an effect in the document already gives, even one whose +/// filter was deleted, so defining a filter of that name later changes only that effect. +#[test] +fn pasted_art_takes_no_name_the_documents_effects_use() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.define", json!({"xml": r#""#})); + run(&mut s, "svgFilter.apply", json!({"name": "Shift 2", "ids": [a.0]})); + run(&mut s, "svgFilter.delete", json!({"name": "Shift 2"})); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + let svg = format!( + r#"{SHIFT_MORE}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + let names: Vec = filter_effects(&s).into_iter().map(|(n, _)| n).collect(); + assert_eq!(names, ["Shift 2", "Shift 3"]); +} + +/// A pasted filter is not renamed to a name an effect in a brush's art gives either. +#[test] +fn pasted_art_takes_no_name_the_documents_brushes_use() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "svgFilter.define", json!({"xml": r#""#})); + run(&mut s, "svgFilter.apply", json!({"name": "Shift 2", "ids": [a.0]})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "brush.new", json!({"type": "art", "name": "Fx"})); + run(&mut s, "edit.clear", json!({"ids": [a.0]})); + run(&mut s, "svgFilter.delete", json!({"name": "Shift 2"})); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + let svg = format!( + r#"{SHIFT_MORE}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + let names: Vec = filter_effects(&s).into_iter().map(|(n, _)| n).collect(); + assert_eq!(names, ["Shift 3"]); +} + +/// A pasted filter at the size limit with a one-letter name, when every free name it could take is +/// in use, is refused rather than pasted under the name of the document's filter. +#[test] +fn a_paste_with_no_free_name_for_its_filter_is_refused() { + let mut s = session(); + for n in ('a'..='z').chain('0'..='9') { + run(&mut s, "svgFilter.define", json!({"xml": format!(r#""#)})); + } + run(&mut s, "svgFilter.define", json!({"xml": r#""#})); + let (open, close) = (r#""#); + let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len())); + let svg = format!( + r#"{big}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + let before = steps(&s); + assert!(err(&mut s, "edit.pasteInPlace", json!({})).contains("no free name")); + assert!(filter_effects(&s).is_empty(), "nothing pasted"); + assert_eq!(steps(&s), before); +} + +/// A pasted filter whose name holds a tab, a line feed or a carriage return keeps those characters +/// in its id under its new name. +#[test] +fn a_renamed_paste_keeps_whitespace_characters_in_its_id() { + for c in [" ", " ", " "] { + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": format!(r#""#)})); + let svg = format!( + r#""# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 1); + assert_ne!(pasted[0].0, names(&mut s)[0], "renamed"); + assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok(pasted[0].0.clone()), "{c}: its id is its name"); + } +} + /// Art in a symbol's definition that uses a filter follows its edits too. #[test] fn a_symbols_art_follows_a_filter_edit() { diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index 410bd473da..febc220296 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -84,7 +84,7 @@ fn the_builtin_library_is_original_art_generated_in_code() { let mut s = Session::new(); let list = run(&mut s, "symbol.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert_eq!(libs.len(), 3, "{libs:?}"); + assert_eq!(libs.len(), 4, "{libs:?}"); assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn"))); assert_eq!( (libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()), @@ -94,6 +94,10 @@ fn the_builtin_library_is_original_art_generated_in_code() { (libs[2]["id"].as_str(), libs[2]["name"].as_str(), libs[2]["category"].as_str()), (Some("map-markers"), Some("Map Markers"), Some("builtIn")) ); + assert_eq!( + (libs[3]["id"].as_str(), libs[3]["name"].as_str(), libs[3]["category"].as_str()), + (Some("inventory-icons"), Some("Inventory Icons"), Some("builtIn")) + ); let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"})); let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]); @@ -129,6 +133,32 @@ fn ui_frames_symbols_carry_default_nine_slice_when_added() { )); } +#[test] +fn inventory_icons_symbols_add_without_nine_slice() { + let mut s = session(); + let lib = run(&mut s, "symbol.library", json!({"library": "inventory-icons"})); + let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Sword", "Shield", "Potion", "Key", "Gem"]); + let mut placed = Vec::new(); + for (i, name) in names.iter().enumerate() { + let r = run( + &mut s, + "symbol.addFromLibrary", + json!({"library": "inventory-icons", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}), + ); + assert_eq!(r["added"], json!([name])); + placed.push(r["placed"].as_u64().unwrap()); + } + let d = doc(&s); + for name in &names { + assert_eq!(d.symbol_nine_slice(name), None, "{name} should not carry 9-slice guides"); + } + assert!(matches!( + d.node(NodeId(placed[0])).map(|n| &n.kind), + Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == "Sword" + )); +} + #[test] fn map_markers_symbols_add_without_nine_slice() { let mut s = session(); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 885ce09e1c..f49a88c80b 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -280,6 +280,37 @@ fn metrics_pair_step_preserves_the_drawn_auto_position() { assert!((moved - s.prefs.tracking_increment * 0.1).abs() < 0.01, "V moves by one kerning increment: {moved}"); } +/// At 50% Horizontal Scale the font's pair reads as the same thousandths of an em as at 100%: +/// kerning is measured in the em as the scale draws it (`vectorcraft_text::spacing_scale`), so the +/// value read keeps V where the font's kerning draws it, and a step moves V half as far as at 100%. +#[test] +fn horizontally_scaled_pair_reads_as_the_kerning_that_keeps_it() { + use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + + let db = vectorcraft_text::FontDb::global(); + db.add_font(pair_kerning_font().unwrap()); + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AV", "size": 100, "font": PAIR_KERNING_FAMILY})).unwrap()["id"].as_u64().unwrap(), + ); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 2, "hScale": 50})).unwrap(); + let before = obj(&s, id); + assert_eq!(before.runs[0].style.h_scale, 50.0); + let auto = vectorcraft_text::layout(db, &before); + let drawn_v = |layout: &vectorcraft_text::TextLayout| layout.glyphs.iter().find(|g| g.byte == 1).unwrap().xf.as_coeffs()[4]; + let read = crate::cmd::effective_kerning(db, &before, &auto, 0, 1); + assert!((read + 160.0).abs() < 0.01, "the font's -160/1000 em: {read}"); + let mut same = before.clone(); + vectorcraft_text::edit::style_range(&mut same.runs, 0, 1, |st| st.kerning = Some(read)); + assert!((drawn_v(&vectorcraft_text::layout(db, &same)) - drawn_v(&auto)).abs() < 0.01); + + s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap(); + let after = obj(&s, id); + assert!((after.runs[0].style.kerning.unwrap() + 160.0 - s.prefs.tracking_increment).abs() < 0.01); + let moved = drawn_v(&vectorcraft_text::layout(db, &after)) - drawn_v(&auto); + assert!((moved - s.prefs.tracking_increment * 0.05).abs() < 0.01, "V moves by half a kerning increment at 100%: {moved}"); +} + #[test] fn effective_auto_kerning_at_area_line_end_survives_unkerned_wrap() { use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; @@ -467,6 +498,85 @@ fn type_commands_refuse_a_number_or_boolean_given_as_text() { assert!(!t.ruby.is_empty() && t.ruby.iter().all(|r| !r.overhang && r.size_percent == 50.0), "{:?}", t.ruby); } +/// The Character commands, Ruby and Move Type Path Handle refuse a param of the wrong type with an +/// error naming the param, also when another param would change something, and leave the +/// document, its revision, the selection and the undo history as they were. Null counts as a param +/// left out, which keeps its default, and `size` and `leading` take a length with a unit. +#[test] +fn character_ruby_and_path_handle_refuse_a_param_of_the_wrong_type() { + use crate::tests::{history, not_a_number, select_with_a_step_to_redo}; + let mut s = session(); + let id = text(&mut s, "abc"); + let path = s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 300, "in": [50, 300], "out": [150, 300]}, {"x": 400, "y": 300}]})); + let on_path = s.execute("text.createInPath", &json!({"path": path.unwrap()["id"], "mode": "onPath", "text": "Along"})).unwrap()["id"].clone(); + select_with_a_step_to_redo(&mut s, &[id]); + let string = |k: &str| format!("`{k}` must be a string"); + let tags = "features must be a list of tags".to_string(); + let which = "`which` must be one of in, out".to_string(); + let handle = |which: Value| json!({"id": on_path, "anchor": 0, "which": which, "x": 100, "y": 250}); + let mut calls = vec![ + ("text.setStyle", json!({"font": 5}), string("font")), + ("text.setStyle", json!({"style": true}), string("style")), + ("text.setStyle", json!({"size": 30, "style": ["Bold"]}), string("style")), + ("text.setStyle", json!({"justify": 1}), string("justify")), + ("text.setStyle", json!({"size": 30, "justify": {"value": "center"}}), string("justify")), + ("text.setStyle", json!({"features": ["dlig", 5]}), tags.clone()), + ("text.setStyle", json!({"leading": true}), "leading must be a number or \"auto\"".to_string()), + ("text.setStyle", json!({"leading": "12abc"}), "leading must be a number or \"auto\"".to_string()), + ("text.setRangeStyle", json!({"id": id.0, "font": 5}), string("font")), + ("text.setRangeStyle", json!({"id": id.0, "size": 30, "style": false}), string("style")), + ("text.setRangeStyle", json!({"id": id.0, "features": [null]}), tags), + ("type.ruby", json!({"text": 5}), string("text")), + ("type.ruby", json!({"remove": true, "text": ["a"]}), string("text")), + ("type.ruby", json!({"text": "a", "position": 1}), string("position")), + ("type.ruby", json!({"text": "a", "align": true}), string("align")), + ("text.setPathHandle", handle(json!(1)), which.clone()), + ("text.setPathHandle", handle(json!("up")), which), + ]; + calls.extend( + [ + ("text.setStyle", json!({"size": true}), "size"), + ("text.setStyle", json!({"size": "big"}), "size"), + ("text.setStyle", json!({"size": "20abc"}), "size"), + ("text.setStyle", json!({"tracking": "20abc"}), "tracking"), + ("text.setStyle", json!({"font": "Inter", "size": [12]}), "size"), + ("text.setStyle", json!({"tracking": "wide"}), "tracking"), + ("text.setStyle", json!({"size": 30, "tracking": false}), "tracking"), + ] + .map(|(cmd, p, key)| { + let (_, p, msg) = not_a_number(cmd, p, key); + (cmd, p, msg) + }), + ); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.revision, st.selection.objects.clone(), history(s)) + }; + let before = state(&s); + let wrong: Vec = calls + .iter() + .filter_map(|(cmd, p, want)| { + let r = s.execute(cmd, p); + let refused = matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want); + let unchanged = state(&s) == before; + (!refused || !unchanged).then(|| format!("{cmd} {p}: {r:?}, unchanged: {unchanged}")) + }) + .collect(); + assert!(wrong.is_empty(), "not refused: {wrong:#?}"); + // Null keeps each default; a size and a leading with a unit are lengths. + let r = json!({"font": null, "style": null, "justify": null, "tracking": null, "features": null, "leading": null, "size": "5 mm"}); + s.execute("text.setStyle", &r).unwrap(); + let st = obj(&s, id).runs[0].style.clone(); + assert!((st.size - 5.0 * 72.0 / 25.4).abs() < 1e-6 && st.tracking == 0.0 && st.leading.is_none(), "{st:?}"); + s.execute("text.setStyle", &json!({"size": "12 pt", "leading": "18 pt", "tracking": 50})).unwrap(); + let st = obj(&s, id).runs[0].style.clone(); + assert_eq!((st.size, st.leading, st.tracking), (12.0, Some(18.0), 50.0)); + s.execute("type.ruby", &json!({"text": "a", "position": null, "align": null})).unwrap(); + let ruby = obj(&s, id).ruby; + assert!(ruby.iter().all(|r| r.position == vectorcraft_doc::RubyPosition::Above && r.align == vectorcraft_doc::RubyAlign::Center), "{ruby:?}"); + s.execute("text.setPathHandle", &handle(Value::Null)).unwrap(); +} + /// Where each glyph of type object `id` is drawn from (its origin in font units), document space. fn glyph_pens(s: &Session, id: NodeId) -> Vec<(usize, Point)> { let t = obj(s, id); @@ -3358,6 +3468,75 @@ fn glyph_alternates_query_reports_the_fallback_glyph_that_is_drawn() { assert_eq!(query["chosen"], json!(glyph.gid), "an overflowing character reports the fallback glyph it is drawn with"); } +/// `text.setGlyphAlternate` with `gid: null` reports the glyph the character is drawn with, as +/// `text.glyphAlternates` does: the fallback face's glyph for a character the font lacks, laid out +/// or overflowing, and the capital that All Caps draws for an a. +#[test] +fn a_glyph_choice_taken_away_reports_the_glyph_drawn() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let mut s = session(); + let reset = |s: &mut Session, id: NodeId, start: usize| { + s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": start, "gid": null})).unwrap()["gid"].clone() + }; + let chosen = |s: &mut Session, id: NodeId, start: usize| { + s.execute("text.glyphAlternates", &json!({"id": id.0, "start": start})).unwrap()["chosen"].clone() + }; + + let ch = 'Ƃ'; + assert_eq!(face.glyph_for(ch), 0); + let point = json!({"x": 0, "y": 0, "text": ch.to_string(), "font": alternates_family(true)}); + let id = NodeId(s.execute("text.create", &point).unwrap()["id"].as_u64().unwrap()); + let drawn = vectorcraft_text::layout(db, &obj(&s, id)).glyphs[0].gid; + assert_ne!(drawn, 0); + assert_eq!(reset(&mut s, id, 0), json!(drawn), "the fallback glyph"); + assert_eq!(chosen(&mut s, id, 0), json!(drawn)); + + let area = json!({"x": 0, "y": 300, "text": ch.to_string(), "font": alternates_family(true), "area": {"width": 200, "height": 2}}); + let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap()); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + assert_eq!(reset(&mut s, boxed, 0), json!(drawn), "the overflowing character's fallback glyph"); + + let caps = NodeId( + s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xaay", "size": 20, "font": alternates_family(true)})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("text.setRangeStyle", &json!({"id": caps.0, "start": 0, "end": 4, "allCaps": true})).unwrap(); + let drawn = vectorcraft_text::layout(db, &obj(&s, caps)).glyphs.iter().find(|g| g.byte == 1).expect("the a is laid out").gid; + assert_ne!(drawn, face.glyph_for('a'), "All Caps draws the a as A"); + assert_eq!(reset(&mut s, caps, 1), json!(drawn), "the capital drawn"); + assert_eq!(chosen(&mut s, caps, 1), json!(drawn)); +} + +/// A run that holds a choice for its first character and goes on past it, as a file may have, +/// draws Source Serif 4's fi ligature for the f and the i after that character. `gid: null` for the +/// i leaves the text as it is and reports the ligature, as `text.glyphAlternates` does. +#[test] +fn a_glyph_choice_taken_away_inside_a_ligature_reports_the_ligature() { + let db = vectorcraft_text::FontDb::global(); + let face = db.face("Source Serif 4", "Regular").expect("the bundled face"); + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "xfin", "size": 40, "font": "Source Serif 4"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let mut runs = obj(&s, id).runs; + runs[0].style.glyph_alternate = Some(face.choice('x', face.glyph_for('x'))); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let Some(NodeKind::Text(text)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("text") }; + text.runs = runs.clone(); + let ligature = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.iter().find(|g| g.byte == 1 && g.len == 2).expect("f + i is one glyph").gid; + let chosen = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 2})).unwrap()["chosen"].clone(); + assert_eq!(chosen, json!(ligature)); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 2, "gid": null})).unwrap(); + assert_eq!(r["gid"], chosen, "the ligature drawn for the i"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no edit"); + assert_eq!(obj(&s, id).runs, runs, "the runs are kept"); +} + /// A fallback face draws Ka with the vowel sign I in one cluster, the vowel sign first. The glyph /// reported for Ka is the fallback face's glyph for Ka, laid out or overflowing, not the vowel /// sign's. diff --git a/crates/engine/src/tests/typescale.rs b/crates/engine/src/tests/typescale.rs index 5bc09827b9..f96193a6c4 100644 --- a/crates/engine/src/tests/typescale.rs +++ b/crates/engine/src/tests/typescale.rs @@ -345,3 +345,27 @@ fn scale_text_attributes_bakes_group_scale_and_undoes() { s.execute("edit.undo", &json!({})).unwrap(); near(text(&s, id).runs[0].style.size, 12.0); } + +/// Scale Text Attributes bakes a horizontal stretch into the Horizontal Scale: tracked type stays +/// where the stretch drew it, as tracking is measured in the em the Horizontal Scale draws +/// (`vectorcraft_text::spacing_scale`). It used to lose the stretch's share of the tracking. +#[test] +fn scale_text_attributes_keeps_tracked_type_where_it_was() { + let mut s = session(); + let id = create(&mut s, 20.0); + s.execute("text.setRangeStyle", &json!({"id": id.0, "tracking": 300})).unwrap(); + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + let pens = |s: &Session| { + let t = text(s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + lay.glyphs.iter().map(|g| t.xf * (g.xf * Point::ZERO)).collect::>() + }; + let before = pens(&s); + s.execute("type.scaleTextAttributes", &json!({})).unwrap(); + near(text(&s, id).runs[0].style.h_scale, 200.0); + let after = pens(&s); + assert_eq!(before.len(), after.len()); + for (b, a) in before.iter().zip(&after) { + assert!((*a - *b).hypot() < 1e-6, "{before:?} {after:?}"); + } +} diff --git a/crates/engine/src/tests/units.rs b/crates/engine/src/tests/units.rs index 1608c86c6a..6c859b7276 100644 --- a/crates/engine/src/tests/units.rs +++ b/crates/engine/src/tests/units.rs @@ -36,6 +36,19 @@ fn preferences_general_sets_the_open_documents_units_as_one_undo_step() { assert_eq!(s.prefs.units_general, "millimeters", "undo is the document's; the preference stays"); } +#[test] +fn preferences_general_with_document_units_false_sets_only_the_preference() { + let mut s = session(); + s.execute("document.setUnits", &json!({"units": "Millimeters"})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("prefs.set", &json!({"values": {"unitsGeneral": "inches"}, "documentUnits": false})).unwrap(); + assert_eq!((units(&s), s.prefs.units_general.as_str()), (Unit::Millimeters, "inches")); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + let e = s.execute("prefs.set", &json!({"key": "unitsGeneral", "value": "points", "documentUnits": "no"})).unwrap_err(); + assert!(e.to_string().contains("`documentUnits` must be true or false"), "{e}"); + assert_eq!((units(&s), s.prefs.units_general.as_str()), (Unit::Millimeters, "inches"), "nothing changes on error"); +} + #[test] fn new_documents_start_in_the_preference_and_document_setup_only_changes_the_document() { let mut s = Session::new(); @@ -186,3 +199,78 @@ fn east_asian_type_unit_leaves_the_document_in_points() { assert!((lead.unwrap() - Unit::Ha.to_pt(20.0)).abs() < 1e-9, "{lead:?}"); assert!((sz - 17.0 * 72.0 / 101.6).abs() < 1e-9); } + +/// A session whose Preferences › Units › General is `unit`, with no document open. +fn general_in(unit: &str) -> Session { + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "unitsGeneral", "value": unit})).unwrap(); + s +} + +/// `bytes` opened as `name` in `s` → the opened document's units. +fn opened_units(s: &mut Session, name: &str, bytes: &[u8]) -> Unit { + s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + units(s) +} + +/// The active document of a session in `unit`, exported as `format`. +fn exported(unit: &str, format: &str) -> Vec { + let mut s = session(); + s.execute("document.setUnits", &json!({"units": unit})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 30})).unwrap(); + let data = s.execute("document.export", &json!({"format": format})).unwrap()["dataBase64"].clone(); + vectorcraft_format::base64_decode(data.as_str().unwrap()).unwrap() +} + +/// A PostScript `.ai` with one empty layer and `header` among its comments. +fn postscript_ai(header: &str) -> Vec { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 14.0\n{header}%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n0 A\n0 Xw\n\nLB\n%AI5_EndLayer--\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n" + ) + .into_bytes() +} + +#[test] +fn files_that_record_no_units_open_in_the_general_unit() { + let pdf = vectorcraft_testkit::pdf::pdf(&[vectorcraft_testkit::pdf::PdfPage::new(120.0, 60.0, "0 0 0 rg 10 10 50 30 re f")], None); + let png = exported("Inches", "png"); + let ai = postscript_ai(""); + let mut s = general_in("Millimeters"); + assert_eq!(opened_units(&mut s, "plain.pdf", &pdf), Unit::Millimeters, "a PDF records no units (#5820)"); + assert_eq!(opened_units(&mut s, "image.png", &png), Unit::Millimeters, "nor does an image"); + assert_eq!(opened_units(&mut s, "old.ai", &ai), Unit::Millimeters, "nor a .ai without ruler units"); + // Only the units change: the page keeps its size in points. + s.execute("document.open", &json!({"name": "plain.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)})).unwrap(); + let board = s.doc().unwrap().doc.artboards[0].rect; + assert!((board.width() - 120.0).abs() < 1e-6 && (board.height() - 60.0).abs() < 1e-6, "{board:?}"); + // With the preference left at points, they open in points as before. + let mut p = general_in("Points"); + assert_eq!(opened_units(&mut p, "plain.pdf", &pdf), Unit::Points); +} + +#[test] +fn files_that_record_units_keep_them_whatever_the_general_unit() { + let mut s = general_in("Millimeters"); + assert_eq!(opened_units(&mut s, "inches.ai", &postscript_ai("%AI5_RulerUnits: 0\n")), Unit::Inches, "a .ai's ruler units"); + assert_eq!(opened_units(&mut s, "points.ai", &postscript_ai("%AI5_RulerUnits: 2\n")), Unit::Points, "ruler units in points are kept too"); + assert_eq!(opened_units(&mut s, "saved.vectorcraft", &exported("Inches", "vectorcraft")), Unit::Inches, "a native file"); + let svg = r#""#; + assert_eq!(opened_units(&mut s, "inches.svg", svg.as_bytes()), Unit::Inches, "an SVG's root size"); +} + +#[test] +fn revert_reopens_a_file_without_units_in_the_general_unit() { + let dir = std::env::temp_dir().join(format!("vc-5820-revert-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("plain.pdf"); + std::fs::write(&path, vectorcraft_testkit::pdf::pdf(&[vectorcraft_testkit::pdf::PdfPage::new(120.0, 60.0, "0 0 0 rg 10 10 50 30 re f")], None)) + .unwrap(); + let mut s = general_in("Millimeters"); + s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(units(&s), Unit::Millimeters); + s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 5, "height": 5})).unwrap(); + s.execute("document.setUnits", &json!({"units": "Inches"})).unwrap(); + s.execute("file.revert", &json!({})).unwrap(); + assert_eq!(units(&s), Unit::Millimeters, "as the file opens"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 3f364c2ce6..b222f32107 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -22,6 +22,8 @@ pub struct ViewInfo { /// View → Show Guides: the ruler guides show (and, unlocked, can be picked). pub guides: bool, pub snap_to_grid: bool, + /// View → Pixel Preview: while it is on, the tools use no Smart Guides. + pub pixel_preview: bool, pub show_bbox: bool, /// View → Snap to Pixel: drawing and moving land on whole pixels (points at 72 ppi). pub snap_to_pixel: bool, @@ -46,6 +48,7 @@ impl Default for ViewInfo { smart_guides: true, guides: true, snap_to_grid: false, + pixel_preview: false, show_bbox: true, snap_to_pixel: false, snap_to_point: true, @@ -335,6 +338,7 @@ impl Session { { let Some(st) = self.active.and_then(|i| self.docs.get(i)) else { return R::default() }; let (unit, stroke_unit) = (self.general_unit(), self.stroke_unit()); + let smart_guides = view.smart_guides && !view.pixel_preview; let cx = ToolContext { doc: &st.doc, ruler_origin: st.doc.ruler_origin_for(view.artboard), @@ -344,7 +348,7 @@ impl Session { isolation: st.isolation, paint: &self.paint, outline: view.outline, - smart_guides: view.smart_guides, + smart_guides, guides: view.guides && !self.menu.guides_locked, snap_to_grid: view.snap_to_grid, show_bbox: view.show_bbox, @@ -354,7 +358,7 @@ impl Session { snap_to_point: view.snap_to_point, snap_tangent: self.prefs.snap_tangent, snap_perpendicular: self.prefs.snap_perpendicular, - snap_to_glyph: view.snap_to_glyph && view.smart_guides && !view.snap_to_grid, + snap_to_glyph: view.snap_to_glyph && smart_guides && !view.snap_to_grid, glyph_snap: self.prefs.glyph_snap, corner_widgets: view.corner_widgets, fill_active: self.fill_active, @@ -704,20 +708,39 @@ impl Session { Ok(()) } + /// The artboard a guide made from a ruler belongs to: with the Artboard tool, its active + /// artboard (an artboard guide); with any other tool, none (a canvas guide). + pub fn ruler_guide_artboard(&self) -> Option { + let boards = self.active().map_or(0, |d| d.doc.artboards.len()); + let active = (self.tool.id() == "artboard").then(|| self.tool.options()["active"].as_u64()).flatten(); + active.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < boards) + } + /// A guide dragged out of a ruler, whatever the tool: a vertical one out of the left ruler, a /// horizontal one out of the top ruler. `ev` is the pointer in document space (a drag, then the /// release), over the canvas or not (`on_canvas`). The guide shows where the pointer is over /// the canvas, snapped as a moved guide is, and is made where the button is released over it /// (one undo step); released anywhere else, none is. With the Artboard tool it is an artboard - /// guide of the active artboard. + /// guide of the active artboard. With Preferences › Guides & Grid › Artboard Guides with + /// Cmd/Ctrl + Ruler Drag on, `mods.cmd` on the drag's first event swaps the two: with another + /// tool the guide is one of the view's active artboard (`view.artboard`), shown and made only + /// where it lies within that artboard, and with the Artboard tool it is a canvas guide. pub fn ruler_guide(&mut self, vertical: bool, ev: &PointerEvent, on_canvas: bool, view: ViewInfo) -> Result<()> { + use vectorcraft_tools::rulerguide::NewGuide; let g = match self.ruler_guide.take() { Some(g) => Some(g), None => { - let boards = self.active().map_or(0, |d| d.doc.artboards.len()); - let active = (self.tool.id() == "artboard").then(|| self.tool.options()["active"].as_u64()).flatten(); - let artboard = active.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < boards); - self.with_tool_cx(view, |_, cx| Some(vectorcraft_tools::rulerguide::NewGuide::new(cx, vertical, artboard))) + let artboard_tool = self.tool.id() == "artboard"; + let swap = self.prefs.cmd_ruler_drag_artboard_guides && ev.mods.cmd; + let artboard = self.ruler_guide_artboard(); + let view_board = view.artboard; + self.with_tool_cx(view, |_, cx| { + Some(match (swap, artboard_tool) { + (false, _) => NewGuide::new(cx, vertical, artboard), + (true, true) => NewGuide::new(cx, vertical, None), + (true, false) => NewGuide::within(cx, vertical, view_board), + }) + }) } }; let Some(mut g) = g else { return Ok(()) }; diff --git a/crates/engine/src/units.rs b/crates/engine/src/units.rs index edad5c532c..26fd9ba14f 100644 --- a/crates/engine/src/units.rs +++ b/crates/engine/src/units.rs @@ -44,7 +44,7 @@ impl Measure { } /// The unit a Units preference value names (points when it names none). -fn pref_unit(value: &str) -> Unit { +pub(crate) fn pref_unit(value: &str) -> Unit { Unit::named(value).unwrap_or_default() } diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index de14c38b5a..947cf559d0 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -9,10 +9,11 @@ use vectorcraft_engine::{Session, command_specs}; use vectorcraft_testkit::catch_quiet; use vectorcraft_testkit::fixtures::Fixture; use vectorcraft_testkit::invariants::{check_all, check_session, doc_json}; -use vectorcraft_testkit::strategies::{junk_params, junk_values, param_keys}; +use vectorcraft_testkit::strategies::{junk_params, junk_values, param_keys, safe_value}; /// Commands that replace/close the active document or touch the filesystem are fine to call, but a -/// few need their paths redirected into a temp dir (handled by `junk_params`). +/// few need their file and folder params redirected into a temp dir (`safe_value`, which +/// `junk_params` applies). fn safe_path() -> String { vectorcraft_testkit::temp_dir("sweep").join("out.bin").to_string_lossy().to_string() } @@ -230,6 +231,54 @@ fn tool_edit_state(s: &Session) -> ToolEditState { (docs, s.active_index(), s.paint.clone()) } +/// The params the tool-edit sweep sends `c`: junk params, then each documented key turned on and +/// off, with a string under a file or folder key replaced by a location inside `path`'s folder. +fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { + let mut cases = junk_params(c.params, path); + if heavy(c.id) { + cases.truncate(12); + } + for k in param_keys(c.params) { + for v in [json!(true), json!(false), json!(1), json!("on")] { + cases.push(json!({ k.as_str(): safe_value(&k, &v, path) })); + } + } + // Find Objects selects only with a filter, which one key at a time does not give it. + if c.id == "document.find" { + cases.extend([json!({"kind": "Path", "select": true}), json!({"name": "no such name", "select": true})]); + } + cases +} + +/// Every string the sweeps send under a key that names a file or folder to write is inside the +/// sweep's temp folder, so no run writes into the working directory. +#[test] +fn sweep_cases_name_files_only_inside_the_temp_folder() { + let path = safe_path(); + let dir = vectorcraft_testkit::temp_dir("sweep"); + let keys = ["path", "diffPath", "folder", "destinationFolder"]; + let mut seen = std::collections::BTreeSet::new(); + let mut outside = std::collections::BTreeSet::new(); + for c in command_specs() { + let mut cases = junk_params(c.params, &path); + cases.extend(tool_edit_cases(c, &path)); + for p in &cases { + let Some(o) = p.as_object() else { continue }; + for (k, v) in o.iter().filter(|(k, _)| keys.contains(&k.as_str())) { + seen.insert(k.clone()); + if let Some(s) = v.as_str() + && !std::path::Path::new(s).starts_with(&dir) + { + outside.insert(format!("{} {{\"{k}\": {v}}}", c.id)); + } + } + } + } + assert_eq!(seen.len(), keys.len(), "the sweeps send only {seen:?}"); + let outside: Vec = outside.into_iter().collect(); + assert!(outside.is_empty(), "{} cases name a location outside {}:\n{}", outside.len(), dir.display(), outside.join("\n")); +} + /// Every command that runs at once while the active tool computes an edit on another thread (a /// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the /// documents' revisions and selections, the active document and the current paint as they were, @@ -241,19 +290,7 @@ fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { let mut failures = vec![]; for fx in [Fixture::Single, Fixture::Multi] { for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) { - let mut cases = junk_params(c.params, &path); - if heavy(c.id) { - cases.truncate(12); - } - for k in param_keys(c.params) { - for v in [json!(true), json!(false), json!(1), json!("on")] { - cases.push(json!({ k.as_str(): v })); - } - } - // Find Objects selects only with a filter, which one key at a time does not give it. - if c.id == "document.find" { - cases.extend([json!({"kind": "Path", "select": true}), json!({"name": "no such name", "select": true})]); - } + let cases = tool_edit_cases(c, &path); for p in &cases { let mut s = fx.session(); let before = tool_edit_state(&s); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 424f30cdd7..f729ed394c 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -663,6 +663,26 @@ proptest! { survive(&svg, || vectorcraft_svg::import(&svg).ok())?; } + /// Clip paths made of text, of `` elements showing text, and of both with shapes, each with + /// hostile attributes, clipping art that may clip by them in turn. + #[test] + fn svg_text_clip_paths_never_panic( + text in prop::collection::vec(arb_svg_attr(), 0..5), + used in prop::collection::vec(arb_svg_attr(), 0..5), + clip in prop::collection::vec(arb_svg_attr(), 0..3), + body in prop::collection::vec(arb_svg_element(1), 0..3), + ) { + let svg = format!( + "abcClipit{}", + text.concat(), + clip.concat(), + text.concat(), + used.concat(), + body.concat() + ); + survive(&svg, || vectorcraft_svg::import(&svg).ok())?; + } + #[test] fn svg_mutated_export_never_panics( cut in 0usize..20_000, diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 16deb3d242..56ee67be17 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -59,9 +59,11 @@ fn dimension_length_scale_live_edit_undo_and_roundtrip() { run(&mut reopened, "object.scale", json!({"sx":50,"sy":100})); assert_eq!(text(&reopened, id), "10.00 in"); run(&mut reopened, "edit.clear", json!({})); - assert!(reopened.doc().unwrap().doc.node(NodeId(id)).is_none()); + assert_eq!(text(&reopened, id), "10.00 in", "deleting the art leaves the dimension"); + assert!(recipe(&reopened, id).source.is_none(), "no longer linked"); run(&mut reopened, "edit.undo", json!({})); assert_eq!(text(&reopened, id), "10.00 in"); + assert!(recipe(&reopened, id).source.is_some(), "undo links it again"); } /// Documents without dimensions skip the refresh, and lose the flag when the last goes. @@ -210,6 +212,313 @@ fn clicking_two_points_then_placing_measures_between_them() { assert_eq!(text(&s, id), "72.00 pt"); } +/// After two clicked points, a pointer beside them (between the perpendiculars at the points) +/// gives the distance between them (aligned), as does clicking again on the second point. Past +/// either point, the quarter that holds the direction straight up or down from it gives their +/// horizontal distance, and the quarter that holds the direction straight left or right gives +/// their vertical distance. The dimension stays linked to the anchors it measures. +#[test] +fn two_points_measure_horizontally_vertically_or_aligned() { + use vectorcraft_doc::dimension::Orientation; + for ((x, y), want, orientation) in [ + ((210.0, 120.0), "100.00 pt", Orientation::Horizontal), + ((90.0, 380.0), "100.00 pt", Orientation::Horizontal), + ((280.0, 220.0), "100.00 pt", Orientation::Vertical), + ((40.0, 310.0), "100.00 pt", Orientation::Vertical), + ((120.0, 160.0), "141.42 pt", Orientation::Aligned), + ((200.0, 300.0), "141.42 pt", Orientation::Aligned), + ((200.0, 200.0), "141.42 pt", Orientation::Aligned), + ] { + let mut s = session(); + let line = run(&mut s, "shape.line", json!({"x1":100,"y1":300,"x2":200,"y2":200}))["id"].as_u64().unwrap(); + s.select_tool("dimension", ViewInfo::default()).unwrap(); + for (px, py) in [(100.0, 300.0), (200.0, 200.0), (x, y)] { + ev(&mut s, PointerKind::Move, px, py); + ev(&mut s, PointerKind::Down, px, py); + ev(&mut s, PointerKind::Up, px, py); + } + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!((text(&s, id), recipe(&s, id).orientation), (want.to_string(), orientation), "pointer at ({x}, {y})"); + assert!(recipe(&s, id).source.is_some_and(|src| src.nodes() == vec![NodeId(line), NodeId(line)])); + if orientation != Orientation::Aligned { + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.scale", json!({"sx":200,"sy":200})); + assert_eq!(text(&s, id), "200.00 pt", "follows the art"); + } + } +} + +/// A third click a little past the second point, still within reach of it, places an aligned +/// dimension, also when Shift moved the second point away from where the pointer was: the click +/// counts as clicking again on the second point. +#[test] +fn clicking_again_by_the_second_point_places_an_aligned_dimension() { + use vectorcraft_doc::dimension::Orientation; + let click = |s: &mut Session, x: f64, y: f64, shift: bool| { + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + let e = PointerEvent::new(kind, x, y).with_mods(Mods { shift, ..Mods::default() }); + s.pointer(&e, ViewInfo::default()).unwrap(); + } + }; + // Free points, the third click 2.2 pt past the second. + let mut s = session(); + s.select_tool("dimension", ViewInfo::default()).unwrap(); + click(&mut s, 100.0, 300.0, false); + click(&mut s, 200.0, 200.0, false); + click(&mut s, 202.0, 201.0, false); + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!((text(&s, id), recipe(&s, id).orientation), ("141.42 pt".to_string(), Orientation::Aligned)); + // Shift puts the second point on the 45 degree line, about 21 pt from the pointer. + let mut s = session(); + s.select_tool("dimension", ViewInfo::default()).unwrap(); + click(&mut s, 100.0, 300.0, false); + click(&mut s, 260.0, 170.0, true); + click(&mut s, 262.0, 168.0, false); + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!((text(&s, id), recipe(&s, id).orientation), ("206.16 pt".to_string(), Orientation::Aligned)); +} + +/// Dragged out from a slanted segment, the dimension follows the drag the same way, wherever on +/// the segment the press was: beside the segment it measures its length, and past either end +/// its horizontal or vertical length. +#[test] +fn a_segment_drag_measures_horizontally_vertically_or_aligned() { + use vectorcraft_doc::dimension::Orientation; + for (press, (x, y), want, orientation) in [ + ((150.0, 250.0), (210.0, 120.0), "100.00 pt", Orientation::Horizontal), + ((110.0, 290.0), (210.0, 120.0), "100.00 pt", Orientation::Horizontal), + ((150.0, 250.0), (280.0, 220.0), "100.00 pt", Orientation::Vertical), + ((190.0, 210.0), (40.0, 310.0), "100.00 pt", Orientation::Vertical), + ((150.0, 250.0), (120.0, 160.0), "141.42 pt", Orientation::Aligned), + ((110.0, 290.0), (200.0, 300.0), "141.42 pt", Orientation::Aligned), + ] { + let mut s = session(); + run(&mut s, "shape.line", json!({"x1":100,"y1":300,"x2":200,"y2":200})); + s.select_tool("dimension", ViewInfo::default()).unwrap(); + ev(&mut s, PointerKind::Move, press.0, press.1); + ev(&mut s, PointerKind::Down, press.0, press.1); + ev(&mut s, PointerKind::Drag, (press.0 + x) / 2.0, (press.1 + y) / 2.0); + ev(&mut s, PointerKind::Drag, x, y); + ev(&mut s, PointerKind::Up, x, y); + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!((text(&s, id), recipe(&s, id).orientation), (want.to_string(), orientation), "pressed at {press:?}, dragged to ({x}, {y})"); + } +} + +/// Two points on one vertical line give an aligned dimension wherever the pointer goes: their +/// vertical distance is the distance between them, and they have no horizontal distance. +#[test] +fn points_on_a_vertical_line_measure_aligned() { + use vectorcraft_doc::dimension::Orientation; + for (x, y) in [(60.0, 200.0), (160.0, 80.0), (100.0, 40.0), (40.0, 340.0), (100.0, 300.0)] { + let mut s = session(); + s.select_tool("dimension", ViewInfo::default()).unwrap(); + for (px, py) in [(100.0, 100.0), (100.0, 300.0), (x, y)] { + ev(&mut s, PointerKind::Move, px, py); + ev(&mut s, PointerKind::Down, px, py); + ev(&mut s, PointerKind::Up, px, py); + } + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!((text(&s, id), recipe(&s, id).orientation), ("200.00 pt".to_string(), Orientation::Aligned), "pointer at ({x}, {y})"); + } +} + +/// The ends of a dimension's generated paths (extension lines first, then the dimension line), +/// rounded. +fn path_ends(s: &Session, id: u64) -> Vec> { + let round = |v: f64| (v * 1e6).round() / 1e6; + let doc = &s.doc().unwrap().doc; + let art = doc.node(NodeId(id)).unwrap().children().unwrap(); + art.iter().filter_map(|n| n.path_data()).map(|p| p.subpaths[0].anchors.iter().map(|a| (round(a.p.x), round(a.p.y))).collect()).collect() +} + +/// A horizontal dimension's line is horizontal and a vertical one's vertical, through the point +/// it was placed at, and each extension line runs from its point to the dimension line. Points +/// given right to left or bottom to top draw the same lines. +#[test] +fn horizontal_and_vertical_dimensions_draw_lines_along_their_axis() { + let mut s = session(); + let r = run(&mut s, "dimension.create", json!({"a":[100,300],"b":[200,200],"orientation":"horizontal","offset":-150})); + assert_eq!(r["label"], "100.00 pt"); + // Extension lines: 4 pt off each point, 6 pt past the line at y = 150. + let horizontal = vec![vec![(100.0, 296.0), (100.0, 144.0)], vec![(200.0, 196.0), (200.0, 144.0)], vec![(100.0, 150.0), (200.0, 150.0)]]; + assert_eq!(path_ends(&s, r["id"].as_u64().unwrap()), horizontal); + let r = run(&mut s, "dimension.create", json!({"a":[200,200],"b":[100,300],"orientation":"horizontal","offset":-50})); + let swapped = vec![vec![(200.0, 196.0), (200.0, 144.0)], vec![(100.0, 296.0), (100.0, 144.0)], vec![(200.0, 150.0), (100.0, 150.0)]]; + assert_eq!(path_ends(&s, r["id"].as_u64().unwrap()), swapped, "the line stays on the side the offset puts it"); + // A vertical dimension 50 pt left of the first point: the line at x = 50. + let r = run(&mut s, "dimension.create", json!({"a":[100,300],"b":[200,200],"orientation":"vertical","offset":50})); + assert_eq!(r["label"], "100.00 pt"); + let vertical = vec![vec![(96.0, 300.0), (44.0, 300.0)], vec![(196.0, 200.0), (44.0, 200.0)], vec![(50.0, 300.0), (50.0, 200.0)]]; + assert_eq!(path_ends(&s, r["id"].as_u64().unwrap()), vertical); +} + +/// A horizontal dimension stays horizontal when it or the art it measures turns: it shows the +/// new horizontal distance, and 0 when the points come one above the other. It is not removed. +#[test] +fn turned_horizontal_dimensions_stay_horizontal() { + use vectorcraft_doc::dimension::Orientation; + let mut s = session(); + let id = run(&mut s, "dimension.create", json!({"a":[100,200],"b":[200,260],"orientation":"horizontal","offset":-50}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.rotate", json!({"angle":90,"origin":[150,230]})); + assert_eq!((text(&s, id), recipe(&s, id).orientation), ("60.00 pt".to_string(), Orientation::Horizontal)); + // The points are now at y = 180 and 280: the line stays 50 pt above the upper one instead of + // crossing between them. + let d = recipe(&s, id); + let mut ys = [d.a.y.round(), d.b.y.round()]; + ys.sort_by(f64::total_cmp); + assert_eq!(ys, [180.0, 280.0]); + assert!(path_ends(&s, id)[2].iter().all(|(_, y)| (y - 130.0).abs() < 1e-6), "{:?}", path_ends(&s, id)); + let line = run(&mut s, "shape.line", json!({"x1":100,"y1":400,"x2":200,"y2":400}))["id"].as_u64().unwrap(); + let anchor = |anchor: u64| json!({"node":line,"subpath":0,"anchor":anchor}); + let src = json!({"kind":"points","a":anchor(0),"b":anchor(1)}); + let id = run(&mut s, "dimension.create", json!({"source":src,"orientation":"horizontal"}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.rotate", json!({"angle":90})); + assert_eq!((text(&s, id), recipe(&s, id).orientation), ("0.00 pt".to_string(), Orientation::Horizontal)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(text(&s, id), "100.00 pt"); +} + +/// The line of a linked horizontal dimension keeps its gap from the outermost point on its side +/// when the art turns, so it stays clear of the art: after a half turn the line is still 50 pt +/// above the upper point, which is now the other anchor. +#[test] +fn a_linked_horizontal_dimension_keeps_its_gap_from_turned_art() { + let mut s = session(); + let line = run(&mut s, "shape.line", json!({"x1":100,"y1":300,"x2":200,"y2":200}))["id"].as_u64().unwrap(); + let anchor = |anchor: u64| json!({"node":line,"subpath":0,"anchor":anchor}); + let src = json!({"kind":"points","a":anchor(0),"b":anchor(1)}); + let id = run(&mut s, "dimension.create", json!({"source":src,"orientation":"horizontal","offset":-150}))["id"].as_u64().unwrap(); + assert_eq!(path_ends(&s, id)[2], vec![(100.0, 150.0), (200.0, 150.0)]); + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.rotate", json!({"angle":180,"origin":[150,250]})); + assert_eq!(text(&s, id), "100.00 pt"); + assert_eq!(path_ends(&s, id)[2], vec![(200.0, 150.0), (100.0, 150.0)]); + // Scaled to twice the size about the lower left point, the upper point is at y = 100. + run(&mut s, "object.scale", json!({"sx":200,"sy":200,"origin":[100,300]})); + assert_eq!(text(&s, id), "200.00 pt"); + assert_eq!(path_ends(&s, id)[2], vec![(300.0, 50.0), (100.0, 50.0)]); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(path_ends(&s, id)[2], vec![(100.0, 150.0), (200.0, 150.0)]); +} + +/// An unlinked horizontal dimension reflected on its own has its line where the reflection puts +/// it: a line above the points is below them after a flip top to bottom. +#[test] +fn a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side() { + let mut s = session(); + let id = run(&mut s, "dimension.create", json!({"a":[100,300],"b":[200,200],"orientation":"horizontal","offset":-150}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,250]})); + let d = recipe(&s, id); + assert_eq!((d.a.y.round(), d.b.y.round()), (200.0, 300.0)); + assert_eq!(path_ends(&s, id)[2], vec![(100.0, 350.0), (200.0, 350.0)]); + assert_eq!(text(&s, id), "100.00 pt"); +} + +/// The line of a linked horizontal dimension below both points stays below them when the art +/// turns a half turn; a line between the points keeps its distance from the first point. +#[test] +fn a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art() { + for (offset, want) in [(50.0, vec![(200.0, 350.0), (100.0, 350.0)]), (-50.0, vec![(200.0, 150.0), (100.0, 150.0)])] { + let mut s = session(); + let line = run(&mut s, "shape.line", json!({"x1":100,"y1":300,"x2":200,"y2":200}))["id"].as_u64().unwrap(); + let anchor = |anchor: u64| json!({"node":line,"subpath":0,"anchor":anchor}); + let src = json!({"kind":"points","a":anchor(0),"b":anchor(1)}); + let id = run(&mut s, "dimension.create", json!({"source":src,"orientation":"horizontal","offset":offset}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.rotate", json!({"angle":180,"origin":[150,250]})); + assert_eq!(text(&s, id), "100.00 pt"); + assert_eq!(path_ends(&s, id)[2], want, "offset {offset}"); + } +} + +/// A dimension recipe without an orientation reads as aligned. +#[test] +fn a_dimension_without_an_orientation_reads_as_aligned() { + use vectorcraft_doc::dimension::{Dimension, Orientation}; + let mut s = session(); + let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[30,40]}))["id"].as_u64().unwrap(); + let v = serde_json::to_value(recipe(&s, id)).unwrap(); + assert!(v.get("orientation").is_none()); + let d: Dimension = serde_json::from_value(v).unwrap(); + assert_eq!(d.orientation, Orientation::Aligned); +} + +/// `orientation` is checked on create and update, and only linear dimensions take one. +#[test] +fn dimension_orientation_is_checked() { + let mut s = session(); + for (p, want) in [ + (json!({"a":[0,0],"b":[30,40],"orientation":"horizontal"}), Some("30.00 pt")), + (json!({"a":[0,0],"b":[30,40],"orientation":"vertical"}), Some("40.00 pt")), + (json!({"a":[0,0],"b":[30,40],"orientation":"aligned"}), Some("50.00 pt")), + (json!({"a":[0,0],"b":[0,40],"orientation":"horizontal"}), Some("0.00 pt")), + (json!({"a":[0,0],"b":[30,40],"orientation":"diagonal"}), None), + (json!({"a":[0,0],"b":[30,40],"orientation":7}), None), + (json!({"a":[0,0],"b":[30,40],"orientation":null}), None), + (json!({"mode":"angular","a":[0,0],"b":[30,40],"vertex":[10,0],"orientation":"horizontal"}), None), + ] { + let before = serde_json::to_value(&*s.doc().unwrap().doc).unwrap(); + match (s.execute("dimension.create", &p), want) { + (Ok(r), Some(want)) => assert_eq!(r["label"], want, "{p}"), + (Err(_), None) => assert_eq!(serde_json::to_value(&*s.doc().unwrap().doc).unwrap(), before, "{p}"), + (r, _) => panic!("{p}: {r:?}"), + } + } + // An aligned dimension is written as before, without the field. + let doc = serde_json::to_string(&*s.doc().unwrap().doc).unwrap(); + assert_eq!(doc.matches("\"orientation\"").count(), 3, "only the horizontal and vertical ones"); + // dimension.update turns an existing linear dimension, and refuses the same bad values. + let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[30,40]}))["id"].as_u64().unwrap(); + let angle = run(&mut s, "dimension.create", json!({"mode":"angular","a":[0,0],"b":[30,40],"vertex":[10,0]}))["id"].as_u64().unwrap(); + for (orientation, want) in [("horizontal", "30.00 pt"), ("vertical", "40.00 pt"), ("aligned", "50.00 pt")] { + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":orientation})); + assert_eq!(text(&s, id), want); + } + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical"})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(text(&s, id), "50.00 pt", "one undo step"); + let before = serde_json::to_value(&*s.doc().unwrap().doc).unwrap(); + for p in [ + json!({"ids":[id],"orientation":"diagonal"}), + json!({"ids":[id],"orientation":7}), + json!({"ids":[angle],"orientation":"vertical"}), + // A linear and an angular dimension together: neither changes. + json!({"ids":[id, angle],"orientation":"vertical"}), + ] { + assert!(s.execute("dimension.update", &p).is_err(), "{p}"); + assert_eq!(serde_json::to_value(&*s.doc().unwrap().doc).unwrap(), before, "{p}"); + } + // The orientation it already has, or aligned for an angular one, changes nothing and records + // no undo step: the undo after it goes back to the vertical dimension of the earlier update. + for p in [json!({"ids":[id],"orientation":"aligned"}), json!({"ids":[angle],"orientation":"aligned"})] { + run(&mut s, "dimension.update", p); + assert_eq!(serde_json::to_value(&*s.doc().unwrap().doc).unwrap(), before); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!(text(&s, id), "40.00 pt"); +} + +/// A dimension turned with `dimension.update` keeps its line on the side of the points it was +/// on: an aligned line 30 pt above a pair made right to left stays 30 pt above as horizontal, +/// and an aligned line below and right of slanted points goes 30 pt below the lower point. +#[test] +fn a_turned_dimension_keeps_its_line_on_its_side() { + let mut s = session(); + let id = run(&mut s, "dimension.create", json!({"a":[200,200],"b":[100,200],"offset":30}))["id"].as_u64().unwrap(); + assert_eq!(path_ends(&s, id)[2], vec![(200.0, 170.0), (100.0, 170.0)]); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"horizontal"})); + assert_eq!(path_ends(&s, id)[2], vec![(200.0, 170.0), (100.0, 170.0)]); + // The middle of the aligned line (about 171, 271) lies between the points' heights. + let id = run(&mut s, "dimension.create", json!({"a":[100,300],"b":[200,200],"offset":30}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"horizontal"})); + assert_eq!(path_ends(&s, id)[2], vec![(100.0, 330.0), (200.0, 330.0)]); +} + /// Dragging out from a corner of two straight segments measures the angle between them. #[test] fn dragging_out_from_a_corner_measures_its_angle() { @@ -260,6 +569,425 @@ fn dimension_anchor_links_and_native_file_survive_source_moves() { assert_eq!(text(&s, id), "100 pt"); } +/// The anchors of path `id`'s first subpath. +fn anchors(s: &Session, id: u64) -> Vec { + let doc = &s.doc().unwrap().doc; + doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect() +} +fn near(p: vectorcraft_geom::Point, q: vectorcraft_geom::Point) -> bool { + p.distance(q) < 1e-6 +} +/// Clicks with the Dimension tool at each point in turn. +fn clicks(s: &mut Session, points: &[(f64, f64)]) -> u64 { + s.select_tool("dimension", ViewInfo::default()).unwrap(); + for &(x, y) in points { + ev(s, PointerKind::Move, x, y); + ev(s, PointerKind::Down, x, y); + ev(s, PointerKind::Up, x, y); + } + s.doc().unwrap().selection.objects[0].0 +} + +/// A dimension from an anchor to a point on a straight segment follows the art at both ends: the +/// segment end keeps its place along the segment when the art is scaled, moved or reflected. +#[test] +fn a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 150.0), (120.0, 90.0)]); + let length = recipe(&s, id).length; + for (command, p) in [ + ("object.scale", json!({"sx":150,"sy":150})), + ("object.move", json!({"dx":40,"dy":-30})), + ("object.rotate", json!({"angle":30})), + ("object.reflect", json!({"axis":"vertical"})), + ] { + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, command, p); + let (d, at) = (recipe(&s, id), anchors(&s, rect)); + assert!(near(d.a, at[0]), "{command}: {:?} {:?}", d.a, at[0]); + assert!(near(d.b, at[1].midpoint(at[2])), "{command}: {:?} {:?}", d.b, at[1].midpoint(at[2])); + assert!(d.source.is_some(), "{command}: still linked"); + } + assert!((recipe(&s, id).length - 1.5 * length).abs() < 1e-6); +} + +/// A point off the art is held against the anchors of the art at the other end, and moves with it. +#[test] +fn a_dimension_to_a_point_off_the_art_moves_with_the_art() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(200.0, 200.0), (330.0, 260.0), (260.0, 330.0)]); + let before = recipe(&s, id); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.move", json!({"dx":40,"dy":-30})); + let d = recipe(&s, id); + let v = vectorcraft_geom::Vec2::new(40.0, -30.0); + assert!(near(d.a, before.a + v) && near(d.b, before.b + v), "{before:?} → {d:?}"); + assert!((d.length - before.length).abs() < 1e-6 && (d.offset - before.offset).abs() < 1e-6); + run(&mut s, "object.scale", json!({"sx":200,"sy":200})); + assert!((recipe(&s, id).length - 2.0 * before.length).abs() < 1e-6); +} + +/// When the art it measures is deleted or gets another number of anchors, a dimension stays where +/// it was, no longer linked: later edits of the art do not move it, and undo links it again. +#[test] +fn a_dimension_whose_art_changes_its_anchors_stays_where_it_was() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 150.0), (120.0, 90.0)]); + let before = recipe(&s, id); + let label = text(&s, id); + run(&mut s, "path.insertAnchor", json!({"id":rect,"segment":3,"t":0.5})); + let d = recipe(&s, id); + assert!(d.source.is_none(), "no longer linked"); + assert_eq!((d.a, d.b, d.offset, text(&s, id)), (before.a, before.b, before.offset, label.clone())); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.scale", json!({"sx":150,"sy":150})); + assert_eq!((recipe(&s, id).a, recipe(&s, id).b), (before.a, before.b), "does not follow the art"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(recipe(&s, id).source, before.source, "undo links it again"); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "edit.clear", json!({})); + assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none()); + assert_eq!((recipe(&s, id).source, text(&s, id)), (None, label)); +} + +/// A linked dimension whose art is reflected has its line on the reflected side: a line above the +/// top edge is below that edge's points after a flip top to bottom. +#[test] +fn a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side() { + use vectorcraft_doc::dimension::Orientation; + for orientation in ["aligned", "horizontal"] { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let at = anchors(&s, rect); + let top = |p: vectorcraft_geom::Point| (p.y - 100.0).abs() < 1e-9; + let (i, j) = (at.iter().position(|p| top(*p)).unwrap(), at.iter().rposition(|p| top(*p)).unwrap()); + let anchor = |anchor: usize| json!({"node":rect,"subpath":0,"anchor":anchor}); + let src = json!({"kind":"points","a":anchor(i),"b":anchor(j)}); + // The line 30 pt above the top edge: the offset is along the left normal of a → b when + // aligned, downward when horizontal. + let offset = if orientation == "aligned" && at[i].x > at[j].x { 30.0 } else { -30.0 }; + let id = run(&mut s, "dimension.create", json!({"source":src,"orientation":orientation,"offset":offset}))["id"].as_u64().unwrap(); + let line_y = |s: &Session| recipe(s, id).line_ends().0.y; + assert!((line_y(&s) - 70.0).abs() < 1e-6, "{orientation}: {}", line_y(&s)); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal"})); + let d = recipe(&s, id); + assert!(d.source.is_some()); + assert!(((d.a.y, d.b.y) == (200.0, 200.0)), "{orientation}: {d:?}"); + assert!((line_y(&s) - 230.0).abs() < 1e-6, "{orientation}: line at {}", line_y(&s)); + let want = if orientation == "aligned" { Orientation::Aligned } else { Orientation::Horizontal }; + assert_eq!(d.orientation, want); + run(&mut s, "edit.undo", json!({})); + assert!((line_y(&s) - 70.0).abs() < 1e-6); + } +} + +/// Reflected across the line through the two points it measures, an arch keeps those points +/// where they were, and the dimension's line goes to the other side with the arch. +#[test] +fn a_dimension_of_art_reflected_across_its_points_changes_sides() { + let mut s = session(); + let arch = json!([{"x":100,"y":200,"out":[100,150]},{"x":200,"y":200,"in":[200,150]}]); + let curve = run(&mut s, "path.create", json!({"anchors":arch,"closed":false}))["id"].as_u64().unwrap(); + let anchor = |anchor: u64| json!({"node":curve,"subpath":0,"anchor":anchor}); + let src = json!({"kind":"points","a":anchor(0),"b":anchor(1)}); + let id = run(&mut s, "dimension.create", json!({"source":src,"offset":-30}))["id"].as_u64().unwrap(); + assert!((recipe(&s, id).line_ends().0.y - 170.0).abs() < 1e-6); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,200]})); + let d = recipe(&s, id); + assert_eq!((d.a, d.b), (vectorcraft_geom::Point::new(100.0, 200.0), vectorcraft_geom::Point::new(200.0, 200.0))); + assert!((d.line_ends().0.y - 230.0).abs() < 1e-6, "below with the arch: {:?}", d.line_ends()); + // Reflected together with the art, it ends in the same place. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "select.set", json!({"ids":[curve, id]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,200]})); + assert!((recipe(&s, id).line_ends().0.y - 230.0).abs() < 1e-6, "{:?}", recipe(&s, id).line_ends()); +} + +/// A dimension between two paths that are each reflected in their own way in one edit is not +/// mirrored by the map of one of them. +#[test] +fn a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset() { + let mut s = session(); + let low = json!([{"x":100,"y":200,"out":[100,150]},{"x":200,"y":200,"in":[200,150]}]); + let high = json!([{"x":300,"y":200,"out":[300,100]},{"x":400,"y":200,"in":[400,100]}]); + let first = run(&mut s, "path.create", json!({"anchors":low,"closed":false}))["id"].as_u64().unwrap(); + let second = run(&mut s, "path.create", json!({"anchors":high,"closed":false}))["id"].as_u64().unwrap(); + let src = json!({"kind":"points","a":{"node":first,"subpath":0,"anchor":0},"b":{"node":second,"subpath":0,"anchor":1}}); + let id = run(&mut s, "dimension.create", json!({"source":src,"offset":30}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[first, second]})); + run(&mut s, "object.transformEach", json!({"reflectY":true})); + let d = recipe(&s, id); + assert!(d.source.is_some() && (d.a.y - d.b.y).abs() > 1.0, "{d:?}"); + assert!((d.offset - 30.0).abs() < 1e-6, "{d:?}"); +} + +/// A recipe's free points are checked: weights that do not add up to 1, or an end that is both an +/// anchor and a free point, are refused without changing the document. +#[test] +fn dimension_free_points_are_checked() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let original = serde_json::to_value(&*s.doc().unwrap().doc).unwrap(); + let w = |anchor: u64, weight: f64| json!({"subpath":0,"anchor":anchor,"weight":weight}); + let held = |anchors: Value, across: f64| json!({"kind":"anchors","node":rect,"anchors":anchors,"across":across}); + let on = |segment: u64, t: f64| json!({"kind":"onSegment","edge":{"node":rect,"subpath":0,"segment":segment},"t":t}); + let anchor = json!({"node":rect,"subpath":0,"anchor":0}); + for free in [ + held(json!([w(1, 0.5), w(2, 0.6)]), 0.0), + held(json!([w(1, 1.0)]), 0.0), + held(json!([w(1, 1e300), w(2, -1e300)]), 0.0), + held(json!([w(1, 0.5), w(99, 0.5)]), 0.0), + held(json!([w(1, 0.5), w(2, f64::MAX)]), 0.0), + held(json!([w(1, 0.5), w(2, 0.5)]), 1e300), + held(json!([w(1, 0.5), w(2, 0.25), w(3, 0.25)]), 0.5), + on(1, 1.5), + on(1, -0.1), + on(99, 0.5), + json!({"kind":"elsewhere","node":rect}), + ] { + let p = json!({"source":{"kind":"points","a":anchor,"freeB":free}}); + assert!(s.execute("dimension.create", &p).is_err(), "{p}"); + assert_eq!(serde_json::to_value(&*s.doc().unwrap().doc).unwrap(), original); + } + let both = json!({"source":{"kind":"points","a":anchor,"freeA":held(json!([w(1, 0.5), w(2, 0.5)]), 0.0),"b":anchor}}); + assert!(s.execute("dimension.create", &both).is_err()); + let at = anchors(&s, rect); + for (free, want) in [(held(json!([w(1, 0.5), w(2, 0.5)]), 0.0), at[1].midpoint(at[2])), (on(1, 0.5), at[1].midpoint(at[2]))] { + let ok = json!({"source":{"kind":"points","a":anchor,"freeB":free}}); + let id = run(&mut s, "dimension.create", ok)["id"].as_u64().unwrap(); + assert!(near(recipe(&s, id).b, want), "{:?}", recipe(&s, id).b); + } +} + +/// A point off a straight two-anchor line is held by its distance along and across the line: it +/// moves, turns and scales with the line. +#[test] +fn a_dimension_to_a_point_off_a_line_follows_the_line() { + let mut s = session(); + let line = run(&mut s, "shape.line", json!({"x1":100,"y1":100,"x2":200,"y2":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (150.0, 160.0), (60.0, 130.0)]); + let d = recipe(&s, id); + assert!(d.source.as_ref().is_some_and(|src| src.nodes() == vec![NodeId(line), NodeId(line)]), "{:?}", d.source); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"aligned"})); + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.rotate", json!({"angle":90,"origin":[100,100]})); + run(&mut s, "object.scale", json!({"sx":200,"sy":200,"origin":[100,100]})); + run(&mut s, "object.move", json!({"dx":10,"dy":20})); + let at = anchors(&s, line); + let (o, u) = (at[0], at[1] - at[0]); + // 50 along the line and 60 across it before, now in the line's new frame at twice the size. + let want = o + u * 0.5 + vectorcraft_geom::Vec2::new(-u.y, u.x) * 0.6; + let d = recipe(&s, id); + assert!(near(d.a, o) && near(d.b, want), "{d:?} want {want:?}"); + assert!((d.length - 2.0 * (50.0f64.hypot(60.0))).abs() < 1e-6); +} + +/// A point on a straight segment stays on the segment when its handles are edited into a curve. +#[test] +fn a_point_on_a_segment_stays_on_it_when_the_segment_curves() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 150.0), (120.0, 90.0)]); + let at = anchors(&s, rect); + assert!(near(at[1], vectorcraft_geom::Point::new(200.0, 100.0)) && near(at[2], vectorcraft_geom::Point::new(200.0, 200.0)), "{at:?}"); + let a = |p: vectorcraft_geom::Point| json!({"x":p.x,"y":p.y}); + let mut curved = vec![a(at[0]), a(at[1]), a(at[2]), a(at[3])]; + curved[1]["out"] = json!([240, 110]); + curved[2]["in"] = json!([240, 190]); + run(&mut s, "path.setAnchors", json!({"id":rect,"subpaths":[{"anchors":curved,"closed":true}]})); + let d = recipe(&s, id); + assert!(d.source.is_some(), "still linked"); + assert!(near(d.b, vectorcraft_geom::Point::new(230.0, 150.0)), "on the curve: {:?}", d.b); +} + +/// The line of a linked dimension of a curved two-anchor path goes to the reflected side when the +/// path is reflected: its handles tell a reflection from a turn. +#[test] +fn a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side() { + let mut s = session(); + let arch = json!([{"x":100,"y":200,"out":[100,150]},{"x":200,"y":200,"in":[200,150]}]); + let curve = run(&mut s, "path.create", json!({"anchors":arch,"closed":false}))["id"].as_u64().unwrap(); + let anchor = |anchor: u64| json!({"node":curve,"subpath":0,"anchor":anchor}); + let src = json!({"kind":"points","a":anchor(0),"b":anchor(1)}); + // The line 30 pt below the two points (the left normal of a → b points down). + let id = run(&mut s, "dimension.create", json!({"source":src,"offset":30}))["id"].as_u64().unwrap(); + assert!((recipe(&s, id).line_ends().0.y - 230.0).abs() < 1e-6); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.reflect", json!({"axis":"vertical"})); + let d = recipe(&s, id); + assert!((d.a.y, d.b.y) == (200.0, 200.0) && d.a.x > d.b.x, "{d:?}"); + assert!((d.line_ends().0.y - 230.0).abs() < 1e-6, "below the points: {:?}", d.line_ends()); + run(&mut s, "object.reflect", json!({"axis":"horizontal"})); + let d = recipe(&s, id); + assert!((d.line_ends().0.y - (d.a.y - 30.0)).abs() < 1e-6, "above the points: {d:?}"); +} + +/// A point off an arch, whose anchors lie on one line, is held against its anchors and handles: +/// it is reflected with the arch, to the same side as the dimension's line. +#[test] +fn a_point_off_an_arch_is_reflected_with_the_arch() { + let mut s = session(); + let arch = json!([{"x":100,"y":200,"out":[100,150]},{"x":200,"y":200,"in":[200,150]}]); + let curve = run(&mut s, "path.create", json!({"anchors":arch,"closed":false}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 200.0), (150.0, 120.0), (60.0, 120.0)]); + let d = recipe(&s, id); + assert!(d.source.as_ref().is_some_and(|src| src.nodes() == vec![NodeId(curve), NodeId(curve)]), "{:?}", d.source); + assert!(near(d.b, vectorcraft_geom::Point::new(150.0, 120.0)), "{:?}", d.b); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,200]})); + let d = recipe(&s, id); + assert!(near(d.a, vectorcraft_geom::Point::new(100.0, 200.0)), "{:?}", d.a); + assert!(near(d.b, vectorcraft_geom::Point::new(150.0, 280.0)), "below with the arch: {:?}", d.b); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.reflect", json!({"axis":"vertical","origin":[150,0]})); + let d = recipe(&s, id); + assert!(near(d.a, vectorcraft_geom::Point::new(200.0, 200.0)), "{:?}", d.a); + assert!(near(d.b, vectorcraft_geom::Point::new(150.0, 120.0)), "above with the arch: {:?}", d.b); +} + +/// A point beside a curve that is almost straight is still held against it. +#[test] +fn a_point_beside_an_almost_straight_curve_follows_it() { + let mut s = session(); + let flat = json!([{"x":100,"y":200,"out":[100,199.999]},{"x":200,"y":200}]); + let curve = run(&mut s, "path.create", json!({"anchors":flat,"closed":false}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 200.0), (150.0, 150.0), (60.0, 120.0)]); + let d = recipe(&s, id); + assert!(d.source.as_ref().is_some_and(|src| src.nodes() == vec![NodeId(curve), NodeId(curve)]), "{:?}", d.source); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.move", json!({"dx":40,"dy":-30})); + let d = recipe(&s, id); + assert!(near(d.b, vectorcraft_geom::Point::new(190.0, 120.0)), "{:?}", d.b); +} + +/// A point off a loop whose two anchors are in one place is held against the loop's handles. +#[test] +fn a_point_off_a_loop_with_its_anchors_in_one_place_follows_it() { + let mut s = session(); + let tear = json!([{"x":100,"y":200,"out":[60,120]},{"x":100,"y":200,"in":[140,120]}]); + let curve = run(&mut s, "path.create", json!({"anchors":tear,"closed":false}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 200.0), (100.0, 60.0), (30.0, 130.0)]); + let d = recipe(&s, id); + assert!(d.source.as_ref().is_some_and(|src| src.nodes() == vec![NodeId(curve), NodeId(curve)]), "{:?}", d.source); + run(&mut s, "select.set", json!({"ids":[curve]})); + run(&mut s, "object.move", json!({"dx":40,"dy":-30})); + let d = recipe(&s, id); + assert!(near(d.b, vectorcraft_geom::Point::new(140.0, 30.0)), "{:?}", d.b); +} + +/// Beside a straight two-anchor line, a point is moved by a reflection as a half turn would move +/// it: the line's positions alone do not tell the two apart. +#[test] +fn a_point_beside_a_reflected_line_moves_as_a_half_turn_would() { + let mut s = session(); + let line = run(&mut s, "shape.line", json!({"x1":100,"y1":100,"x2":200,"y2":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (150.0, 160.0), (60.0, 130.0)]); + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.reflect", json!({"axis":"vertical","origin":[150,0]})); + let d = recipe(&s, id); + assert!(d.source.is_some()); + assert!(near(d.a, vectorcraft_geom::Point::new(200.0, 100.0)), "{:?}", d.a); + assert!(near(d.b, vectorcraft_geom::Point::new(150.0, 40.0)), "{:?}", d.b); +} + +/// Opening a closed path that a dimension measures leaves the dimension where it was, no longer +/// linked, and undo links it again. +#[test] +fn a_dimension_whose_art_is_opened_stays_where_it_was() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 150.0), (120.0, 90.0)]); + let before = recipe(&s, id); + let label = text(&s, id); + let a = |p: vectorcraft_geom::Point| json!({"x":p.x,"y":p.y}); + let open: Vec = anchors(&s, rect).into_iter().map(a).collect(); + run(&mut s, "path.setAnchors", json!({"id":rect,"subpaths":[{"anchors":open,"closed":false}]})); + let d = recipe(&s, id); + assert!(d.source.is_none(), "no longer linked"); + assert_eq!((d.a, d.b, d.offset, text(&s, id)), (before.a, before.b, before.offset, label)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(recipe(&s, id).source, before.source, "undo links it again"); +} + +/// An angle whose arm becomes a curve, and an arc radius whose arc stops being circular, stay where +/// they were, no longer linked. +#[test] +fn angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were() { + let mut s = session(); + let first = edge(&mut s); + let second = run(&mut s, "shape.line", json!({"x1":100,"y1":100,"x2":100,"y2":172}))["id"].as_u64().unwrap(); + let angle = json!({"mode":"angular","source":{"kind":"angle","first":{"node":first,"subpath":0,"segment":0},"second":{"node":second,"subpath":0,"segment":0}}}); + let id = run(&mut s, "dimension.create", angle)["id"].as_u64().unwrap(); + let label = text(&s, id); + let curved = json!([{"x":100,"y":100,"out":[140,130]},{"x":100,"y":172}]); + run(&mut s, "path.setAnchors", json!({"id":second,"subpaths":[{"anchors":curved,"closed":false}]})); + assert_eq!((recipe(&s, id).source, text(&s, id)), (None, label)); + let circle = run(&mut s, "shape.ellipse", json!({"x":300,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap(); + let arc = json!({"mode":"radius","source":{"kind":"arc","edge":{"node":circle,"subpath":0,"segment":0}},"options":{"units":"in","precision":1}}); + let id = run(&mut s, "dimension.create", arc)["id"].as_u64().unwrap(); + assert_eq!(text(&s, id), "1.0 in"); + run(&mut s, "select.set", json!({"ids":[circle]})); + run(&mut s, "object.scale", json!({"sx":200,"sy":100})); + assert_eq!((recipe(&s, id).source, text(&s, id)), (None, "1.0 in".to_string())); +} + +/// Saved and opened again, a dimension to points that are not anchors still follows its art. +#[test] +fn free_points_survive_a_native_file() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(200.0, 150.0), (330.0, 260.0), (260.0, 330.0)]); + let before = recipe(&s, id); + let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let mut reopened = Session::new(); + reopened.add_document(doc, None); + assert_eq!(recipe(&reopened, id).source, before.source); + run(&mut reopened, "select.set", json!({"ids":[rect]})); + run(&mut reopened, "object.move", json!({"dx":40,"dy":-30})); + let d = recipe(&reopened, id); + let v = vectorcraft_geom::Vec2::new(40.0, -30.0); + assert!(near(d.a, before.a + v) && near(d.b, before.b + v), "{before:?} → {d:?}"); +} + +/// A linked dimension opened from a file with options it cannot be drawn with keeps its art, as a +/// plain group, when the art it measures is deleted. +#[test] +fn a_dimension_that_cannot_be_drawn_again_keeps_its_art() { + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":100}))["id"].as_u64().unwrap(); + let id = clicks(&mut s, &[(100.0, 100.0), (200.0, 100.0), (150.0, 80.0)]); + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + let mut v: Value = serde_json::from_slice(&saved).unwrap(); + fn bad_precision(v: &mut Value) { + match v { + Value::Object(m) => { + if let Some(Value::Object(o)) = m.get_mut("dimension").and_then(|d| d.get_mut("options")) { + o.insert("precision".into(), json!(99)); + } + m.values_mut().for_each(bad_precision); + } + Value::Array(a) => a.iter_mut().for_each(bad_precision), + _ => {} + } + } + bad_precision(&mut v); + let mut reopened = Session::new(); + reopened.add_document(vectorcraft_format::load(&serde_json::to_vec(&v).unwrap()).unwrap(), None); + let art = reopened.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap().clone(); + run(&mut reopened, "select.set", json!({"ids":[rect]})); + run(&mut reopened, "edit.clear", json!({})); + let n = reopened.doc().unwrap().doc.node(NodeId(id)).cloned().expect("the dimension's art stays"); + assert!(n.extras().dimension.is_none(), "no longer a live dimension"); + assert_eq!(n.children().unwrap(), &art); +} + /// A linked dimension moved on its own keeps its new place when its art changes later; moved with /// its art, it keeps its distance from it. #[test] @@ -346,7 +1074,8 @@ fn an_expanded_dimension_stays_plain_art() { assert_eq!((art(&s, id), bounds(&s, id)), (plain, at)); run(&mut s, "edit.clear", json!({})); assert_eq!((art(&s, id), bounds(&s, id)), (plain, at)); - assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none()); + assert_eq!(text(&s, other), "20.00 in", "the live dimension stays, no longer linked"); + assert!(recipe(&s, other).source.is_none()); // Saved and opened again, it is still plain art. let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); let mut reopened = Session::new(); @@ -435,16 +1164,10 @@ fn an_expand_that_changes_no_art_leaves_a_dimension_live() { assert_eq!(art(&s, id), live); } -/// A dimension selected with the art it measures, or held by a selected group, expands the same -/// way: outlining that art does not remove it. +/// A dimension held by a selected group without the art it measures expands as a dimension +/// selected on its own does. #[test] -fn a_dimension_expanded_with_its_art_or_in_a_group_stays_plain_art() { - let mut s = session(); - let line = edge(&mut s); - let id = dim(&mut s, line); - run(&mut s, "select.set", json!({"ids":[line, id]})); - run(&mut s, "object.expand", json!({})); - stays_plain_art(&mut s, id); +fn a_dimension_expanded_in_a_group_without_its_art_stays_plain_art() { let mut s = session(); let line = edge(&mut s); let id = dim(&mut s, line); @@ -454,8 +1177,176 @@ fn a_dimension_expanded_with_its_art_or_in_a_group_stays_plain_art() { stays_plain_art(&mut s, id); } -/// Expand replacing only the art a selected dimension measures leaves the dimension's art as it -/// is, without a link to the art that went. +/// `command` on a dimension selected with the art it measures, or on a group holding both, leaves +/// the dimension's own lines and label as they are and replaces only the art: the dimension stays +/// where it was, no longer linked, and one undo links it again. +fn keeps_its_own_lines_and_label(command: &str) { + for grouped in [false, true] { + let context = format!("{command}, grouped: {grouped}"); + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setStroke", json!({"ids":[art_id],"color":"#000000"})); + run(&mut s, "select.set", json!({"ids":[art_id]})); + run(&mut s, "appearance.addStroke", json!({})); + let id = dim(&mut s, art_id); + let live = art(&s, id); + let label = text(&s, id); + let at = bounds(&s, id); + let linked = recipe(&s, id); + let measured = s.doc().unwrap().doc.node(NodeId(art_id)).unwrap().clone(); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + if grouped { + run(&mut s, "object.group", json!({})); + } + let steps = s.doc().unwrap().history.undo.len(); + let result = run(&mut s, command, json!({})); + if command == "effect.expandAppearance" { + let mut own = vec![]; + s.doc().unwrap().doc.node(NodeId(id)).unwrap().walk(&mut |c| own.push(json!(c.id.0))); + assert!(result["ids"].as_array().unwrap().iter().all(|i| !own.contains(i)), "{context}: {result}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{context}: one undo step"); + assert_ne!(s.doc().unwrap().doc.node(NodeId(art_id)), Some(&measured), "{context}: the art is replaced"); + assert_eq!(art(&s, id), live, "{context}: its own lines and label"); + assert_eq!(bounds(&s, id), at, "{context}: where it was"); + stays_unlinked(&mut s, id, &label, &context); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "{context}"); + assert_eq!(recipe(&s, id), linked, "{context}: one undo links it again"); + assert_eq!(s.doc().unwrap().doc.node(NodeId(art_id)), Some(&measured), "{context}"); + } +} + +#[test] +fn expand_leaves_a_dimension_selected_with_its_art_as_it_is() { + keeps_its_own_lines_and_label("object.expand"); +} + +#[test] +fn expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is() { + keeps_its_own_lines_and_label("effect.expandAppearance"); +} + +#[test] +fn outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is() { + keeps_its_own_lines_and_label("object.path.outlineStroke"); +} + +/// A selected group whose blur Expand Appearance turns into an image takes the dimension it holds, +/// with the art it measures, into that image. +#[test] +fn a_blurred_group_expanded_takes_its_dimension_into_the_image() { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + let id = dim(&mut s, art_id); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[group]})); + run(&mut s, "effect.apply", json!({"effect":"blur.gaussian"})); + run(&mut s, "effect.expandAppearance", json!({})); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(id)).is_none(), "the dimension is part of the image"); + let mut images = 0; + d.walk(|n| images += usize::from(matches!(n.kind, NodeKind::Image(_)))); + assert_eq!(images, 1); +} + +/// Object › Expand keeps a dimension selected with its art in the export assets that list it and +/// bound to its variables. +#[test] +fn expand_keeps_a_dimension_in_its_asset_and_its_variable_binding() { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setStroke", json!({"ids":[art_id],"color":"#000000"})); + let id = dim(&mut s, art_id); + let asset = run(&mut s, "assets.add", json!({"ids":[id]}))["assets"][0].as_u64().unwrap(); + run(&mut s, "variable.define", json!({"name":"Shown","kind":"visibility"})); + run(&mut s, "variable.bind", json!({"variable":"Shown","ids":[id]})); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + run(&mut s, "object.expand", json!({})); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(id)).is_some_and(|n| n.extras().dimension.is_some()), "still a dimension"); + let listed = d.assets.iter().find(|a| a.id == asset).map(|a| a.nodes.clone()); + assert_eq!(listed, Some(vec![NodeId(id)]), "in its asset"); + assert!(d.variables.bindings.get(&NodeId(id)).is_some_and(|b| b.contains("Shown")), "bound to its variable"); +} + +/// A selected group with a geometry effect of its own bakes that effect into everything it holds +/// when its appearance expands, the dimension's lines and label included: the dimension becomes a +/// plain group of that art, as one selected without its art does. +#[test] +fn a_group_effect_expanded_reaches_the_dimension_it_holds() { + for command in ["effect.expandAppearance", "object.expand"] { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + let id = dim(&mut s, art_id); + let live = art(&s, id); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[group]})); + run(&mut s, "effect.apply", json!({"effect":"distort.puckerBloat"})); + run(&mut s, command, json!({})); + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).unwrap_or_else(|| panic!("{command}: the dimension's group is still there")); + assert!(n.extras().dimension.is_none(), "{command}: a plain group"); + assert_ne!(art(&s, id), live, "{command}: its art is baked with the group's effect"); + } +} + +/// When the dimension selected with its art is all there is to change, the command fails and +/// changes nothing. +#[test] +fn a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing() { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[art_id]})); + run(&mut s, "paint.setStroke", json!({"none": true})); + // A plain path: Expand would make a live rectangle a path. + run(&mut s, "object.expand", json!({})); + let id = dim(&mut s, art_id); + for grouped in [false, true] { + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + if grouped { + run(&mut s, "object.group", json!({})); + } + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!(info["appearance"], json!(false), "grouped: {grouped}: Object › Expand… is not dimmed for the dimension's label"); + assert_eq!(info["stroke"], json!(false), "grouped: {grouped}: {info}"); + assert!(!vectorcraft_engine::cmd::expand::has_appearance(&s), "grouped: {grouped}: the menus read this"); + for (command, p) in [ + ("object.expand", json!({})), + ("object.expand", json!({"object":false,"fill":false})), + ("object.path.outlineStroke", json!({})), + ("effect.expandAppearance", json!({})), + ] { + assert!(s.execute(command, &p).is_err(), "grouped: {grouped}: {command} {p}"); + assert_eq!(s.doc().unwrap().doc.layers, before.layers, "grouped: {grouped}: {command} {p}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "grouped: {grouped}: {command} {p}"); + } + } +} + +/// The dimension `id` is a dimension that measures nothing, still showing `label`, and a move +/// takes it along without redrawing it from other art. +fn stays_unlinked(s: &mut Session, id: u64, label: &str, context: &str) { + let live = art(s, id); + assert!(live.2, "{context}: still a dimension"); + assert!(recipe(s, id).source.is_none(), "{context}: no longer linked"); + assert_eq!(text(s, id), label, "{context}"); + let at = bounds(s, id); + run(s, "select.set", json!({"ids":[id]})); + run(s, "object.move", json!({"dx":30,"dy":0})); + assert_eq!(art(s, id), live, "{context}"); + assert_eq!(text(s, id), label, "{context}"); + let moved = bounds(s, id); + assert!((moved[0] - at[0] - 30.0).abs() < 1e-6 && (moved[1] - at[1]).abs() < 1e-6, "{context}: {at:?} moved to {moved:?}"); + run(s, "edit.undo", json!({})); +} + +/// Expand replacing only the art a selected dimension measures leaves the dimension where it was, +/// still a dimension, without a link to the art that went; undo links it again. #[test] fn a_dimension_keeps_no_link_to_the_art_expand_replaced() { for circle in [false, true] { @@ -468,18 +1359,21 @@ fn a_dimension_keeps_no_link_to_the_art_expand_replaced() { } else { dim(&mut s, art_id) }; - let (nodes, labels, _) = art(&s, id); + let live = art(&s, id); + let label = text(&s, id); run(&mut s, "select.set", json!({"ids":[art_id, id]})); run(&mut s, "object.expand", json!({"object":false,"stroke":false})); - assert_eq!(art(&s, id), (nodes, labels, false), "circle: {circle}"); - run(&mut s, "select.set", json!({"ids":[id]})); - run(&mut s, "object.move", json!({"dx":30,"dy":0})); - assert_eq!(art(&s, id), (nodes, labels, false), "circle: {circle}"); + stays_unlinked(&mut s, id, &label, &format!("circle: {circle}")); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "circle: {circle}"); + assert!(recipe(&s, id).source.is_some(), "circle: {circle}: one undo links it again"); } } -/// Outline Stroke and Expand Appearance replacing the art a selected dimension measures leave the -/// dimension as a plain group, whether or not they change its own art. +/// Outline Stroke and Expand Appearance replacing only the art a selected dimension measures +/// leave the dimension where it was, still a dimension, no longer linked; undo links it again. +/// Here the dimension's lines are guides, which neither command changes, and the selection holds +/// the whole dimension or one of its lines. #[test] fn a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced() { for command in ["object.path.outlineStroke", "effect.expandAppearance"] { @@ -496,19 +1390,44 @@ fn a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced() { }; run(&mut s, "select.set", json!({"ids":lines})); run(&mut s, "view.guides.make", json!({})); + let live = art(&s, id); + let label = text(&s, id); let picked = if whole { id } else { lines[0] }; run(&mut s, "select.set", json!({"ids":[art_id, picked]})); run(&mut s, command, json!({})); assert!(s.doc().unwrap().doc.node(NodeId(id)).is_some(), "{command} removed the dimension, whole: {whole}"); - let plain = art(&s, id); - assert!(!plain.2, "{command}: no recipe left, whole: {whole}"); - run(&mut s, "select.set", json!({"ids":[id]})); - run(&mut s, "object.move", json!({"dx":30,"dy":0})); - assert_eq!(art(&s, id), plain, "{command}, whole: {whole}"); + stays_unlinked(&mut s, id, &label, &format!("{command}, whole: {whole}")); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "{command}, whole: {whole}"); + assert!(recipe(&s, id).source.is_some(), "{command}, whole: {whole}: one undo links it again"); } } } +/// Object › Expand that outlines only the stroke of the art a selected dimension measures leaves +/// the dimension a dimension, no longer linked, as Outline Stroke does. +#[test] +fn a_dimension_outlasts_the_stroke_expand_outlined() { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setStroke", json!({"ids":[art_id],"color":"#000000"})); + let id = dim(&mut s, art_id); + let lines: Vec = { + let children = s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap(); + children.iter().filter(|c| matches!(c.kind, NodeKind::Path { .. })).map(|c| c.id.0).collect() + }; + run(&mut s, "select.set", json!({"ids":lines})); + run(&mut s, "view.guides.make", json!({})); + let live = art(&s, id); + let label = text(&s, id); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + run(&mut s, "object.expand", json!({"object":false,"fill":false})); + stays_unlinked(&mut s, id, &label, "object.expand stroke"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live); + assert!(recipe(&s, id).source.is_some(), "one undo links it again"); +} + /// A part of a dimension expanded on its own ends the link too, so the move does not undo it. #[test] fn expanding_a_part_of_a_dimension_ends_its_link() { @@ -542,10 +1461,11 @@ fn a_dimension_in_an_expanded_symbol_instance_stays_plain_art() { stays_plain_art(&mut s, root); } -/// Create Outlines on a dimension, or on its label alone, ends the link in the same undo step. +/// Create Outlines on a dimension, also one selected with the art it measures, or on its label +/// alone, ends the link in the same undo step. #[test] fn outlining_a_dimension_or_its_label_ends_its_link() { - for label_alone in [false, true] { + for target in ["dimension", "label", "with its art"] { let mut s = session(); let line = edge(&mut s); let id = dim(&mut s, line); @@ -554,8 +1474,12 @@ fn outlining_a_dimension_or_its_label_ends_its_link() { let children = s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap(); children.iter().find(|c| matches!(c.kind, NodeKind::Text(_))).unwrap().id }; - let target = if label_alone { label.0 } else { id }; - run(&mut s, "select.set", json!({"ids":[target]})); + let ids = match target { + "label" => vec![label.0], + "with its art" => vec![line, id], + _ => vec![id], + }; + run(&mut s, "select.set", json!({"ids":ids})); run(&mut s, "type.createOutlines", json!({})); stays_plain_art(&mut s, id); run(&mut s, "edit.undo", json!({})); @@ -668,7 +1592,9 @@ fn dimension_linked_angle_and_circle_update_and_reject_non_circles() { run(&mut s, "object.scale", json!({"sx":200,"sy":200})); assert_eq!(text(&s, id), "4 in"); run(&mut s, "object.scale", json!({"sx":200,"sy":100})); - assert!(s.doc().unwrap().doc.node(NodeId(id)).is_none()); + // An ellipse has no single radius: the dimension stays where it was, no longer linked. + assert_eq!(text(&s, id), "4 in"); + assert!(recipe(&s, id).source.is_none()); assert!(s.execute("dimension.create", &json!({"mode":"radius","source":{"kind":"circle","node":circle}})).is_err()); } diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 878ec6bf59..2c5fc1c307 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -462,3 +462,43 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() { safe_mode::set_active(Some(safe_mode::Source::Flag)); s.execute("effect.expandAppearance", &json!({})).unwrap(); } + +/// In Safe Mode, a plug-in effect on a dimension selected with the art it measures does not stop +/// Expand Appearance: the dimension is left as it is, its effect included, and the art expands. +#[test] +fn expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.dim", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 72, "height": 72})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [art], "color": "#000000"})).unwrap(); + s.execute("appearance.addStroke", &json!({})).unwrap(); + let source = json!({"kind": "segment", "edge": {"node": art, "subpath": 0, "segment": 0}}); + let dim = s.execute("dimension.create", &json!({"source": source})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [dim]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.dim"})).unwrap(); + s.execute("select.set", &json!({"ids": [art, dim]})).unwrap(); + let node = |s: &mut Session, id: &Value| { + let inspect = s.execute("document.inspect", &json!({})).unwrap(); + let mut found = Value::Null; + let mut stack = vec![inspect["layers"].clone()]; + while let Some(v) = stack.pop() { + match v { + Value::Array(a) => stack.extend(a), + Value::Object(o) if o.get("id") == Some(id) => found = Value::Object(o), + Value::Object(o) => stack.extend(o.into_iter().map(|(_, v)| v)), + _ => {} + } + } + found + }; + let kept = node(&mut s, &dim); + let measured = node(&mut s, &art); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + safe_mode::set_active(None); + assert_ne!(node(&mut s, &art), measured, "the art expands"); + assert_eq!(node(&mut s, &dim), kept, "the dimension and its effect stay as they are"); +} diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 28f67f2152..8efa0637ad 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -525,6 +525,51 @@ fn many_objects_of_one_name_are_numbered_in_turn() { assert!(text.contains("(Dot_00000000000000019999_)")); } +/// A document with one top-level layer for each of the 27 layer colour presets, named after its +/// position. +fn every_layer_preset() -> Document { + let mut doc = Document::new(100.0, 100.0); + doc.layers.clear(); + for i in 0..vectorcraft_doc::LAYER_COLORS.len() { + let id = doc.alloc_id(); + doc.layers.push(Arc::new(Node::layer(id, &format!("P{i}"), LayerColor::Preset(u8::try_from(i).unwrap())))); + } + doc +} + +/// #6502: Yellow, Magenta and Cyan (presets 4, 5 and 6) are written as the file's indexes 6, 4 +/// and 5, with their own RGB beside them; every other preset keeps its position. +#[test] +fn layer_presets_are_written_with_the_files_colour_index() { + let text = program(&every_layer_preset()); + for (i, (_, [r, g, b])) in vectorcraft_doc::LAYER_COLORS.iter().enumerate() { + let index = match i { + 4 => 6, + 5 => 4, + 6 => 5, + i => i, + }; + let want = format!(" {index} {r} {g} {b} 0 50 0 Lb\n(P{i}) Ln\n"); + assert!(text.contains(&want), "missing {want:?}"); + } +} + +/// #6502: every preset comes back as itself after a save and an open. +#[test] +fn layer_presets_survive_a_round_trip() { + let doc = read_back(&every_layer_preset()); + let colors: Vec = doc + .layers + .iter() + .map(|l| match l.kind { + NodeKind::Layer { color, .. } => color, + _ => panic!("{:?}", l.kind), + }) + .collect(); + let want: Vec = (0..27u8).map(LayerColor::Preset).collect(); + assert_eq!(colors, want); +} + #[test] fn layers_have_fourteen_operands() { let text = program(&sample()); @@ -3449,6 +3494,9 @@ fn typed() -> Document { v_scale: 90.0, stroke: solid(Color::rgb(0.0, 0.5, 0.0)), stroke_width: 0.5, + stroke_cap: vectorcraft_doc::LineCap::Square, + stroke_join: vectorcraft_doc::LineJoin::Bevel, + stroke_miter_limit: 2.5, all_caps: true, ..regular.clone() }; @@ -3565,7 +3613,7 @@ fn type_lines(doc: &Document) -> Vec { for r in &t.runs { let s = &r.style; out.push(format!( - " run {:?} {} {} {} {:?} {} {} {} {} fill {} stroke {} {} caps={} small={:?} tcy={} roman={}", + " run {:?} {} {} {} {:?} {} {} {} {} fill {} stroke {} {} {:?} {:?} {} caps={} small={:?} tcy={} roman={}", r.text, s.font_family, s.font_style, @@ -3578,6 +3626,9 @@ fn type_lines(doc: &Document) -> Vec { paint(&s.fill), paint(&s.stroke), r3(s.stroke_width), + s.stroke_cap, + s.stroke_join, + r3(s.stroke_miter_limit), s.all_caps, s.small_caps.map(r3), s.tate_chu_yoko, @@ -3718,6 +3769,22 @@ fn type_comes_back_as_type() { assert_eq!(back.text_threads.len(), 1, "the thread comes back"); } +/// A run without a stroke whose stroke's cap, join and miter limit aren't the defaults loses +/// nothing that draws: the save reports no attributes left out. +#[test] +fn an_unstroked_run_with_a_stroke_style_loses_nothing() { + use vectorcraft_doc::{CharStyle, LineCap, LineJoin, TextObject}; + for miter in [3.0, f64::NAN] { + let st = CharStyle { stroke_cap: LineCap::Round, stroke_join: LineJoin::Bevel, stroke_miter_limit: miter, ..style(14.0, Color::BLACK) }; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let n = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Plain", st)); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{miter}: {:?}", out.warnings); + } +} + #[test] fn type_is_written_again_as_the_same_bytes() { let doc = typed(); diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 0c3587e586..c598e2cd9a 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use vectorcraft_color::cms::Cms; use vectorcraft_color::swatch::{REGISTRATION, Swatch}; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer}; +use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer}; use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath}; use vectorcraft_pathops::BoolOp; @@ -449,14 +449,7 @@ impl<'a> Writer<'a> { /// (`Xy`, `0 0 Xd`, `7 () XW`) when it has any, `LB`, `%AI5_EndLayer--`. fn write_layer(&mut self, n: &Node, after: &[Arc]) { let NodeKind::Layer { color, template, printable, children, clip, preview, dim_images } = &n.kind else { return }; - let [r, g, b] = match color { - LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(*i)).map_or([79, 128, 255], |c| c.1), - LayerColor::Custom(rgb) => *rgb, - }; - let index = match color { - LayerColor::Preset(i) if usize::from(*i) < LAYER_COLORS.len() => i64::from(*i), - _ => -1, - }; + let (index, [r, g, b]) = ai_ops::layer_color(*color); if *template { self.warn(TEMPLATES); } diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 1e02941c31..5ebd73de3a 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -21,15 +21,15 @@ use std::fmt::Write; use kurbo::{ParamCurveArclen, PathSeg}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{ - AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, Mojikumi, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, - PathEffect, TextKind, TextObject, VerticalAlign, + AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, LineCap, LineJoin, Mojikumi, Node, NodeId, NodeKind, ParaDirection, + ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign, }; use vectorcraft_geom::{Affine, PathData, Point}; use crate::ps; /// What the text document holds of type, and what it leaves out. -pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and stroke weight, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; +pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; /// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it. const STREAM_VERSION: u32 = 14; @@ -347,6 +347,9 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { fill: unlinked(&s.fill), stroke: unlinked(&s.stroke), stroke_width: if stroked { s.stroke_width } else { CharStyle::default().stroke_width }, + stroke_cap: if stroked { s.stroke_cap } else { CharStyle::default().stroke_cap }, + stroke_join: if stroked { s.stroke_join } else { CharStyle::default().stroke_join }, + stroke_miter_limit: if stroked { miter_limit(s.stroke_miter_limit) } else { CharStyle::default().stroke_miter_limit }, all_caps: s.all_caps, small_caps: s.small_caps.filter(|v| *v == default_small_caps), tate_chu_yoko: s.tate_chu_yoko, @@ -357,7 +360,19 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { }; let run_lost = |s: &CharStyle| { let stroked = !s.stroke.is_none(); - let s = CharStyle { stroke_width: if stroked { s.stroke_width } else { CharStyle::default().stroke_width }, ..s.clone() }; + // Without a stroke, its weight, cap, join and miter limit draw nothing: nothing is lost. + let unstroked = CharStyle::default(); + let s = if stroked { + s.clone() + } else { + CharStyle { + stroke_width: unstroked.stroke_width, + stroke_cap: unstroked.stroke_cap, + stroke_join: unstroked.stroke_join, + stroke_miter_limit: unstroked.stroke_miter_limit, + ..s.clone() + } + }; // A Lab color is written as RGB. let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }); s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !font_kept(&s) @@ -463,6 +478,32 @@ fn font_name(st: &CharStyle) -> FontRecord { } } +/// The text document's number for a stroke's cap (key 61), as PostScript numbers them: 0 butt, 1 +/// round, 2 projecting. +fn cap_code(cap: LineCap) -> i64 { + match cap { + LineCap::Butt => 0, + LineCap::Round => 1, + LineCap::Square => 2, + } +} + +/// The text document's number for a stroke's join (key 62), as PostScript numbers them: 0 miter, 1 +/// round, 2 bevel. +fn join_code(join: LineJoin) -> i64 { + match join { + LineJoin::Miter => 0, + LineJoin::Round => 1, + LineJoin::Bevel => 2, + } +} + +/// A stroke's miter limit (key 64) as the reader takes it back: at least 1 and at most 500, 10 when +/// it isn't a number at least 1. +fn miter_limit(v: f64) -> f64 { + if v.is_finite() && v >= 1.0 { v.min(500.0) } else { 10.0 } +} + /// `v` as the 16.16 fixed-point number a design vector holds (`wght` 700 is 45875200). fn fixed(v: f32) -> i64 { if v.is_finite() { (f64::from(v) * 65536.0).round() as i64 } else { 0 } @@ -621,7 +662,12 @@ impl TextDoc { } d.extend([(56, V::Bool(fill.is_some())), (57, V::Bool(stroke.is_some()))]); if stroke.is_some() { - d.push((63, V::Small(st.stroke_width / scale))); + d.extend([ + (61, V::Int(cap_code(st.stroke_cap))), + (62, V::Int(join_code(st.stroke_join))), + (63, V::Small(st.stroke_width / scale)), + (64, real(miter_limit(st.stroke_miter_limit))), + ]); } dict(d) } diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs index a22c94de53..7707f4bc45 100644 --- a/crates/eps/src/ai_ops.rs +++ b/crates/eps/src/ai_ops.rs @@ -6,7 +6,7 @@ use std::fmt::Write; use vectorcraft_color::{Color, Gradient}; -use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer}; +use vectorcraft_doc::{LAYER_COLORS, LayerColor, LineCap, LineJoin, StrokeLayer}; use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, SubPath}; use crate::ps; @@ -62,6 +62,43 @@ pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, editing: bool) } } +/// The colour index an `.ai` layer's `Lb` gives preset `preset` (its position in +/// [`LAYER_COLORS`]). The file numbers Magenta, Cyan and Yellow 4, 5 and 6, where +/// [`LAYER_COLORS`] has Yellow, Magenta and Cyan; every other preset has its own position (#6502, +/// from the index and RGB pairs of the `Lb` records in files users sent). A reader takes the index +/// and ignores the RGB beside it, so the index decides the colour. +pub(crate) fn ai_layer_index(preset: u8) -> u8 { + match preset { + 4 => 6, + 5 => 4, + 6 => 5, + i => i, + } +} + +/// The preset (position in [`LAYER_COLORS`]) of the colour index `index` in an `.ai` layer's +/// `Lb`: the inverse of [`ai_layer_index`]. +pub(crate) fn preset_of_ai_layer_index(index: u8) -> u8 { + match index { + 6 => 4, + 4 => 5, + 5 => 6, + i => i, + } +} + +/// The colour index and RGB an `.ai` layer's `Lb` writes for `color`: a preset's index +/// ([`ai_layer_index`]) with its RGB, or `-1` with a custom colour's RGB. +pub(crate) fn layer_color(color: LayerColor) -> (i64, [u8; 3]) { + match color { + LayerColor::Preset(i) => match LAYER_COLORS.get(usize::from(i)) { + Some((_, rgb)) => (i64::from(ai_layer_index(i)), *rgb), + None => (-1, [79, 128, 255]), + }, + LayerColor::Custom(rgb) => (-1, rgb), + } +} + pub(crate) fn unit(v: f32) -> f32 { if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } } diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index c0da27f2a9..25701650c9 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -20,8 +20,9 @@ //! `(AIDeformArtKey)`) and the kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object). Then the //! distorted art on plain lines, and the plugin's `XP`. While the contents are edited, the group //! holds the contents and the dictionary the mesh. A top object's outline is the edge of its -//! one-patch mesh. An envelope whose parts don't read, or that doesn't come out as drawn, keeps its -//! drawn art. +//! one-patch mesh. A warp's mesh is a grid of its shape: a warp of type whose own warp doesn't come +//! out as drawn opens as a mesh envelope on that grid where that does. An envelope whose parts don't +//! read, or that doesn't come out as drawn, keeps its drawn art. use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; @@ -130,6 +131,58 @@ fn saved_margin(o: &Obj, content: &[Arc]) -> Option<[f32; 4]> { envelope_stroke_margin(stroked, plain) } +/// The box of `content` an envelope of type with Distort Appearance maps from in a file: type by +/// its glyph outlines grown by as far as its strokes paint along a side (half the weight of a +/// centred stroke), without what miter joins add at corners, as are groups by their own strokes; +/// other objects by their bounds with strokes. `None` when nothing in it has bounds. +fn half_stroked_box(content: &[Arc]) -> Option { + /// How far the visible strokes of `appearance` paint along the sides of closed outlines. + fn along(appearance: &Appearance) -> f64 { + appearance.painted_strokes().map(|s| s.side_reach(true)).fold(0.0, f64::max) + } + /// `r` grown by `by` on each side, where that is a distance. + fn grown(r: Rect, by: f64) -> Rect { + if by.is_finite() && by > 0.0 { r.inflate(by, by) } else { r } + } + fn walk(n: &Arc, acc: Option) -> Option { + let one = std::slice::from_ref(n); + match &n.kind { + NodeKind::Text(t) => { + let Some((_, ink)) = envelope_content_boxes(one, Affine::IDENTITY) else { return acc }; + // The characters' own strokes as the type's bounds with strokes measure them (they + // have no miter allowance there), and the strokes of its appearance along a side. + vectorcraft_geom::union_opt(acc, Some(grown(ink, t.char_stroke_outset().max(along(&n.appearance))))) + } + NodeKind::Group { children, clip: false } => { + let members = children.iter().fold(None, |acc, c| walk(c, acc)); + vectorcraft_geom::union_opt(acc, members.map(|b| grown(b, along(&n.appearance)))) + } + _ => vectorcraft_geom::union_opt(acc, envelope_content_boxes(one, Affine::IDENTITY).map(|(stroked, _)| stroked)), + } + } + content.iter().fold(None, |acc, c| walk(c, acc)) +} + +/// Envelope `kind` mapping from its contents' glyphs grown by as far as their strokes paint along a +/// side ([`half_stroked_box`]), for an envelope with Distort Appearance whose contents have strokes it +/// doesn't map from already; `None` otherwise. +fn with_strokes(kind: &NodeKind) -> Option { + let NodeKind::Envelope { content, options, .. } = kind else { return None }; + if !options.distort_appearance { + return None; + } + let (_, plain) = envelope_content_boxes(content, Affine::IDENTITY)?; + let margin = envelope_stroke_margin(half_stroked_box(content)?, plain)?; + if margin == options.bounds_margin || margin.iter().any(|m| *m < 0.0) || margin.iter().all(|m| *m == 0.0) { + return None; + } + let mut kind = kind.clone(); + if let NodeKind::Envelope { options, .. } = &mut kind { + options.bounds_margin = margin; + } + Some(kind) +} + /// A warp: its style, bend, distortions and orientation. fn warp(o: &Obj) -> Option { let style = whole(o, "DeformStyle")??; @@ -188,9 +241,38 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { let mut pts: Vec = m.points.iter().map(|q| (q.p, q.handles)).collect(); let at = |pts: &[GridPoint], cols: u32, r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).map_or(Point::ZERO, |q| q.0); let remap = |h: [Vec2; 4], slots: [usize; 4]| slots.map(|s| h.get(s).copied().unwrap_or(Vec2::ZERO)); - // Columns that run down the page: the grid goes the other way round. - let along = at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0); - if along.y.abs() > along.x.abs() { + // How far the grid reaches: a run much shorter than that is rounding, not a direction. + let reach = { + let first = pts.first().map_or(Point::ZERO, |q| q.0); + let bounds = pts.iter().fold(Rect::from_points(first, first), |b, q| b.union_pt(q.0)); + bounds.width().hypot(bounds.height()) * 1e-6 + }; + // How the grid runs along its rows (every row end to end, added up) and down its columns (every + // column): read from all of them, a grid bent far round (its end columns leaning more than + // halfway over) still reads the way it runs. Each sum comes with how long its parts are: where + // they nearly cancel out, as in a ring, what is left is rounding, not a direction, and the grid + // reads by its first row or column instead. + let runs = |pts: &[GridPoint], rows: u32, cols: u32| { + let (mut along, mut down, mut along_len, mut down_len) = (Vec2::ZERO, Vec2::ZERO, 0.0, 0.0); + for r in 0..=rows { + let v = at(pts, cols, r, cols) - at(pts, cols, r, 0); + (along, along_len) = (along + v, along_len + v.hypot()); + } + for c in 0..=cols { + let v = at(pts, cols, rows, c) - at(pts, cols, 0, c); + (down, down_len) = (down + v, down_len + v.hypot()); + } + let clear = |v: Vec2, len: f64| (v.hypot() >= len * 0.01 && v.hypot() > reach).then_some(v); + let first_row = at(pts, cols, 0, cols) - at(pts, cols, 0, 0); + let first_col = at(pts, cols, rows, 0) - at(pts, cols, 0, 0); + (clear(along, along_len).unwrap_or(first_row), clear(down, down_len).unwrap_or(first_col)) + }; + // How much of a run is across the page. + let level = |v: Vec2| if v.hypot() > 0.0 { v.x.abs() / v.hypot() } else { 0.0 }; + // Columns that run across the page more than rows do: the grid goes the other way round. Nearly + // as much (a grid turned an eighth round) keeps the file's way round. + let (along, down) = runs(&pts, rows, cols); + if level(down) > level(along) + 1e-3 { let mut t = Vec::with_capacity(len); for r in 0..=cols { for c in 0..=rows { @@ -204,7 +286,7 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { (rows, cols) = (cols, rows); pts = t; } - if (at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0)).x < 0.0 { + if runs(&pts, rows, cols).0.x < 0.0 { for row in pts.chunks_mut(cols as usize + 1) { row.reverse(); for (_, h) in row.iter_mut() { @@ -212,7 +294,7 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { } } } - if (at(&pts, cols, rows, 0) - at(&pts, cols, 0, 0)).y < 0.0 { + if runs(&pts, rows, cols).1.y < 0.0 { let mut flipped: Vec = pts.chunks(cols as usize + 1).rev().flatten().copied().collect(); for (_, h) in &mut flipped { h.swap(H_DOWN, H_UP); @@ -269,6 +351,23 @@ fn unwrapped(mut nodes: Vec) -> Vec> { /// The live envelope of dictionary `o`, the group on `%_` lines before it (`before`) and the art /// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. pub(super) fn live(o: &Obj, before: Option, inner: Vec) -> Option { + envelope_as(o, before, inner, false) +} + +/// Is the envelope of dictionary `o` a warp? +fn is_warp(o: &Obj) -> bool { + whole(o, "AIDeformStyle") == Some(Some(1)) +} + +/// [`live`] for a warp, as a mesh envelope on the grid its editing data saves (the mesh that shapes +/// it), its points and handles as saved: it draws as that grid does, without the warp's style, bend +/// and distortions. `None` for an envelope that isn't a warp, or whose grid doesn't read. +fn live_on_saved_grid(o: &Obj, before: Option, inner: Vec) -> Option { + envelope_as(o, before, inner, true) +} + +/// [`live`], or with `on_grid` [`live_on_saved_grid`]. +fn envelope_as(o: &Obj, before: Option, inner: Vec, on_grid: bool) -> Option { let editing = switch(o, "AIDeformEditModeKey")?; let (mut options, fidelity) = options(o)?; let before = before?; @@ -290,14 +389,14 @@ pub(super) fn live(o: &Obj, before: Option, inner: Vec) -> Option warp(o)?, - 2 => { + let kind = match (whole(o, "AIDeformStyle")??, on_grid) { + (1, false) => warp(o)?, + (1, true) | (2, false) => { let (rows, cols, pts) = upright(shape?)?; let (points, handles) = pts.into_iter().unzip(); EnvelopeKind::Mesh { rows, cols, points, handles } } - 3 => { + (3, false) => { let (rows, cols, pts) = upright(shape?)?; // The outline runs clockwise from the top left corner, one segment per grid edge. let corners = [0, cols, cols.checked_add(rows)?, cols.checked_mul(2)?.checked_add(rows)?]; @@ -448,9 +547,14 @@ impl WarpedType { /// Make each envelope of type live where it draws as its drawn art, its contents' text slots /// holding their type: `type_of` gives, for a slot's id, the hidden text object it became in /// `doc` and the type the contents take in its place (the slot's visibility and lock are the - /// type's). The live envelope takes its drawn art's place and the hidden type goes. Each check - /// uses one of the import's checks and, for an envelope that shows, adds to what the page check - /// allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't + /// type's). The live envelope takes its drawn art's place and the hidden type goes. A warp that + /// doesn't draw as its drawn art is checked again as a mesh envelope on the grid the file saves + /// for it ([`live_on_saved_grid`]), which opens in its place where it does: its type stays + /// editable in that shape, and the warp's style and bend are lost. With Distort Appearance, each + /// is also checked mapping from its type's glyphs grown by half their strokes' weight + /// ([`with_strokes`]). Each + /// check uses one of the import's checks and, for an envelope that shows, adds to what the page + /// check allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't /// available, the drawn art and the hidden type stay. pub(crate) fn settle_envelopes(&mut self, doc: &mut Document, type_of: impl Fn(&Document, NodeId) -> Option<(NodeId, Node)>) -> TypedSettled { let mut settled = TypedSettled::default(); @@ -459,8 +563,11 @@ impl WarpedType { } let mut shown = BTreeSet::new(); doc.layers.iter().for_each(|l| collect_shown(l, &mut shown)); - for envelope in std::mem::take(&mut self.envelopes) { - match self.typed_live(doc, envelope, &type_of, &shown) { + let envelopes = std::mem::take(&mut self.envelopes); + let mut waiting = envelopes.len(); + for envelope in envelopes { + waiting -= 1; + match self.typed_live(doc, envelope, &type_of, &shown, waiting) { Ok(put_back) => { settled.live += 1; settled.put_back.push(put_back); @@ -471,14 +578,16 @@ impl WarpedType { settled } - /// [`Self::settle_envelopes`] for `envelope`, the shown objects of `doc` being `shown`: the live - /// envelope's id and what takes its place again, or why its drawn art stays. + /// [`Self::settle_envelopes`] for `envelope`, the shown objects of `doc` being `shown` and + /// `waiting` envelopes of type still to come: the live envelope's id and what takes its place + /// again, or why its drawn art stays. fn typed_live( &mut self, doc: &mut Document, envelope: TypedEnvelope, type_of: &impl Fn(&Document, NodeId) -> Option<(NodeId, Node)>, shown: &BTreeSet, + waiting: usize, ) -> Result<(NodeId, Vec), TypeKept> { let TypedEnvelope { obj, mut before, mut inner, drawn } = envelope; let art = doc.node(drawn).cloned().ok_or(TypeKept::Read)?; @@ -503,22 +612,47 @@ impl WarpedType { for n in before.iter_mut().chain(inner.iter_mut()) { put_type(n, &texts); } - let kind = live(&obj, before, inner).ok_or(TypeKept::Read)?; - if self.checks == 0 { - return Err(TypeKept::Budget); + // A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the + // grid the file saves for it: then it opens as a mesh envelope on that grid. + let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone()) } else { None }; + // With Distort Appearance, a file's envelope may map its type from its glyphs grown by half + // their strokes' weight or from the glyphs alone, and for type the size the file saves for + // that box is often out of date (not the size of the type there now): each is checked. + let kinds: Vec = live(&obj, before, inner) + .into_iter() + .chain(on_grid) + .flat_map(|k| { + let stroked = with_strokes(&k); + std::iter::once(k).chain(stroked) + }) + .collect(); + if kinds.is_empty() { + return Err(TypeKept::Read); } - self.checks -= 1; - let mut envelope = art.clone(); - (envelope.id, envelope.kind) = (doc.alloc_id(), kind); - let layer = doc.alloc_id(); - let shared = Shared { patterns: &doc.patterns, images: &doc.images }; - let (mut live_one, mut plain) = (envelope.clone(), art.clone()); - (live_one.visible, live_one.opacity) = (true, 1.0); + let (id, layer) = (doc.alloc_id(), doc.alloc_id()); + let mut plain = art.clone(); (plain.visible, plain.opacity) = (true, 1.0); let page = self.page.filter(|_| shown.contains(&drawn)); - if !drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) { - return Err(TypeKept::Differs); + let mut alike = None; + for (i, kind) in kinds.into_iter().enumerate() { + // A second try is only made while more checks are left than there are envelopes of + // type and warped text objects still to come (some of which may need none): one + // envelope's tries don't use up the checks of the others. + if self.checks == 0 || (i > 0 && self.checks <= waiting + self.looks.len()) { + return Err(TypeKept::Budget); + } + self.checks -= 1; + let mut envelope = art.clone(); + (envelope.id, envelope.kind) = (id, kind); + let shared = Shared { patterns: &doc.patterns, images: &doc.images }; + let mut live_one = envelope.clone(); + (live_one.visible, live_one.opacity) = (true, 1.0); + if drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) { + alike = Some(envelope); + break; + } } + let envelope = alike.ok_or(TypeKept::Differs)?; if doc.node(drawn).is_none() { return Err(TypeKept::Read); } @@ -672,3 +806,91 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, s *spent = Spent { any, solid }; true } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{AppearanceItem, CharStyle, LineJoin, StrokeLayer, TextObject}; + + /// An envelope of `content` with Distort Appearance, on a flat one-patch mesh. + fn envelope_of(content: Vec>) -> NodeKind { + let points = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(0.0, 50.0), Point::new(100.0, 50.0)]; + NodeKind::Envelope { + content, + kind: Box::new(EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }), + fidelity: 50.0, + editing: false, + options: EnvelopeOptions::NEW, + frame: Box::default(), + } + } + + /// The bounds margin of the stroked candidate for an envelope of `content`. + fn stroked_margin(content: Vec>) -> Option<[f32; 4]> { + match with_strokes(&envelope_of(content)) { + Some(NodeKind::Envelope { options, .. }) => Some(options.bounds_margin), + _ => None, + } + } + + /// "AVA" at 40 points, at (10, 60). + fn type_node(id: u64, style: CharStyle) -> Node { + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "AVA", CharStyle { size: 40.0, ..style })))) + } + + /// A 4 point stroke with miter joins at a limit of 4. + fn mitred() -> StrokeLayer { + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + (stroke.join, stroke.miter_limit) = (LineJoin::Miter, 4.0); + stroke + } + + /// Type with Distort Appearance and a stroke from its appearance is tried mapped from its glyphs + /// grown by half the stroke's weight, not from its bounds with strokes, which reach as far as a + /// miter join may at a corner. + #[test] + fn stroked_type_is_tried_mapped_from_its_glyphs_grown_by_half_its_stroke() { + let mut text = type_node(1, CharStyle::default()); + let mut appearance = (*text.appearance).clone(); + appearance.items.push(AppearanceItem::Stroke(mitred())); + text.appearance = appearance.into(); + let content = vec![Arc::new(text)]; + let (with, glyphs) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap(); + let half = glyphs.inflate(2.0, 2.0); + assert!(with.width() > half.width() + 1.0, "{with:?} {half:?}"); + assert_eq!(stroked_margin(content), envelope_stroke_margin(half, glyphs)); + } + + /// Type stroked by its characters alone is tried mapped from its bounds with strokes, as before, + /// turned and stretched as well as upright. + #[test] + fn type_with_a_character_stroke_is_tried_mapped_from_its_bounds_with_strokes() { + let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, ..CharStyle::default() }; + for xf in [ + Affine::IDENTITY, + Affine::rotate(std::f64::consts::FRAC_PI_4), + Affine::scale_non_uniform(std::f64::consts::SQRT_2, std::f64::consts::FRAC_1_SQRT_2), + ] { + let mut text = type_node(1, style.clone()); + if let NodeKind::Text(t) = &mut text.kind { + t.xf = xf * t.xf; + } + let content = vec![Arc::new(text)]; + let (with, glyphs) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap(); + assert_eq!(stroked_margin(content), envelope_stroke_margin(with, glyphs), "{xf:?}"); + } + } + + /// A stroke on a group's own appearance round type grows the box by half its weight too. + #[test] + fn a_stroke_on_a_group_of_type_grows_the_box_by_half_its_weight() { + let mut group = Node::new(NodeId(2), NodeKind::Group { children: vec![Arc::new(type_node(1, CharStyle::default()))], clip: false }); + let mut appearance = (*group.appearance).clone(); + appearance.items.push(AppearanceItem::Stroke(mitred())); + group.appearance = appearance.into(); + let content = vec![Arc::new(group)]; + let (_, glyphs) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap(); + assert_eq!(stroked_margin(content), envelope_stroke_margin(glyphs.inflate(2.0, 2.0), glyphs)); + } +} diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 63e9f3df77..eb3d73c691 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -648,6 +648,10 @@ impl<'a> Reader<'a> { if self.author.is_none() { self.author = outer.author; } + // Ruler units the editing data doesn't give: the file still records them (#5820). + if self.ruler_units.is_none() { + self.ruler_units = outer.ruler_units; + } self.names.absorb(outer.names); for n in outer.custom_colors { if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) { @@ -1209,6 +1213,7 @@ impl<'a> Reader<'a> { show_video_safe_areas: b.safe_areas, video_ruler_pixel_aspect_ratio: b.par, color: None, + guide_label: None, }) .collect(); if doc.artboards.is_empty() { @@ -1223,6 +1228,7 @@ impl<'a> Reader<'a> { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }]; } doc.opened_artboard = active.and_then(|i| doc.artboards.get(i)).map(|a| a.id); @@ -1253,6 +1259,7 @@ impl<'a> Reader<'a> { } if let Some(u) = self.ruler_units.and_then(ruler_unit) { doc.units = u; + doc.units_from_file = true; } // The file's own swatches in place of the defaults, in its order and colour groups. let own_palette = match self.palette_swatches(&doc.patterns) { diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 6c84eff236..c0d9852d88 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -471,8 +471,9 @@ impl<'a> Reader<'a> { a.dim = flag(4, false).then_some(dim_pct.round() as u8); let index = n.get(at).copied().unwrap_or(0.0); let rgb = |i: usize| n.get(at + i).map_or(0, |v| v.clamp(0.0, 255.0) as u8); + // The file numbers some presets differently from `LAYER_COLORS` (#6502). a.color = Some(if (0.0..vectorcraft_doc::LAYER_COLORS.len() as f64).contains(&index) && index.fract() == 0.0 { - LayerColor::Preset(index as u8) + LayerColor::Preset(crate::ai_ops::preset_of_ai_layer_index(index as u8)) } else { LayerColor::Custom([rgb(1), rgb(2), rgb(3)]) }); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 2b127e275b..2c219d2b07 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -7501,6 +7501,101 @@ fn a_mesh_envelope_opens_live_with_its_points_and_handles() { assert!(r.warnings.is_empty(), "{:?}", r.warnings); } +/// A mesh envelope bent far round, its end columns leaning more than halfway over (a warp's grid +/// bent into an arc), opens live the way it runs: its columns along the arc, as in the file. +#[test] +fn a_mesh_envelope_bent_far_round_opens_the_way_it_runs() { + use vectorcraft_doc::live::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP}; + // 3 columns along an arc round (100, 0) from 160 to 20 degrees, rows at radius 60 and 90: the + // end columns lean 70 degrees over. + let at = |(i, j): (usize, usize)| { + let (a, r) = ((160.0 - i as f64 * 140.0 / 3.0).to_radians(), 60.0 + j as f64 * 30.0); + (100.0 + r * a.cos(), r * a.sin()) + }; + let handle = |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + // Written with its first index across the arc and its second along it, so that the grid reads + // turned round and has to be turned upright. + let shape = mesh_text(1, 3, &|(i, j)| at((j, i)), &|p, q| handle((p.1, p.0), (q.1, q.0)), None); + // Row r of the envelope is row 1 - r of the file (art space has y up). + let doc_pt = |(x, y): (f64, f64)| Point::new(x, 100.0 - y); + let (mut points, mut handles) = (vec![], vec![]); + for r in 0..=1usize { + for c in 0..=3usize { + let g = (c, 1 - r); + let p = doc_pt(at(g)); + points.push(p); + let towards = |q: Option<(usize, usize)>| q.filter(|q| q.0 <= 3 && q.1 <= 1).map_or(kurbo::Vec2::ZERO, |q| doc_pt(handle(g, q)) - p); + let mut h = [kurbo::Vec2::ZERO; 4]; + h[H_RIGHT] = towards(Some((g.0 + 1, g.1))); + h[H_LEFT] = towards(g.0.checked_sub(1).map(|i| (i, g.1))); + h[H_UP] = towards(Some((g.0, g.1 + 1))); + h[H_DOWN] = towards(g.1.checked_sub(1).map(|j| (g.0, j))); + handles.push(h); + } + } + let want = EnvelopeKind::Mesh { rows: 1, cols: 3, points, handles }; + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let EnvelopeKind::Mesh { rows, cols, points: got, .. } = live_envelope(&a[0]).1 else { panic!("{a:#?}") }; + assert_eq!((*rows, *cols), (1, 3)); + let EnvelopeKind::Mesh { points: want, .. } = &want else { panic!("{want:?}") }; + assert!(got.iter().zip(want).all(|(p, q)| (*p - *q).hypot() < 1e-6), "{got:?}"); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// A mesh envelope bent halfway round, its grid running down an arc from top to bottom so that its +/// end rows cancel out, opens the same way round wherever it sits on the page and whichever way +/// round the file writes it. +#[test] +fn a_mesh_envelope_bent_halfway_round_opens_the_same_way_wherever_it_is() { + use vectorcraft_doc::live::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP}; + for cx in [100.0, 100.1, 37.0, 250.3, 12.7] { + // 4 rows down an arc round (cx, 0) from 90 to 270 degrees, columns at radius 90 and 60. + let at = |(i, j): (usize, usize)| { + let (a, r) = ((90.0 + i as f64 * 45.0_f64).to_radians(), 60.0 + j as f64 * 30.0); + (cx + r * a.cos(), r * a.sin()) + }; + let handle = |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + // Row r of the envelope is the arc's point r from the top, column c the radius 1 - c: the + // outer one is on the left. + let doc_pt = |(x, y): (f64, f64)| Point::new(x, 100.0 - y); + let (mut points, mut handles) = (vec![], vec![]); + for r in 0..=4usize { + for c in 0..=1usize { + let g = (r, 1 - c); + let p = doc_pt(at(g)); + points.push(p); + let towards = |q: Option<(usize, usize)>| q.filter(|q| q.0 <= 4 && q.1 <= 1).map_or(kurbo::Vec2::ZERO, |q| doc_pt(handle(g, q)) - p); + let mut h = [kurbo::Vec2::ZERO; 4]; + h[H_DOWN] = towards(Some((g.0 + 1, g.1))); + h[H_UP] = towards(g.0.checked_sub(1).map(|i| (i, g.1))); + h[H_RIGHT] = towards(g.1.checked_sub(1).map(|j| (g.0, j))); + h[H_LEFT] = towards(Some((g.0, g.1 + 1))); + handles.push(h); + } + } + let want = EnvelopeKind::Mesh { rows: 4, cols: 1, points, handles }; + let along = mesh_text(4, 1, &at, &handle, None); + let across = mesh_text(1, 4, &|(i, j)| at((j, i)), &|p, q| handle((p.1, p.0), (q.1, q.0)), None); + for shape in [along, across] { + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let EnvelopeKind::Mesh { rows, cols, points: got, .. } = live_envelope(&a[0]).1 else { panic!("at {cx}: {a:#?}") }; + assert_eq!((*rows, *cols), (4, 1), "at {cx}"); + let EnvelopeKind::Mesh { points: want, .. } = &want else { panic!("{want:?}") }; + assert!(got.iter().zip(want).all(|(p, q)| (*p - *q).hypot() < 1e-6), "at {cx}: {got:?}"); + } + } +} + /// An envelope made with a top object opens as a live envelope whose top path is the edge of its /// one-patch mesh, an anchor on the edge included; its contents stay the rectangle. #[test] @@ -8370,20 +8465,44 @@ fn layer_with(ops: &str) -> Node { /// the colour index and the last one change nothing. #[test] fn the_template_flag_of_a_layer() { + // Index 4 is the file's Magenta (#6502). let l = layer_with("1 1 0 0 1 0 0 4 255 79 255 1 50 0"); let NodeKind::Layer { template, printable, dim_images, color, .. } = l.kind else { panic!() }; assert!(template && !printable && l.locked); - assert_eq!((dim_images, color), (Some(50), LayerColor::Preset(4))); + assert_eq!((dim_images, color), (Some(50), LayerColor::Preset(5))); + // Index 5 is the file's Cyan (#6502). for ops in ["1 1 1 1 1 0 1 5 1 2 3 1 30 0", "1 1 1 1 1 0 0 5 1 2 3 1 30 1", "1 1 1 1 1 0 1 5 1 2 3 1 30"] { let l = layer_with(ops); let NodeKind::Layer { template, printable, dim_images, color, .. } = l.kind else { panic!() }; assert!(template && printable && !l.locked, "{ops}"); - assert_eq!((dim_images, color), (Some(30), LayerColor::Preset(5)), "{ops}"); + assert_eq!((dim_images, color), (Some(30), LayerColor::Preset(6)), "{ops}"); } let l = layer_with("1 1 1 1 0 0 1 0 79 128 255 0 50 0"); assert!(matches!(l.kind, NodeKind::Layer { template: false, .. })); } +/// #6502: an `.ai` file numbers Magenta, Cyan and Yellow 4, 5 and 6 (the index and RGB pairs of +/// the `Lb` records in files users sent), so they open as those presets; the index decides, not +/// the RGB beside it, and the other presets keep their position. +#[test] +fn layer_colour_indexes_follow_the_file_format() { + let color = |ops: &str| match layer_with(ops).kind { + NodeKind::Layer { color, .. } => color, + _ => panic!(), + }; + let preset = |name: &str| { + let i = vectorcraft_doc::LAYER_COLORS.iter().position(|(n, _)| *n == name).unwrap(); + LayerColor::Preset(u8::try_from(i).unwrap()) + }; + for (index, rgb, name) in + [(3, "79 79 255", "Blue"), (4, "255 79 255", "Magenta"), (5, "79 255 255", "Cyan"), (6, "255 255 79", "Yellow"), (7, "128 128 128", "Gray")] + { + assert_eq!(color(&format!("1 1 1 1 0 0 0 {index} {rgb} 0 50 0")), preset(name), "index {index}"); + } + // The RGB beside an index doesn't change the preset. + assert_eq!(color("1 1 1 1 0 0 0 4 255 255 79 0 50 0"), preset("Magenta")); +} + /// The colour index is one place earlier in eleven and twelve operands, as in ten, and the twelfth /// is the dimming percentage; with nine it is one place earlier still. #[test] diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 2250dea96e..194c0ff1e2 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -26,8 +26,8 @@ use std::collections::BTreeMap; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{ - CharStyle, HyphenationOptions, JustificationOptions, Justify, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TabAlign, - TabStop, TextKind, TextObject, TextRun, + CharStyle, HyphenationOptions, JustificationOptions, Justify, LineCap, LineJoin, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, + PathEffect, TabAlign, TabStop, TextKind, TextObject, TextRun, }; use vectorcraft_geom::{Affine, PathData, Point, Rect}; @@ -462,6 +462,12 @@ struct Style { fill: Option, stroke: Option, stroke_width: f64, + /// Key 61, the stroke's cap: 0 butt, 1 round, 2 projecting (square). + stroke_cap: LineCap, + /// Key 62, the stroke's join: 0 miter, 1 round, 2 bevel. + stroke_join: LineJoin, + /// Key 64, the stroke's miter limit (a multiple of the stroke weight). + stroke_miter_limit: f64, /// Key 12, the case: 1 Small Caps, 2 All Caps. caps: u8, /// Key 35 at 3: Tate-chu-yoko, the characters set across the column as one block. @@ -752,6 +758,21 @@ impl Texts { fill: if on("56") { Some(pick("53").and_then(paint).unwrap_or(Color::BLACK)) } else { None }, stroke: if matches!(pick("57"), Some(Val::Bool(true))) { pick("54").and_then(paint) } else { None }, stroke_width: num("63").filter(|v| *v >= 0.0 && *v < 1e4).unwrap_or(1.0), + // Numbered as PostScript's `setlinecap` and `setlinejoin` operators number them + // (PostScript Language Reference, 3rd ed.): in users' files the page strokes type with + // the cap and join these give, and with key 64 as its miter limit. No file had a bevel + // join (2). Any other value keeps the default. + stroke_cap: match num("61") { + Some(1.0) => LineCap::Round, + Some(2.0) => LineCap::Square, + _ => LineCap::Butt, + }, + stroke_join: match num("62") { + Some(1.0) => LineJoin::Round, + Some(2.0) => LineJoin::Bevel, + _ => LineJoin::Miter, + }, + stroke_miter_limit: num("64").filter(|v| v.is_finite() && *v >= 1.0).map_or(10.0, |v| v.min(500.0)), caps: num("12").filter(|v| *v == 1.0 || *v == 2.0).map_or(0, |v| v as u8), tate_chu_yoko: num("35") == Some(3.0), standard_vertical_roman: num("35") == Some(1.0), @@ -1278,6 +1299,9 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle { fn char_style(s: &Style, scale: f64) -> CharStyle { let (family, style) = s.font.as_deref().map_or_else(|| (CharStyle::default().font_family, "Regular".to_string()), crate::family_style); let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); + // Type without a stroke keeps the stroke's defaults, as its weight is 0. + let (stroke_cap, stroke_join, stroke_miter_limit) = + if s.stroke.is_some() { (s.stroke_cap, s.stroke_join, s.stroke_miter_limit) } else { (LineCap::Butt, LineJoin::Miter, 10.0) }; CharStyle { font_family: family, font_style: style, @@ -1293,6 +1317,9 @@ fn char_style(s: &Style, scale: f64) -> CharStyle { fill: s.fill.map_or(Paint::None, Paint::solid), stroke: s.stroke.map_or(Paint::None, Paint::solid), stroke_width: if s.stroke.is_some() { s.stroke_width * scale } else { 0.0 }, + stroke_cap, + stroke_join, + stroke_miter_limit, all_caps: s.caps == 2, // At the default Small Caps size of Document Setup: the file's own isn't read. small_caps: (s.caps == 1).then(|| vectorcraft_doc::DocSetup::default().small_caps_size), @@ -1573,6 +1600,44 @@ mod tests { assert!(texts(b"/35 3").style(None).tate_chu_yoko && !texts(b"/35 3").style(None).standard_vertical_roman); } + /// Keys 61, 62 and 64 of a character style are its stroke's cap (0 butt, 1 round, 2 + /// projecting), join (0 miter, 1 round, 2 bevel) and miter limit, from the run, its character + /// style or the document's defaults. A value that isn't one of theirs keeps the default, a miter + /// limit past 500 is 500, and type without a stroke keeps the defaults. + #[test] + fn a_run_keeps_its_stroke_cap_join_and_miter_limit() { + let texts = Texts { + stories: vec![], + fonts: vec![], + defaults: read(b"/57 true /54 << /0 << /0 0 /1 [ 1.0 1.0 ] >> >> /64 4.0").unwrap(), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rounded) /6 << /61 1 /62 1 >>").unwrap()], + para_sheets: vec![], + frames: vec![], + }; + let stroke = |run: &[u8]| { + let s = char_style(&texts.style(Some(&read(run).unwrap())), 1.0); + (s.stroke_cap, s.stroke_join, s.stroke_miter_limit) + }; + assert_eq!(stroke(b"/6 << /61 2 /62 2 /64 2.5 >>"), (LineCap::Square, LineJoin::Bevel, 2.5), "the run's own"); + assert_eq!(stroke(b"/5 1 /6 << >>"), (LineCap::Round, LineJoin::Round, 4.0), "its character style's and the defaults'"); + assert_eq!(stroke(b"/5 1 /6 << /62 0 >>"), (LineCap::Round, LineJoin::Miter, 4.0), "the run's own wins over its style"); + assert_eq!(stroke(b"/6 << >>"), (LineCap::Butt, LineJoin::Miter, 4.0), "the defaults'"); + assert_eq!(stroke(b"/6 << /64 1 >>").2, 1.0); + assert_eq!(stroke(b"/6 << /64 1e9 >>").2, 500.0); + for bad in [ + &b"/6 << /61 3 /62 3 /64 0.5 >>"[..], + b"/6 << /61 -1 /62 -1 /64 -4 >>", + b"/6 << /61 1.5 /62 0.5 /64 NaN >>", + b"/6 << /61 (1) /62 (1) /64 inf >>", + b"/6 << /61 true /62 [ 1 ] /64 (4) >>", + b"/6 << /61 1e308 /62 /Round /64 -inf >>", + ] { + assert_eq!(stroke(bad), (LineCap::Butt, LineJoin::Miter, 10.0), "{}", String::from_utf8_lossy(bad)); + } + assert_eq!(stroke(b"/5 1 /6 << /57 false >>"), (LineCap::Butt, LineJoin::Miter, 10.0), "no stroke"); + } + /// A right-to-left paragraph is laid out right to left even when it has no right-to-left /// letters (a dimension's label " 120.5 mm " reads "mm 120.5"); a left-to-right one, or one /// that doesn't say, goes by its letters. @@ -1840,6 +1905,9 @@ mod tests { fill: Some(Color::BLACK), stroke: None, stroke_width: 1.0, + stroke_cap: LineCap::Butt, + stroke_join: LineJoin::Miter, + stroke_miter_limit: 10.0, caps: 0, tate_chu_yoko: false, standard_vertical_roman: false, diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index f71c037c96..2b7b421bba 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -77,6 +77,26 @@ fn names(d: &Document) -> Vec { d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect() } +#[test] +fn ruler_units_in_the_program_header_alone_are_kept() { + let art = layer("Art", true, &square(10, 10)); + let native = |units: &str| { + format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n{units}%AI5_NumLayers: 1\n{art}%%Trailer\n" + ) + }; + let with_header = |data: Vec| { + let at = data.windows(13).position(|w| w == b"%%EndComments").unwrap(); + [&data[..at], &b"%AI5_RulerUnits: 0\n"[..], &data[at..]].concat() + }; + let r = import(&with_header(eps(&page_square(10, 10), &native("")))).unwrap(); + assert_eq!((r.document.units, r.document.units_from_file), (Unit::Inches, true), "the program's header gives them"); + let r = import(&with_header(eps(&page_square(10, 10), &native("%AI5_RulerUnits: 1\n")))).unwrap(); + assert_eq!(r.document.units, Unit::Millimeters, "the editing data's own come first"); + let r = import(&eps(&page_square(10, 10), &native(""))).unwrap(); + assert_eq!((r.document.units, r.document.units_from_file), (Unit::Points, false), "none recorded"); +} + #[test] fn native_import_keeps_ruler_units_from_editing_data() { let art = layer("Art", true, &square(10, 10)); @@ -3291,6 +3311,50 @@ fn a_standard_baseline_run_keeps_standard_vertical_roman_alignment() { } } +#[test] +fn stroked_type_keeps_its_cap_join_and_miter_limit() { + // GUARDS: type strokes came in with a miter join at a limit of 10 whatever the file said, so + // type the file strokes with round or bevel joins, or a lower limit, drew spikes at its corners. + // Four runs over "abcdefgh": "ab" stroked with round caps and joins at a miter limit of 4, "cd" + // with projecting caps and bevel joins at 2.5, "ef" stroked without the keys (the defaults), and + // "gh" with the keys but no stroke. + use vectorcraft_doc::{LineCap, LineJoin}; + let doc = text_document(&[("abcdefgh\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let run = |n: u32, own: &str| { + format!( + "<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 {own}/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 {n} >>" + ) + }; + let one = run(9, ""); + assert!(doc.contains(&one)); + let stroke = "/54 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 0.0 0.0 1.0 ] >> >> /57 true /63 3.0 "; + let runs = [ + run(2, &format!("{stroke}/61 1 /62 1 /64 4.0 ")), + run(2, &format!("{stroke}/61 2 /62 2 /64 2.5 ")), + run(2, stroke), + run(3, "/61 1 /62 1 /64 4.0 "), + ]; + let doc = doc.replacen(&one, &runs.join(" "), 1); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &text_object(0))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.len(), 1, "{:?}", r.warnings); + let strokes: Vec<(String, f64, LineCap, LineJoin, f64)> = texts[0] + .runs + .iter() + .map(|r| (r.text.clone(), r.style.stroke_width, r.style.stroke_cap, r.style.stroke_join, r.style.stroke_miter_limit)) + .collect(); + assert_eq!( + strokes, + [ + ("ab".to_string(), 3.0, LineCap::Round, LineJoin::Round, 4.0), + ("cd".to_string(), 3.0, LineCap::Square, LineJoin::Bevel, 2.5), + ("ef".to_string(), 3.0, LineCap::Butt, LineJoin::Miter, 10.0), + ("gh".to_string(), 0.0, LineCap::Butt, LineJoin::Miter, 10.0), + ] + ); +} + #[test] fn orientation_and_tate_chu_yoko_values_it_cant_use_are_ignored() { for bad in ["(2)", "2.5", "1e300", "-2", "1", "true", "[ 2 ]"] { @@ -5302,7 +5366,6 @@ fn type_envelope(keys: &str, drawn: &str) -> String { /// [`type_envelope`], with `after` (on plain lines, written on `%_` ones) after the text object in /// its contents, such as the text object's XML id. fn type_envelope_with(keys: &str, drawn: &str, after: &str) -> String { - let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); let mesh = format!( "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", @@ -5311,9 +5374,16 @@ fn type_envelope_with(keys: &str, drawn: &str, after: &str) -> String { corner(80.0, 70.0, 80.0, 60.0, 70.0, 70.0), corner(80.0, 40.0, 70.0, 40.0, 80.0, 50.0), ); + type_envelope_on(keys, &mesh, drawn, after) +} + +/// [`type_envelope_with`], with `shape` (on plain lines, written on `%_` ones) in the group before +/// its dictionary, where the editing data saves the envelope's mesh. +fn type_envelope_on(keys: &str, shape: &str, drawn: &str, after: &str) -> String { + let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; format!( "{}{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_1 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", - hidden(&format!("u\n{mesh}U\n")), + hidden(&format!("u\n{shape}U\n")), hidden(&format!("/ArtDictionary :\n{keys}")), hidden(&format!("u\n{}{after}U\n9 () XW\n", text_object(0))), ) @@ -5610,6 +5680,248 @@ fn an_envelope_of_type_bound_to_a_visibility_variable_keeps_its_drawn_art() { assert!(!r.warnings.iter().any(|n| n.contains("variable bindings")), "{:?}", r.warnings); } +/// A one-patch warp grid as the editing data saves it, which no warp style draws: its top edge +/// rises to the right and bulges up. In art space, corners (20, 40) (20, 73) (80, 61) (80, 40), each +/// with its handles towards the next corner and the previous one. +fn rising_grid() -> String { + let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); + format!( + "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", + corner(20.0, 40.0, 20.0, 51.0, 40.0, 40.0), + corner(20.0, 73.0, 40.0, 80.0, 20.0, 62.0), + corner(80.0, 61.0, 80.0, 54.0, 60.0, 72.0), + corner(80.0, 40.0, 60.0, 40.0, 80.0, 47.0), + ) +} + +/// [`rising_grid`] on the page axes as a mesh envelope reads it: its points from the top left, row +/// by row, and their handles (towards the next column, the previous one, the next row and the +/// previous one; none out of the grid). +fn rising_kind() -> vectorcraft_doc::live::EnvelopeKind { + use kurbo::{Point, Vec2}; + let z = Vec2::ZERO; + vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(20.0, 27.0), Point::new(80.0, 39.0), Point::new(20.0, 60.0), Point::new(80.0, 60.0)], + handles: vec![ + [Vec2::new(20.0, -7.0), z, Vec2::new(0.0, 11.0), z], + [z, Vec2::new(-20.0, -11.0), Vec2::new(0.0, 7.0), z], + [Vec2::new(20.0, 0.0), z, z, Vec2::new(0.0, -11.0)], + [z, Vec2::new(-20.0, 0.0), z, Vec2::new(0.0, -7.0)], + ], + } +} + +/// The anchors of the paths `n` draws once its live art is expanded. +fn drawn_anchors(n: &Node) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Path { path, .. } => out.extend(path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p))), + _ => n.children().into_iter().flatten().for_each(|c| walk(c, out)), + } + } + let mut out = vec![]; + walk(&vectorcraft_effects::expand_live_deep(None, n), &mut out); + out +} + +/// A warp of type whose own warp draws apart from its drawn art, where the grid the file saves for +/// it draws as that art, opens as a mesh envelope on that grid, its points and handles as saved: +/// the type is editable, and new text fills the same shape (#3179). +#[test] +fn a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its_text_changes() { + use vectorcraft_doc::live::EnvelopeKind; + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let mut text = made_envelope_type(&doc); + text.visible = true; + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + let shaped = |text: Node| { + let content = vec![std::sync::Arc::new(text)]; + let kind = Box::new(rising_kind()); + Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind, fidelity: 50.0, editing: false, options, frame: Box::default() }, + ) + }; + let (drawn, page) = drawn_envelope(&shaped(text)); + let art = + native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); + let mut live = None; + r.document.walk(|n| { + if matches!(n.kind, NodeKind::Envelope { .. }) { + live = Some(n.clone()); + } + }); + let mut live = live.unwrap(); + let NodeKind::Envelope { kind, content, .. } = &mut live.kind else { panic!("not an envelope: {live:?}") }; + let (EnvelopeKind::Mesh { rows, cols, points, handles }, EnvelopeKind::Mesh { points: want, handles: want_h, .. }) = (&**kind, rising_kind()) + else { + panic!("not a mesh envelope: {kind:?}") + }; + assert_eq!((*rows, *cols), (1, 1)); + assert!(points.iter().zip(&want).all(|(p, q)| (*p - *q).hypot() < 1e-6), "{points:?}"); + assert!(handles.iter().flatten().zip(want_h.iter().flatten()).all(|(h, g)| (*h - *g).hypot() < 1e-6), "{handles:?}"); + // New text in the envelope fills the grid as the old did: "HIH", whose corners are its glyphs', + // reaches each corner of the grid. + let NodeKind::Text(t) = &mut std::sync::Arc::make_mut(&mut content[0]).kind else { panic!("type") }; + let style = t.runs[0].style.clone(); + t.runs = vec![vectorcraft_doc::TextRun::new("HIH", style)]; + (t.cached_bounds, t.cached_ink) = (None, None); + t.cached_baselines.clear(); + let anchors = drawn_anchors(&live); + for corner in want { + let near = anchors.iter().map(|a| (*a - corner).hypot()).fold(f64::INFINITY, f64::min); + assert!(near < 0.25, "{corner:?} is {near} from the new text"); + } +} + +/// A warp of stroked type with Distort Appearance whose drawn art maps the type's bounds with its +/// strokes onto the grid the file saves (not its glyphs' bounds alone) opens live as a mesh envelope +/// mapping from that box (#3179). +#[test] +fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does() { + use vectorcraft_doc::live::{envelope_content_boxes, envelope_stroke_margin}; + let Some(family) = installed_family() else { return }; + // "FLUX" stroked 4 points wide in black. + let stroked = "/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> /54 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 0.0 0.0 1.0 ] >> >> /57 true /63 4.0"; + let doc = type_envelope_text(&family, None).replace("/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >>", stroked); + let mut text = made_envelope_type(&doc); + text.visible = true; + assert!(matches!(&text.kind, NodeKind::Text(t) if t.runs[0].style.stroke_width == 4.0), "{text:?}"); + let content = vec![std::sync::Arc::new(text)]; + let (with, without) = envelope_content_boxes(&content, kurbo::Affine::IDENTITY).unwrap(); + let mut options = vectorcraft_doc::live::EnvelopeOptions::NEW; + options.bounds_margin = envelope_stroke_margin(with, without).unwrap(); + assert!(options.bounds_margin.iter().all(|m| *m > 0.0), "{options:?}"); + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() }, + ); + let (drawn, page) = drawn_envelope(&shaped); + let art = + native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + let mut margin = None; + r.document.walk(|n| { + if let NodeKind::Envelope { options, .. } = &n.kind { + margin = Some(options.bounds_margin); + } + }); + assert_eq!(margin, Some(options.bounds_margin)); +} + +/// A warp of type whose editing data saves no grid it can be shaped by keeps its drawn art and its +/// type, hidden, with the note, when its own warp draws apart from that art (#3179). +#[test] +fn a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let mut text = made_envelope_type(&doc); + text.visible = true; + let content = vec![std::sync::Arc::new(text)]; + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() }, + ); + let (drawn, page) = drawn_envelope(&shaped); + let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), "", &drawn, ""))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert!(envelopes.is_empty(), "{envelopes:?}"); + assert_eq!(loose, [("FLUX".to_string(), false)], "{:?}", r.warnings); + assert_eq!(super::tests::program_warnings(&r.warnings), [crate::import::ai::ENVELOPE_TYPE_DRAWN], "{:?}", r.warnings); +} + +/// A warp of type tried again on its saved grid leaves a check for each envelope of type still to +/// come: with one check too few for both, the next envelope, whose first try opens it, gets it. +#[test] +fn a_warp_of_type_tried_again_leaves_the_next_envelope_its_check() { + use vectorcraft_doc::live::EnvelopeKind; + let Some(family) = installed_family() else { return }; + let story = ("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0); + let mut doc = text_document(&[story, story]).replace("(Helvetica)", &format!("({family})")); + // [`native_with_text`] writes 60 characters a line: the end of the data, `~>`, isn't split. + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let text = made_envelope_type(&doc); + // The first envelope, of story 0, draws as its saved grid and not as its warp: two checks. + let mut shown = text.clone(); + shown.visible = true; + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { + content: vec![std::sync::Arc::new(shown)], + kind: Box::new(rising_kind()), + fidelity: 50.0, + editing: false, + options, + frame: Box::default(), + }, + ); + let (drawn_grid, page_grid) = drawn_envelope(&shaped); + let grid = type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn_grid, ""); + // The second, of story 1, draws as its warp: one check. + let (drawn_arc, page_arc) = drawn_envelope(&arc_envelope(&text, 30.0)); + let arc = type_envelope(&arc_keys(0.3), &drawn_arc).replace("%_0 /StoryIndex", "%_1 /StoryIndex"); + // Envelopes of art before them use all but `left` of the import's checks. + let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; + let rect = "20 5 m\n20 95 L\n80 95 L\n80 5 L\n20 5 L\n"; + let corner = |x: f64, y: f64, nx: f64, ny: f64, px: f64, py: f64| format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); + let mesh = format!( + "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[1 1] /Size X#\n/Data X#\n/DeviceGray /CS X#\n[0 0] /P X#\n{}{}{}{}/E X#\n/End X!\n", + corner(20.0, 5.0, 20.0, 35.0, 40.0, 5.0), + corner(20.0, 95.0, 40.0, 95.0, 20.0, 65.0), + corner(80.0, 95.0, 80.0, 65.0, 60.0, 95.0), + corner(80.0, 5.0, 60.0, 5.0, 80.0, 35.0), + ); + let red = "0 1 1 0 1 0 0 Xa\n"; + let filler = format!( + "{}%_/ArtDictionary :\n%_131073 /Int (AIDeformOptionsKey) ,\n%_50 /Int (AIDeformFidelityKey) ,\n%_0 /Bool (AIDeformEditModeKey) ,\n%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n%_\nu\n{red}{rect}f\nU\n(Adobe Deform Plugin) 1 0 0 XP\n", + hidden(&format!("u\n{mesh}U\n")), + hidden(&format!("u\n{red}{rect}f\nU\n")), + ); + let page = + format!("{}\n1 0 0 setrgbcolor 20 5 moveto 20 95 lineto 80 95 lineto 80 5 lineto closepath fill\n{page_grid}{page_arc}", page_square(10, 10)); + let file = |left: usize| { + let body = format!("{}\n{}{grid}{arc}", square(10, 10), filler.repeat(crate::import::ai::MAX_CHECKED - left)); + eps(&page, &native_with_text(&layer("Art", true, &body), &doc)) + }; + // The live envelopes of type, by kind. + let typed = |d: &Document| { + let mut out = vec![]; + d.walk(|n| { + if let NodeKind::Envelope { content, kind, .. } = &n.kind + && content.iter().any(|c| matches!(c.kind, NodeKind::Text(_))) + { + out.push(if matches!(**kind, EnvelopeKind::Mesh { .. }) { "mesh" } else { "warp" }); + } + }); + out + }; + let r = import(&file(3)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(typed(&r.document), ["mesh", "warp"], "{:?}", r.warnings); + let r = import(&file(2)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(typed(&r.document), ["warp"], "{:?}", r.warnings); +} + /// The fill of the first run of type `n`. fn text_fill(n: &Node) -> Option { let NodeKind::Text(t) = &n.kind else { return None }; diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index c5c1c4c269..6b553b8d1a 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -65,8 +65,8 @@ use std::sync::Arc; use vectorcraft_color::cms::Cms; use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, Paint}; use vectorcraft_doc::{ - AppearanceItem, AreaOptions, CharPosition, CharStyle, CompositeFont, Document, FillLayer, ImageBlob, Justify, LAYER_COLORS, LayerColor, Node, - NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, StrokeLayer, TextKind, TextObject, + AppearanceItem, AreaOptions, CharPosition, CharStyle, CompositeFont, Document, FillLayer, ImageBlob, Justify, Node, NodeKind, ParaDirection, + ParaStyle, PathAlign, PathEffect, StrokeLayer, TextKind, TextObject, }; use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Rect, Shape, SubPath, Vec2}; diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index c3ca85c083..979cd2a436 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -940,6 +940,35 @@ fn names_outside_windows_1252_are_replaced_and_kept_apart() { assert_eq!(inks(&read), want); } +/// #6502: the legacy writer gives Yellow, Magenta and Cyan (presets 4, 5 and 6) the file's +/// indexes 6, 4 and 5, and they open as the same presets. +#[test] +fn layer_presets_are_written_with_the_files_colour_index() { + let mut doc = Document::new(100.0, 100.0); + doc.layers.clear(); + for i in 3..8u8 { + let id = doc.alloc_id(); + doc.layers.push(Arc::new(Node::layer(id, &format!("P{i}"), vectorcraft_doc::LayerColor::Preset(i)))); + } + let out = write(&doc); + let text = String::from_utf8_lossy(&out.bytes).replace("\r\n", "\n"); + for (i, index) in [(3, 3), (4, 6), (5, 4), (6, 5), (7, 7)] { + let [r, g, b] = vectorcraft_doc::LAYER_COLORS[i].1; + let want = format!(" 0 {index} {r} {g} {b} Lb\n(P{i}) Ln\n"); + assert!(text.contains(&want), "missing {want:?} in\n{text}"); + } + let read = crate::import(&out.bytes).unwrap().document; + let colors: Vec<_> = read + .layers + .iter() + .filter_map(|l| match l.kind { + NodeKind::Layer { color, .. } => Some(color), + _ => None, + }) + .collect(); + assert_eq!(colors, (3..8u8).map(vectorcraft_doc::LayerColor::Preset).collect::>()); +} + #[test] fn losses_are_warned() { let mut doc = sample(); diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index cf601e9391..c95940b95d 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -5,9 +5,9 @@ use super::encoding::{ use super::{ Affine, AppearanceItem, Arc, BezPath, BlendMode, CharStyle, Cms, Color, Document, ELLIPTICAL, FREEFORM, FillLayer, FillRule, Gradient, GradientKind, GradientPaint, HEX_LINE, HIDDEN, HIDDEN_LAYER, HIDDEN_SHOWN, HiddenObjects, IMAGE_ALPHA, ImageBlob, Justify, LARGE_IMAGE, - LAYER_COLORS, LAYER_NAME, LIVE, LayerColor, LegacyAiOptions, MAX_IMAGE_PIXELS, MAX_NEST, NAMES, Node, NodeKind, PATTERNS, Paint, ParaDirection, - ParaStyle, PathData, ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, - TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, + LAYER_NAME, LIVE, LegacyAiOptions, MAX_IMAGE_PIXELS, MAX_NEST, NAMES, Node, NodeKind, PATTERNS, Paint, ParaDirection, ParaStyle, PathData, + ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind, + TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; pub(super) struct Writer<'a> { @@ -135,14 +135,7 @@ impl<'a> Writer<'a> { /// A top-level layer. False when it isn't a layer. pub(super) fn layer(&mut self, n: &Node) -> bool { let NodeKind::Layer { color, template, printable, children, clip, preview, dim_images } = &n.kind else { return false }; - let [r, g, b] = match color { - LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(*i)).map_or([79, 128, 255], |c| c.1), - LayerColor::Custom(rgb) => *rgb, - }; - let index = match color { - LayerColor::Preset(i) if usize::from(*i) < LAYER_COLORS.len() => i64::from(*i), - _ => -1, - }; + let (index, [r, g, b]) = ai_ops::layer_color(*color); let flag = |b: bool| u8::from(b); let name = self.layer_name(n.name.as_deref().unwrap_or("Layer")); // A template layer doesn't print and shows dimmed. @@ -173,14 +166,7 @@ impl<'a> Writer<'a> { } let art = std::mem::take(&mut self.hidden_art); let NodeKind::Layer { color, template, printable, .. } = &n.kind else { return false }; - let [r, g, b] = match color { - LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(*i)).map_or([79, 128, 255], |c| c.1), - LayerColor::Custom(rgb) => *rgb, - }; - let index = match color { - LayerColor::Preset(i) if usize::from(*i) < LAYER_COLORS.len() => i64::from(*i), - _ => -1, - }; + let (index, [r, g, b]) = ai_ops::layer_color(*color); let name = format!("{} (hidden)", n.name.as_deref().unwrap_or("Layer")); let name = self.layer_name(&name); let _ = writeln!( diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 5d7aabd077..667b39aad2 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -510,20 +510,35 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result // at `MAX_READ_ANCHORS` anchors together, the document at `MAX_READ_NODES` objects, and the // fields read before an object's type at `MAX_BUFFERED_VALUES` values. The preview and the // PDF are skipped without being kept. - let read = || { - vectorcraft_doc::node::with_node_budget(max_nodes, || { - vectorcraft_doc::node::with_buffered_value_budget(max_values, || Contents::::read(file.json())) + fn within_budgets(max_nodes: usize, max_values: usize, read: impl FnOnce() -> T) -> T { + #[cfg(test)] + DOCUMENT_READS.with(|n| n.set(n.get() + 1)); + vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, || { + vectorcraft_doc::node::with_node_budget(max_nodes, || vectorcraft_doc::node::with_buffered_value_budget(max_values, read)) }) - }; - let mut f = vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, read).map_err(|e| match e { + } + let read_error = |e| match e { ReadError::Json(e) => { let why = if e.to_string().contains("recursion limit") { format!("its objects are nested too deep ({e})") } else { e.to_string() }; FormatError::NotVectorcraft(why) } ReadError::Envelope(e) => e.into(), e => FormatError::NotVectorcraft(e.to_string()), - })?; - let pdf_compatible = pdf_member(file.json()).map_err(|e| FormatError::NotVectorcraft(e.to_string()))?; + }; + // The document and the saved PDF preference come from one pass over the JSON. + let (mut f, pdf_compatible) = match within_budgets(max_nodes, max_values, || Contents::::read_with_pdf_preference(file.json())) { + Ok(read) => read, + // That pass refuses a `pdfCompatible` that is not a boolean, and any other data error. + // When it stopped at the preference, the file is read again without it, and only then is + // its JSON scanned for the preference a second time, so such a file opens as before. Any + // other error, such as a document past a budget, is returned without a second read. + Err(ReadError::Json(e)) if e.is_data() && refused_preference_at(file.json(), &e) => { + let f = within_budgets(max_nodes, max_values, || Contents::::read(file.json())).map_err(read_error)?; + let pdf_compatible = pdf_member(file.json()).map_err(|e| FormatError::NotVectorcraft(e.to_string()))?; + (f, pdf_compatible) + } + Err(e) => return Err(read_error(e)), + }; let info = FileInfo { version: f.version, legacy: f.format == LEGACY_EXTENSION, pdf_compatible }; // A version 1 document saved before VectorCraft 0.21.0, or for an app before it (an older file // version): its Twist angles turned the other way. The app that wrote it is read from the JSON @@ -615,9 +630,62 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result Ok(NativeFile { doc, depth_notes, info, profiles }) } +#[cfg(test)] +thread_local! { + /// Tests: how many times a file's JSON was scanned again for its PDF preference on this thread. + static PDF_MEMBER_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many times a file's document was read on this thread. + static DOCUMENT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether reading `json`'s `pdfCompatible` as a boolean or null fails with a data error at the +/// line and column of `e`, that is, whether the read that gave `e` stopped at the preference. Only +/// the bytes up to that position, and the one there, are read, and they are skipped without being +/// kept. +fn refused_preference_at(json: &[u8], e: &serde_json::Error) -> bool { + // serde_json gives a 1-based line and the bytes before the position on that line. + let Some(line_start) = (match e.line() { + 0 => None, + 1 => Some(0), + n => json.iter().enumerate().filter(|(_, b)| **b == b'\n').nth(n - 2).map(|(i, _)| i + 1), + }) else { + return false; + }; + let end = line_start.saturating_add(e.column()).saturating_add(1).min(json.len()); + struct StrictPreference; + impl<'de> Visitor<'de> for StrictPreference { + type Value = (); + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a native file envelope") + } + + fn visit_map>(self, mut map: A) -> Result<(), A::Error> { + while let Some(key) = map.next_key::()? { + if key == "pdfCompatible" { + map.next_value::>()?; + } else { + map.next_value::()?; + } + } + Ok(()) + } + + fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> { + while seq.next_element::()?.is_some() {} + Ok(()) + } + } + serde_json::Deserializer::from_slice(&json[..end]) + .deserialize_any(StrictPreference) + .is_err_and(|s| s.is_data() && s.line() == e.line() && s.column() == e.column()) +} + /// The saved PDF preference, falling back to the presence of its payload without retaining or /// decoding it. The array form has neither member. Repeated members use their last value. fn pdf_member(json: &[u8]) -> Result { + #[cfg(test)] + PDF_MEMBER_SCANS.with(|n| n.set(n.get() + 1)); struct PdfMember; impl<'de> Visitor<'de> for PdfMember { type Value = bool; @@ -801,6 +869,67 @@ mod tests { } } + #[test] + fn only_a_preference_that_is_not_a_boolean_scans_the_json_again() { + let scans_for = |bytes: &[u8]| { + PDF_MEMBER_SCANS.with(|n| n.set(0)); + let compatible = load_info(bytes).unwrap().1.pdf_compatible; + (compatible, PDF_MEMBER_SCANS.with(|n| n.get())) + }; + let d = Document::new(10.0, 10.0); + assert_eq!(scans_for(&save(&d, false)), (false, 0)); + assert_eq!(scans_for(&save(&d, true)), (false, 0)); + for compatible in [false, true] { + let bytes = save_with(&d, &SaveOptions { pdf_compatible: Some(compatible), ..SaveOptions::default() }).unwrap(); + assert_eq!(scans_for(&bytes), (compatible, 0)); + } + let with_pdf = save_with(&d, &SaveOptions { pdf: Some(vec![7; 1024]), ..SaveOptions::default() }).unwrap(); + assert_eq!(scans_for(&with_pdf), (true, 0)); + let mut value: serde_json::Value = serde_json::from_slice(&save(&d, false)).unwrap(); + for odd in [serde_json::json!("yes"), serde_json::json!(1), serde_json::json!([true])] { + value["pdfCompatible"] = odd.clone(); + assert_eq!(scans_for(&serde_json::to_vec(&value).unwrap()), (false, 1), "{odd}"); + } + // A document that can't be read still fails. Read before the preference, it is not read + // a second time. + value["document"] = serde_json::json!("not a document"); + DOCUMENT_READS.with(|n| n.set(0)); + assert!(load_info(&serde_json::to_vec(&value).unwrap()).is_err()); + assert_eq!(DOCUMENT_READS.with(|n| n.get()), 1); + // Read after a preference that is not a boolean, it fails on the second read, which is + // the first to reach it. + let mut first = serde_json::to_vec(&value).unwrap(); + assert!(first.starts_with(br#"{"document""#)); + first.splice(1..1, br#""pdfCompatible":"yes","#.iter().copied()); + DOCUMENT_READS.with(|n| n.set(0)); + assert!(load_info(&first).is_err()); + assert_eq!(DOCUMENT_READS.with(|n| n.get()), 2); + } + + /// A document past a read budget is refused after one read, also in a file whose preference + /// is not a boolean. + #[test] + fn a_document_past_a_budget_is_read_once() { + let mut d = Document::new(100.0, 100.0); + let l = d.add_layer(None); + for i in 0..20 { + let id = d.alloc_id(); + d.insert(Some(l), i, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())).unwrap(); + } + let n = d.node_count(); + let mut value: serde_json::Value = serde_json::from_slice(&save(&d, false)).unwrap(); + for preference in [serde_json::Value::Null, serde_json::json!(true), serde_json::json!("yes")] { + value["pdfCompatible"] = preference.clone(); + let bytes = serde_json::to_vec(&value).unwrap(); + DOCUMENT_READS.with(|r| r.set(0)); + let Err(FormatError::NotVectorcraft(why)) = load_file_within(&bytes, n - 1, vectorcraft_doc::node::MAX_BUFFERED_VALUES) else { + panic!("one object past the budget must be refused") + }; + assert!(why.contains(&format!("more than {} objects", n - 1)), "{why}"); + assert_eq!(DOCUMENT_READS.with(|r| r.get()), 1, "{preference}"); + } + } + #[test] fn file_info_keeps_the_pdf_preference_without_artboards() { let mut d = Document::new(10.0, 10.0); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index d420b94b31..dfb2cf9f7c 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -10,6 +10,7 @@ //! run past [`crate::Limits`]. mod array; +pub(crate) mod extensions; mod global; mod json; mod math; @@ -358,6 +359,13 @@ fn object_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResu /// `Object.prototype.toString` (section 15.2.4.2). fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + // With `$.localize` on, a localization object gives its text for the current locale. + if interp.localization.enabled() + && let Value::Object(id) = this + && let Some(text) = extensions::localized_text(interp, id)? + { + return Ok(text); + } let class = match &this { Value::Undefined => "Undefined", Value::Null => "Null", @@ -472,7 +480,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe Ok(p) => p, Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)), }; - let source = Rc::new(Source { lines: program.lines.clone(), text: units.into() }); + let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() }); let code = match compile_constructed_function(&program, &source) { Ok(Some(code)) => code, Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), @@ -501,7 +509,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> return Ok(Value::String(Str::from_units(units.to_vec()))); } Some(Func::Native { name, .. }) => format!("function {name}() {{ [native code] }}"), - Some(Func::Host { name, .. } | Func::Data { name, .. }) => format!("function {name}() {{ [native code] }}"), + Some(Func::Host { name, .. } | Func::Data { name, .. } | Func::Eval { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Bound { .. }) => "function () { [native code] }".to_string(), None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")), }; diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs new file mode 100644 index 0000000000..15ebbe734f --- /dev/null +++ b/crates/js/src/builtins/extensions.rs @@ -0,0 +1,400 @@ +//! The script extensions a host adds with [`crate::Realm::add_script_extensions`]: the global +//! `localize`, the global `toSource` and `Object.prototype.toSource`, and the getters behind +//! [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of +//! [`Localization`]. +//! +//! `toSource` writes primitives, arrays and plain objects as the text of a JavaScript expression +//! that makes the same value: strings in double quotes, property names quoted, properties in the +//! order the object lists them, a hole in an array as an empty element. It never runs a getter or +//! a script's own method: a getter, a function, a date, a regular expression, an error, a boxed +//! primitive, an array with properties besides its elements, an object whose prototype is not +//! `Object.prototype`, a property that is not enumerable or any other object that is not plain +//! data throws a `TypeError`, and so does an object that contains itself. A value nested deeper, with more entries or longer text than the +//! realm's [`crate::DataLimits`] allow throws a `RangeError`. Every value written takes fuel. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +use super::{Builder, arg, method}; +use crate::heap::{Class, NativeFn, ObjId, Prop, key}; +use crate::interp::{ErrorType, Interp, JsResult}; +use crate::value::{Value, array_index, index_key, number_to_str}; +use crate::{ScriptItem, bytecode::Code}; + +/// The locale `localize` looks a localization object up in, and whether `toString` gives an +/// object's localized text (`$.localize`). A host changes it through [`crate::Realm::localization`]. +#[derive(Debug)] +pub struct Localization { + locale: RefCell, + platform: Cell>, + enabled: Cell, +} + +impl Default for Localization { + fn default() -> Self { + Self { locale: RefCell::new("en".into()), platform: Cell::new(None), enabled: Cell::new(false) } + } +} + +impl Localization { + /// The locale, a language and an optional region joined by `_`, such as `de_DE`. + pub fn locale(&self) -> String { + self.locale.borrow().clone() + } + + pub fn set_locale(&self, locale: &str) { + *self.locale.borrow_mut() = locale.to_string(); + } + + /// The platform suffix the lookup tries first (`Win`, `Mac` or `Unix`), or none. + pub fn platform(&self) -> Option<&'static str> { + self.platform.get() + } + + pub fn set_platform(&self, platform: Option<&'static str>) { + self.platform.set(platform); + } + + /// Does `Object.prototype.toString` give an object's localized text? + pub fn enabled(&self) -> bool { + self.enabled.get() + } + + pub fn set_enabled(&self, on: bool) { + self.enabled.set(on); + } + + /// The property names a localization object is looked up by, in order: the locale with the + /// platform suffix, the locale, its language with the suffix, its language, and `en`. + pub fn keys(&self) -> Vec { + let locale = self.locale(); + let language = locale.split('_').next().unwrap_or_default().to_string(); + let mut keys = Vec::with_capacity(5); + for name in [&locale, &language] { + if let Some(p) = self.platform() { + keys.push(format!("{name}_{p}")); + } + keys.push(name.clone()); + } + keys.push("en".into()); + let mut unique = Vec::with_capacity(keys.len()); + for k in keys { + if !k.is_empty() && !unique.contains(&k) { + unique.push(k); + } + } + unique + } +} + +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let global = interp.global; + method(interp, global, "localize", localize, 1)?; + method(interp, global, "toSource", to_source, 1)?; + let object_proto = interp.intrinsics.object_proto; + method(interp, object_proto, "toSource", to_source_method, 0) +} + +/// The text of the localization object `id` for the current locale: the string value of the first +/// of [`Localization::keys`] that the object has as its own data property. No getter runs. +pub(crate) fn localized_text(interp: &mut Interp, id: ObjId) -> JsResult> { + if !matches!(interp.object(id)?.class, Class::Ordinary) { + return Ok(None); + } + for k in interp.localization.keys() { + interp.use_fuel()?; + if let Some(Prop::Data { value: v @ Value::String(_), .. }) = interp.get_own_property(id, &key(&k))? { + return Ok(Some(v)); + } + } + Ok(None) +} + +/// `localize(object, ...values)`: the text of a localization object for the current locale, or of +/// a string, with `%1` replaced by the first value, `%2` by the second and so on. A number with no +/// value stays as it is. An object with none of the locale's names is returned as it is. +fn localize(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let mark = interp.temp_roots.len(); + interp.temp_roots.extend(args.iter().cloned()); + let r = localize_rooted(interp, args); + interp.temp_roots.truncate(mark); + r +} + +fn localize_rooted(interp: &mut Interp, args: &[Value]) -> JsResult { + let text = match args.first() { + Some(Value::String(s)) => s.flat(), + Some(first @ Value::Object(id)) => match localized_text(interp, *id)? { + Some(Value::String(s)) => s.flat(), + _ => return Ok(first.clone()), + }, + _ => return Err(interp.type_error("localize: the first argument must be a localization object or a string")), + }; + let values = args.get(1..).unwrap_or_default(); + let mut converted: Vec>> = vec![None; values.len()]; + let mut out = Builder::new(); + let (mut start, mut i) = (0, 0); + while let Some(&u) = text.get(i) { + if u != u16::from(b'%') { + i += 1; + continue; + } + let digits = text.get(i + 1..).unwrap_or_default().iter().take(4).take_while(|d| (0x30..=0x39).contains(*d)).count(); + let n = text.get(i + 1..i + 1 + digits).unwrap_or_default().iter().fold(0usize, |n, d| n * 10 + usize::from(*d - 0x30)); + let Some(slot) = n.checked_sub(1).filter(|&k| digits > 0 && k < values.len()) else { + i += 1 + digits; + continue; + }; + out.push_units(interp, text.get(start..i).unwrap_or_default())?; + let units = match converted.get(slot).cloned().flatten() { + Some(u) => u, + None => { + let s = interp.to_str(&arg(values, slot))?.flat(); + if let Some(c) = converted.get_mut(slot) { + *c = Some(s.clone()); + } + s + } + }; + out.push_units(interp, &units)?; + i += 1 + digits; + start = i; + } + out.push_units(interp, text.get(start..).unwrap_or_default())?; + Ok(out.finish(interp)) +} + +/// The global `toSource(value)`. +fn to_source(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + write_source(interp, arg(args, 0)) +} + +/// `Object.prototype.toSource()`: the source of the value it is called on. +fn to_source_method(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + write_source(interp, this) +} + +fn write_source(interp: &mut Interp, v: Value) -> JsResult { + let mark = interp.temp_roots.len(); + interp.temp_roots.push(v.clone()); + let mut w = Source { out: Builder::new(), ancestors: Vec::new(), entries: 0 }; + let r = w.value(interp, &v); + interp.temp_roots.truncate(mark); + r?; + Ok(w.out.finish(interp)) +} + +/// A value being written as source: the text so far, the objects it is inside and the entries it +/// has written. +struct Source { + out: Builder, + ancestors: Vec, + entries: usize, +} + +impl Source { + fn push(&mut self, interp: &mut Interp, s: &str) -> JsResult<()> { + self.out.push_str(interp, s)?; + self.check_length(interp) + } + + fn check_length(&mut self, interp: &mut Interp) -> JsResult<()> { + self.fit(interp, 0) + } + + /// Checks that `more` code units can be added without passing the length limit. + fn fit(&mut self, interp: &mut Interp, more: usize) -> JsResult<()> { + if self.out.units.len().saturating_add(more) > interp.data_limits.bytes { + return Err(interp.throw(ErrorType::Range, "toSource: the source is too long")); + } + Ok(()) + } + + fn count(&mut self, interp: &mut Interp, n: usize) -> JsResult<()> { + self.entries = self.entries.saturating_add(n); + if self.entries > interp.data_limits.entries { + return Err(interp.throw(ErrorType::Range, "toSource: the value has too many entries")); + } + Ok(()) + } + + fn value(&mut self, interp: &mut Interp, v: &Value) -> JsResult<()> { + interp.use_fuel()?; + match v { + Value::Undefined => self.push(interp, "(void 0)"), + Value::Null => self.push(interp, "null"), + Value::Bool(b) => self.push(interp, if *b { "true" } else { "false" }), + Value::Number(n) if *n == 0.0 && n.is_sign_negative() => self.push(interp, "-0"), + Value::Number(n) => { + self.out.push_units(interp, &number_to_str(*n).flat())?; + self.check_length(interp) + } + Value::String(s) => self.quoted(interp, &s.flat()), + Value::Object(id) => self.object(interp, *id), + } + } + + /// `s` in double quotes, with the characters a string literal cannot hold escaped. The length + /// limit is checked before each addition, so a string that grows as it is escaped throws a + /// `RangeError` before the text takes more heap than the limit allows. + fn quoted(&mut self, interp: &mut Interp, s: &[u16]) -> JsResult<()> { + self.fit(interp, 1)?; + self.out.push_str(interp, "\"")?; + let mut start = 0; + for (i, &c) in s.iter().enumerate() { + let escape = match c { + 0x22 => "\\\"".to_string(), + 0x5C => "\\\\".to_string(), + 0x0A => "\\n".to_string(), + 0x0D => "\\r".to_string(), + 0x09 => "\\t".to_string(), + 0x08 => "\\b".to_string(), + 0x0C => "\\f".to_string(), + 0..=0x1F | 0x7F | 0x2028 | 0x2029 | 0xD800..=0xDFFF => format!("\\u{c:04X}"), + _ => continue, + }; + self.fit(interp, (i - start).saturating_add(escape.len()))?; + self.out.push_units(interp, s.get(start..i).unwrap_or_default())?; + self.out.push_str(interp, &escape)?; + start = i + 1; + } + self.fit(interp, s.len().saturating_sub(start).saturating_add(1))?; + self.out.push_units(interp, s.get(start..).unwrap_or_default())?; + self.push(interp, "\"") + } + + fn object(&mut self, interp: &mut Interp, id: ObjId) -> JsResult<()> { + if self.ancestors.contains(&id) { + return Err(interp.type_error("toSource: the value contains itself")); + } + if self.ancestors.len() >= interp.data_limits.depth { + return Err(interp.throw(ErrorType::Range, "toSource: the value is nested too deep")); + } + let (object_proto, array_proto) = (interp.intrinsics.object_proto, interp.intrinsics.array_proto); + let o = interp.object(id)?; + // The text makes an array or an object from `Object.prototype` with enumerable properties + // only, so an array with other properties, an object with another prototype and a property + // that is not enumerable are refused. + let enumerable = o.props.iter().all(|(_, p)| p.enumerable()); + let shape = match &o.class { + Class::Array { length, .. } + if o.proto == Some(array_proto) && enumerable && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) => + { + Some(Err(*length)) + } + Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)), + Class::Ordinary if o.proto == Some(object_proto) && enumerable => { + Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::>())) + } + Class::Ordinary => return Err(interp.type_error(NOT_PLAIN_OBJECT)), + _ => None, + }; + let Some(shape) = shape else { + let what = format!("toSource: a {} cannot be written as source", interp.object(id)?.class.name()); + return Err(interp.type_error(&what)); + }; + self.ancestors.push(id); + let r = match shape { + Err(length) => self.array(interp, id, length), + Ok(props) => self.plain(interp, props), + }; + self.ancestors.pop(); + r + } + + fn array(&mut self, interp: &mut Interp, id: ObjId, length: u32) -> JsResult<()> { + self.count(interp, length as usize)?; + self.push(interp, "[")?; + let mut hole = false; + for i in 0..length { + interp.use_fuel()?; + if i > 0 { + self.push(interp, ", ")?; + } + let prop = interp.object(id)?.props.get(&index_key(i)).cloned(); + hole = prop.is_none(); + match prop { + None => {} + Some(Prop::Data { value, .. }) => self.value(interp, &value)?, + Some(Prop::Accessor { .. }) => return Err(interp.type_error("toSource: a getter cannot be written as source")), + } + } + // A hole at the end needs a comma of its own, or the array would be one shorter. + if hole { + self.push(interp, ",")?; + } + self.push(interp, "]") + } + + fn plain(&mut self, interp: &mut Interp, props: Vec<(crate::heap::Key, Prop)>) -> JsResult<()> { + self.count(interp, props.len())?; + self.push(interp, "({")?; + for (n, (k, prop)) in props.into_iter().enumerate() { + interp.use_fuel()?; + if n > 0 { + self.push(interp, ", ")?; + } + let Prop::Data { value, .. } = prop else { return Err(interp.type_error("toSource: a getter cannot be written as source")) }; + self.quoted(interp, &k)?; + self.push(interp, ":")?; + self.value(interp, &value)?; + } + self.push(interp, "})") + } +} + +const NOT_PLAIN_ARRAY: &str = + "toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source"; +const NOT_PLAIN_OBJECT: &str = + "toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source"; + +/// The getter behind `item`; [`ScriptItem::Global`] is a value and has none. +pub(crate) fn getter(item: ScriptItem) -> Option<(&'static str, NativeFn)> { + match item { + ScriptItem::Global => None, + ScriptItem::LastError => Some(("error", last_error)), + ScriptItem::Line => Some(("line", line)), + ScriptItem::Stack => Some(("stack", stack)), + } +} + +fn last_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Ok(interp.last_error.clone()) +} + +fn line(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let line = interp.script_frames().last().map_or(0, |(code, pc, _)| code.line_column(pc.saturating_sub(1)).0); + Ok(Value::Number(f64::from(line))) +} + +/// The most frames `$.stack` lists, and the most characters of a function's name it shows. +const STACK_FRAMES: usize = 64; +const STACK_NAME_UNITS: usize = 64; + +/// The script's frames, outermost first, one a line: the function's name and the line it is at. +fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let frames: Vec<(Rc, usize, bool)> = interp.script_frames().map(|(c, pc, f)| (c.clone(), pc, f)).collect(); + let skip = frames.len().saturating_sub(STACK_FRAMES); + let mut text = String::new(); + if skip > 0 { + text.push_str("…\n"); + } + for (code, pc, function) in frames.iter().skip(skip) { + interp.use_fuel()?; + let name = if *function { function_name(code) } else { "[global]".to_string() }; + let line = code.line_column(pc.saturating_sub(1)).0; + text.push_str(&format!("{name}:{line}\n")); + } + let mut out = Builder::new(); + out.push_str(interp, &text)?; + Ok(out.finish(interp)) +} + +/// The name `code` has: its own as a function expression's, or its declaration's, cut to +/// [`STACK_NAME_UNITS`]; `[anonymous]` without one. +fn function_name(code: &Code) -> String { + match code.self_name.as_ref().or(code.decl_name.as_ref()) { + Some(name) => String::from_utf16_lossy(name.get(..STACK_NAME_UNITS).unwrap_or(&**name)), + None => "[anonymous]".to_string(), + } +} diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index b23d9a525d..9681d01681 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -171,6 +171,11 @@ pub(crate) struct Handler { pub(crate) struct Source { pub(crate) lines: LineTable, pub(crate) text: Rc<[u16]>, + /// Which source this is, as [`crate::Realm::error_source`] gives it. + pub(crate) tag: u32, + /// Writes to read-only and getter-only properties, and new properties on objects that are + /// not extensible, throw in this source's code even where it is not strict mode code. + pub(crate) strict_writes: bool, } #[derive(Debug)] @@ -190,6 +195,8 @@ pub(crate) struct Code { pub(crate) strict: bool, /// A function expression's own name, bound inside it. pub(crate) self_name: Option, + /// A function declaration's name, which `$.stack` shows. + pub(crate) decl_name: Option, pub(crate) params: Vec, pub(crate) vars: Vec, /// Function declarations to instantiate on entry: their names and indices in `functions`. diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index ae470be443..34e64814b6 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -1193,6 +1193,7 @@ impl<'a> FnCompiler<'a> { max_stack: 0, strict: self.strict, self_name: meta.self_name, + decl_name: meta.decl_name, params: meta.params, vars: hoisted.vars, fun_decls: hoisted.fun_decls, @@ -1209,6 +1210,7 @@ impl<'a> FnCompiler<'a> { #[derive(Default)] struct Meta { self_name: Option, + decl_name: Option, params: Vec, span: (u32, u32), } @@ -1231,6 +1233,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, c.emit(Op::Return); let name = f.name.as_ref().map(|n| key_of(&n.name)); let meta = Meta { + decl_name: if f.kind == FunctionKind::Declaration { name.clone() } else { None }, self_name: if bind_name && f.kind == FunctionKind::Expression { name } else { None }, params: f.params.iter().map(|p| key_of(&p.name)).collect(), span: (f.span.start, f.span.end), diff --git a/crates/js/src/extension_tests.rs b/crates/js/src/extension_tests.rs new file mode 100644 index 0000000000..19a20ab5b8 --- /dev/null +++ b/crates/js/src/extension_tests.rs @@ -0,0 +1,202 @@ +//! The script extensions: `localize`, `toSource`, host properties with setters and the items that +//! read the interpreter's own state. + +use std::cell::RefCell; +use std::rc::Rc; + +use super::*; + +fn realm() -> Realm { + let mut r = Realm::new(); + r.add_script_extensions().unwrap(); + r +} + +fn text(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Ok(JsValue::String(s)) => s, + other => panic!("{source}: {other:?}"), + } +} + +fn thrown(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Err(e) if e.kind == RunErrorKind::Thrown => e.message, + other => panic!("{source}: {other:?}"), + } +} + +#[test] +fn localize_looks_up_the_locale_with_its_platform_then_its_language_then_english() { + let mut r = realm(); + let l = r.localization(); + l.set_locale("de_DE"); + l.set_platform(Some("Win")); + assert_eq!(l.keys(), ["de_DE_Win", "de_DE", "de_Win", "de", "en"]); + let all = "({en: 'e', de: 'd', de_Win: 'dw', de_DE: 'dd', de_DE_Win: 'ddw'})"; + assert_eq!(text(&mut r, &format!("localize({all})")), "ddw"); + assert_eq!(text(&mut r, "localize({en: 'e', de: 'd', de_Win: 'dw', de_DE: 'dd'})"), "dd"); + assert_eq!(text(&mut r, "localize({en: 'e', de: 'd', de_Win: 'dw'})"), "dw"); + assert_eq!(text(&mut r, "localize({en: 'e', de: 'd', DE: 'x'})"), "d", "names are case sensitive"); + assert_eq!(text(&mut r, "localize({en: 'e', fr: 'f'})"), "e"); + l.set_platform(None); + assert_eq!(text(&mut r, &format!("localize({all})")), "dd"); + l.set_locale("en"); + assert_eq!(l.keys(), ["en"]); +} + +#[test] +fn localize_replaces_numbered_values_once_and_leaves_the_rest() { + let mut r = realm(); + assert_eq!(text(&mut r, "localize({en: '%2 before %1, %1 again'}, 'a', 'b')"), "b before a, a again"); + assert_eq!(text(&mut r, "localize('%1%% %3 %0 %', 'x', '%1')"), "x%% %3 %0 %"); + assert_eq!(text(&mut r, "localize('%2', 'x', '%1')"), "%1", "a value is not replaced again"); + assert_eq!(text(&mut r, "localize('%1', {toString: function () { return 'o'; }})"), "o"); + assert_eq!(text(&mut r, "var n = 0; var v = {toString: function () { n++; return 'v'; }}; localize('%1%1', v) + n"), "vv1"); +} + +#[test] +fn localize_gives_back_an_object_without_the_locale_and_runs_no_getter() { + let mut r = realm(); + r.localization().set_locale("fr_FR"); + assert_eq!(r.run("var o = {de: 'd'}; localize(o) === o").unwrap(), JsValue::Bool(true)); + let source = "var hit = false; var o = {get fr() { hit = true; return 'g'; }, en: 'e'}; localize(o) + ',' + hit"; + assert_eq!(text(&mut r, source), "e,false"); + assert_eq!(text(&mut r, "localize({fr: 1, en: 'e'})"), "e", "a value that is not a string is passed over"); + for bad in ["localize()", "localize(1)", "localize(null)"] { + assert!(thrown(&mut r, bad).starts_with("TypeError"), "{bad}"); + } +} + +#[test] +fn to_string_localizes_an_object_only_while_localization_is_on() { + let mut r = realm(); + r.localization().set_locale("ja"); + let source = "String({en: 'Hello', ja: 'こんにちは'}) + '|' + String({x: 1})"; + assert_eq!(text(&mut r, source), "[object Object]|[object Object]"); + r.localization().set_enabled(true); + assert_eq!(text(&mut r, source), "こんにちは|[object Object]"); +} + +#[test] +fn to_source_writes_plain_data_as_an_expression_that_makes_it_again() { + let mut r = realm(); + let source = r#"toSource({a: [1, "x\n\"", null, true, -0, 1.5e300], "b c": {d: undefined}, e: {}, f: []})"#; + let want = r#"({"a":[1, "x\n\"", null, true, -0, 1.5e+300], "b c":({"d":(void 0)}), "e":({}), "f":[]})"#; + assert_eq!(text(&mut r, source), want); + assert_eq!(text(&mut r, "[1, , 3].toSource() + '|' + [1, ,].toSource() + '|' + [,].toSource()"), "[1, , 3]|[1, ,]|[,]"); + assert_eq!( + text(&mut r, "toSource(NaN) + toSource(-Infinity) + toSource() + toSource('\\u2028\\ud800\\x7f')"), + "NaN-Infinity(void 0)\"\\u2028\\uD800\\u007F\"" + ); + assert_eq!(text(&mut r, "(5).toSource() + 'a'.toSource() + true.toSource()"), "5\"a\"true"); + // Parsed back, the text makes the same value: holes, -0 and undefined included. + let round = r#"var v = {a: [1, , "q\u0001'\\"], b: {"0": -0, "": undefined, "x y": [[]]}}; + var w = eval(toSource(v)); + [JSON.stringify(w) === JSON.stringify(v), w.a.length, 1 in w.a, 1 / w.b[0], "" in w.b].join()"#; + assert_eq!(text(&mut r, round), "true,3,false,-Infinity,true"); + let shared = "var s = {k: 1}; toSource([s, s])"; + assert_eq!(text(&mut r, shared), r#"[({"k":1}), ({"k":1})]"#, "a value seen twice that is not its own ancestor is written twice"); +} + +#[test] +fn to_source_refuses_what_is_not_plain_data() { + let mut r = realm(); + for (source, kind) in [ + ("var o = {}; o.o = o; toSource(o)", "TypeError"), + ("var a = [1]; a.push([a]); toSource(a)", "TypeError"), + ("toSource({f: function () {}})", "TypeError"), + ("toSource({get g() { return 1; }})", "TypeError"), + ("toSource(new Date(0))", "TypeError"), + ("toSource([/x/])", "TypeError"), + ("toSource(new Error('e'))", "TypeError"), + ("toSource(new String('s'))", "TypeError"), + ("var a = [1]; a.extra = 2; toSource(a)", "TypeError"), + ("toSource(Object.create(Array.prototype))", "TypeError"), + ("var o = {}; Object.defineProperty(o, 'hidden', {value: 1}); toSource(o)", "TypeError"), + ("var a = [0]; Object.defineProperty(a, '0', {value: 1, enumerable: false}); toSource(a)", "TypeError"), + ("toSource(Object.create({a: 1}))", "TypeError"), + ("toSource(Object.create(null))", "TypeError"), + ("function F() { this.a = 1; } toSource(new F())", "TypeError"), + ("var d = []; for (var i = 0; i < 70; i++) d = [d]; toSource(d)", "RangeError"), + ("var a = []; a.length = 2000000; toSource(a)", "RangeError"), + ] { + assert!(thrown(&mut r, source).starts_with(kind), "{source}"); + } + assert!(thrown(&mut r, "toSource({get g() { throw 'ran'; }})").starts_with("TypeError"), "the getter does not run"); +} + +#[test] +fn to_source_of_a_string_with_many_escapes_throws_a_range_error_before_the_heap_limit() { + let mut r = realm(); + // A run's heap in the web build. 2^23 control characters, each written as six, pass a quarter + // of it, which is all one string may take. + r.set_limits(Limits { heap_bytes: 128 << 20, ..Limits::default() }); + let source = "var s = '\\x01'; for (var i = 0; i < 23; i++) s = s + s; + try { toSource(s); 'no error'; } catch (e) { e.name + ': ' + e.message; }"; + assert_eq!(text(&mut r, source), "RangeError: toSource: the source is too long"); + assert_eq!(text(&mut r, "toSource('a\\x01a\\x01a\\x01a\\x01').length + ''"), "30", "short strings are written whole"); +} + +#[test] +fn to_source_stops_at_the_fuel_limit() { + let mut r = realm(); + r.set_limits(Limits { fuel: 200_000, ..Limits::default() }); + let e = r.run("var a = []; for (var i = 0; i < 1000; i++) a.push(i); while (true) toSource(a);").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); +} + +#[test] +fn script_items_read_the_global_object_the_last_error_the_line_and_the_stack() { + let mut r = realm(); + let items = ["global", "error", "line", "stack"] + .into_iter() + .zip([ScriptItem::Global, ScriptItem::LastError, ScriptItem::Line, ScriptItem::Stack]) + .map(|(n, i)| (n.to_string(), HostItem::Script(i))) + .collect(); + r.define_host_object("h", items).unwrap(); + assert_eq!(r.run("var later = 2; h.global === this && h.global.later === 2").unwrap(), JsValue::Bool(true)); + let source = "var before = h.error; try { null.x; } catch (e) {} var caught = h.error; try { throw 'text'; } catch (e) {} + [before === null, caught instanceof TypeError, h.error === caught].join()"; + assert_eq!(text(&mut r, source), "true,true,true"); + let source = "try { try { throw new RangeError('first'); } finally { try { throw new TypeError('second'); } catch (e) {} } } catch (e) {} + h.error.message"; + assert_eq!(text(&mut r, source), "second", "an exception a finally block passes on is not thrown again"); + let source = "try { [1].map(function () { try { throw new RangeError('first'); } finally { try { throw new TypeError('second'); } catch (e) {} } }); } catch (e) {} + h.error.message"; + assert_eq!(text(&mut r, source), "second", "nor is one that leaves a built-in's callback"); + let source = "var kept; try { throw new RangeError('first'); } catch (e) { kept = e; } try { throw new TypeError('second'); } catch (e) {} + try { throw kept; } catch (e) {} h.error.message"; + assert_eq!(text(&mut r, source), "first", "throwing a caught error again makes it the last one"); + assert_eq!(r.run("h.error").unwrap(), JsValue::Null, "each run starts without one"); + assert_eq!(r.run("\n\n h.line").unwrap(), JsValue::Number(3.0)); + let source = "function outer() {\n return inner();\n}\nfunction inner() {\n return h.stack;\n}\nvar f = function () { return outer(); };\nf()"; + assert_eq!(text(&mut r, source), "[global]:8\n[anonymous]:7\nouter:2\ninner:5\n"); + let source = "function maker() {\n function named() {\n return h.stack;\n }\n return named;\n}\nvar later = maker();\nlater()"; + assert_eq!(text(&mut r, source), "[global]:8\nnamed:3\n", "a declared function keeps its name after its declaring function returns"); + let deep = "function d(n) { return n ? d(n - 1) : h.stack; } var s = d(100).split('\\n'); s.length + ',' + s[0]"; + let lines = text(&mut r, deep); + assert_eq!(lines, "66,…", "64 frames, the line that some are left out, and the last line's end"); + assert!(thrown(&mut r, "'use strict'; h.line = 1").starts_with("TypeError"), "the items cannot be assigned"); +} + +#[test] +fn a_host_property_reads_its_getter_and_gives_assignments_to_its_setter() { + let mut r = Realm::new(); + let seen: Rc>> = Rc::default(); + let log = seen.clone(); + let get: HostFunction = Rc::new(move |_| Ok(Data::String("got".into()))); + let set: HostFunction = Rc::new(move |args| match args.first() { + Some(Data::Number(n)) if *n < 0.0 => Err(HostError::Range("no negatives".into())), + Some(d) => { + log.borrow_mut().push(d.clone()); + Ok(Data::Undefined) + } + None => Ok(Data::Undefined), + }); + r.define_host_object("h", vec![("p".into(), HostItem::Property { get, set })]).unwrap(); + assert_eq!(r.run("h.p = 5; h.p = {a: [1]}; h.p").unwrap(), JsValue::String("got".into())); + assert_eq!(*seen.borrow(), [Data::Number(5.0), Data::Object(vec![("a".into(), Data::Array(vec![Data::Number(1.0)]))])]); + let e = r.run("try { h.p = -1; } catch (e) { e instanceof RangeError && e.message }").unwrap(); + assert_eq!(e, JsValue::String("no negatives".into())); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index a53721fc71..0dbe949889 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -175,12 +175,16 @@ pub(crate) enum NativeKind { /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section /// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given. +/// `Data` is a host function given [`crate::Data`], its arguments read as `read` says. `Eval` is a +/// host function that gives source to run as global code ([`crate::HostItem::Evaluator`]); `end` +/// is called when that code ends. #[derive(Clone)] pub(crate) enum Func { Closure { code: Rc, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, Host { f: Rc, name: Rc }, - Data { f: DataFn, name: Rc }, + Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, + Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } @@ -525,7 +529,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) { strings.add(flags); } let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k)); - for k in keys.chain(&code.self_name) { + for k in keys.chain(&code.self_name).chain(&code.decl_name) { strings.add_key(k); } stack.extend(code.functions.iter().map(|f| &**f)); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 457b2ce2e1..4ec8f2c721 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -55,23 +55,97 @@ pub enum HostError { Type(String), /// Thrown to the script as a `RangeError`. Range(String), + /// Thrown to the script as a `SyntaxError`. + Syntax(String), /// Ends the run with [`LimitKind::Host`] and this message. The script cannot catch it. Abort(String), + /// Pauses the run at this call: [`crate::Realm::advance`] returns [`crate::Progress::Paused`], + /// and the call's result is the value [`crate::Realm::answer`] gives it. A function may return + /// it only while [`crate::Realm::wait_flag`] is set; otherwise the run ends with an internal + /// error. + Wait, + /// `error`, with a mark the host chose. When the run ends with the exception `error` throws, + /// or with the limit it ends the run with, [`crate::Realm::error_mark`] gives `mark`. A `catch` + /// clause that takes the exception drops the mark, so a `throw` of the caught value later + /// raises it without one; a `finally` block that ends normally keeps it. + Marked { error: Box, mark: u32 }, } /// A function the host gives a script, with its arguments converted. pub type HostFunction = Rc) -> Result>; +/// How one argument of a [`HostItem::Converted`] function is read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Arg { + /// The string `String(value)` gives. + Text, + /// `undefined` as [`Data::Undefined`], any other value as the string `String(value)` gives. + TextOrUndefined, + /// The boolean `Boolean(value)` gives. + Bool, +} + +/// How the arguments of a host function are read. +#[derive(Clone)] +pub(crate) enum ArgRead { + /// Each as [`Data`]. + Data, + /// Each as the string `String(value)` gives. + Text, + /// One by one as the list says; those past its end are not read. + Each(Rc<[Arg]>), +} + /// A member of an object the host adds to the global environment. #[derive(Clone)] pub enum HostItem { /// A read-only copy of a value. Value(Data), Function(HostFunction), + /// A function whose arguments arrive as strings, each the string `String(value)` gives. + TextFunction(HostFunction), + /// A function whose arguments arrive converted one by one as the list says. Arguments past the + /// end of the list are not read and do not reach the function. + Converted(Vec, HostFunction), /// A property whose value the function gives each time it is read. Getter(HostFunction), + /// A property whose value `get` gives each time it is read, and that `set` is given each value + /// assigned to it, as its one argument; an error from `set` is thrown to the script. + Property { + get: HostFunction, + set: HostFunction, + }, /// A frozen object with these members. Object(Vec<(String, HostItem)>), + /// A function whose host function gives JavaScript source as a string, which then runs as + /// global code in the realm, as an indirect `eval` runs it, with the run's fuel and limits: + /// the call gives that code's completion value, and its declarations become globals. A result + /// that is not a string is the call's result. `end` is called when the source has run, + /// normally or not. Each source given has the next tag of [`crate::Realm::error_source`], + /// from 1. `strict_writes`, called after `source`, gives [`crate::Realm::set_strict_writes`] + /// for that source alone; with `None` it takes the calling code's. + Evaluator { + source: HostFunction, + end: Rc, + strict_writes: Rc Option>, + }, + /// A read-only property that reads the interpreter's own state. + Script(ScriptItem), +} + +/// The interpreter's own state a host object can show. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ScriptItem { + /// The global object itself, with every global the script has made. + Global, + /// The last `Error` object thrown in the current run, caught or not, or `null` before one. + LastError, + /// The line of the script's code that reads it, counted from 1. + Line, + /// The running frames of the script's code, outermost first, one a line as `name:line`: the + /// global code is `[global]` and a function without a name `[anonymous]`. At most 64 frames + /// are listed, the innermost ones, after a line `…` when some are left out. + Stack, } enum Step { @@ -275,27 +349,127 @@ impl Interp { Ok(Value::Object(id)) } - /// Calls host function `f`: reads its arguments, runs it, and gives its result to the script. - pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value]) -> JsResult { + /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to + /// the script. + pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult { + let data = self.read_args(name, args, how)?; + // Only the script's own code, in a run that can pause, can wait for a result. + let can_wait = self.in_slice && self.reentry == 0; + self.can_wait.set(can_wait); + let result = f(data); + self.can_wait.set(false); + match result { + Ok(d) => self.write_data(d, 0, false), + Err(HostError::Wait) if can_wait => { + self.waiting = true; + self.pause.set(true); + Ok(Value::Undefined) + } + Err(HostError::Wait) => Err(Abrupt::Internal(format!("{name} waited for its result where the run cannot pause"))), + Err(e) => Err(self.host_error(e)?), + } + } + + /// Calls evaluator `f` ([`HostItem::Evaluator`]): reads its arguments, runs it, and runs the + /// source it gives as global code, as an indirect `eval` does, giving that code's completion + /// value. A result that is not a string is given to the script as it is. `end` is called once + /// the source has run, normally or not. `strict_writes` gives the source's + /// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. + pub(crate) fn call_evaluator( + &mut self, + f: &crate::heap::DataFn, + end: &Rc, + strict_writes: &Rc Option>, + name: &Rc, + args: &[Value], + ) -> JsResult { + let data = self.read_args(name, args, &ArgRead::Data)?; + let source = match f(data) { + Ok(Data::String(source)) => source, + Ok(d) => return self.write_data(d, 0, false), + Err(e) => return Err(self.host_error(e)?), + }; + let writes = strict_writes().unwrap_or_else(|| self.writes_mode()); + self.evaluated = self.evaluated.saturating_add(1); + let tag = std::mem::replace(&mut self.source_tag, self.evaluated); + let code = self.encode_source(&source).and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval)); + self.source_tag = tag; + let r = match code { + Ok(code) => self.run_global(code, true), + Err(e) => Err(self.compile_error_to_abrupt(e)), + }; + end(); + r + } + + /// The arguments of host function `name` as [`Data`], read as `how` says. + fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; + let args = match how { + ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), + _ => args, + }; let mut data = Vec::with_capacity(args.len()); + // A conversion can run the script's own `toString`, which may collect garbage. + let mark = self.temp_roots.len(); + if !matches!(how, ArgRead::Data) { + self.temp_roots.extend(args.iter().cloned()); + } + let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); - data.push(self.read_data(a, &mut reading)?); + let d = match how { + ArgRead::Data => self.read_data(a, &mut reading), + ArgRead::Text => self.read_text(a, &mut reading), + ArgRead::Each(list) => match list.get(i) { + Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), + Some(Arg::Bool) => Ok(Data::Bool(a.truthy())), + _ => self.read_text(a, &mut reading), + }, + }; + match d { + Ok(d) => data.push(d), + Err(e) => { + read = Err(e); + break; + } + } reading.path.pop(); } - match f(data) { - Ok(d) => self.write_data(d, 0, false), - Err(HostError::Abort(message)) => { + self.temp_roots.truncate(mark); + read?; + Ok(data) + } + + /// What host error `e` throws, or the limit it ends the run with. A function that waits + /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal + /// error. + fn host_error(&mut self, e: HostError) -> JsResult { + match e { + HostError::Wait => Ok(Abrupt::Internal("a host function waited for its result where the run cannot pause".into())), + HostError::Abort(message) => { self.host_abort = Some(message); - Err(Abrupt::Limit(LimitKind::Host)) + Ok(Abrupt::Limit(LimitKind::Host)) + } + HostError::Error(message) => self.throw_host(ErrorType::Error, &message), + HostError::Type(message) => self.throw_host(ErrorType::Type, &message), + HostError::Range(message) => self.throw_host(ErrorType::Range, &message), + HostError::Syntax(message) => self.throw_host(ErrorType::Syntax, &message), + HostError::Marked { error, mark } => { + let abrupt = self.host_error(*error)?; + self.thrown_mark = Some(mark); + Ok(abrupt) } - Err(HostError::Error(message)) => Err(self.throw_host(ErrorType::Error, &message)?), - Err(HostError::Type(message)) => Err(self.throw_host(ErrorType::Type, &message)?), - Err(HostError::Range(message)) => Err(self.throw_host(ErrorType::Range, &message)?), } } + /// `v` as the string `String(v)` gives, within the limits of a crossing. + fn read_text(&mut self, v: &Value, r: &mut Reading) -> JsResult { + let s = self.to_str(v)?; + self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?; + Ok(Data::String(s.to_rust_string())) + } + /// The exception for a host error, charged to the heap. fn throw_host(&mut self, t: ErrorType, message: &str) -> JsResult { let bytes = string_bytes(message.encode_utf16().count()); @@ -332,16 +506,46 @@ impl Interp { let full = format!("{path}.{name}"); let prop = match item { HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE }, - HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full)), flags: ENUMERABLE }, - HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full)), set: None, flags: ENUMERABLE }, + HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Data)), set: None, flags: ENUMERABLE }, + HostItem::Property { get, set } => Prop::Accessor { + get: Some(self.host_function(get, &full, ArgRead::Data)), + set: Some(self.host_function(set, &full, ArgRead::Data)), + flags: ENUMERABLE, + }, HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, + HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Data)), flags: ENUMERABLE }, + HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Text)), flags: ENUMERABLE }, + HostItem::Converted(list, f) => { + Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE } + } + HostItem::Evaluator { source, end, strict_writes } => { + let proto = self.intrinsics.function_proto; + let func = Func::Eval { f: source, end, strict_writes, name: full.into() }; + let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto))); + Prop::Data { value: Value::Object(f), flags: ENUMERABLE } + } + HostItem::Script(item) => match crate::builtins::extensions::getter(item) { + None => Prop::Data { value: Value::Object(self.global), flags: ENUMERABLE }, + Some((name, f)) => { + let get = crate::builtins::native(self, name, f, 0, crate::heap::NativeKind::Plain, false)?; + Prop::Accessor { get: Some(get), set: None, flags: ENUMERABLE } + } + }, }; self.define(o, key(&name), prop) } - fn host_function(&mut self, f: HostFunction, name: &str) -> ObjId { + /// Adds the global function `name` with its arguments converted as `args` says. A script may + /// replace or delete it, as it may a built-in function. + pub(crate) fn install_host_function(&mut self, name: &str, args: Vec, f: HostFunction) -> JsResult<()> { + let o = self.host_function(f, name, ArgRead::Each(args.into())); + let global = self.global; + self.define(global, key(name), Prop::Data { value: Value::Object(o), flags: crate::heap::HIDDEN }) + } + + fn host_function(&mut self, f: HostFunction, name: &str, read: ArgRead) -> ObjId { let proto = self.intrinsics.function_proto; - self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into() }), Some(proto))) + self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read }), Some(proto))) } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 85e178d879..48aaa96106 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -223,6 +223,25 @@ fn a_getter_is_read_each_time() { assert_eq!(r.run("host.n + host.n").unwrap(), JsValue::Number(3.0)); } +#[test] +fn a_text_function_takes_each_argument_as_string_gives_it() { + let mut r = realm(1_000_000); + let seen: Rc>> = Rc::default(); + let log = seen.clone(); + let f: HostFunction = Rc::new(move |args| { + log.borrow_mut().extend(args); + Ok(Data::Undefined) + }); + r.define_host_object("host", vec![("text".into(), HostItem::TextFunction(f))]).unwrap(); + r.run("host.text(1 / 0, NaN, undefined, null, 0.1, [1, [2]], {toString: function () { return 'own'; }}, function f() {}, '\\ud800x')").unwrap(); + let texts: Vec = seen.borrow().iter().map(|d| if let Data::String(s) = d { s.clone() } else { format!("{d:?}") }).collect(); + assert_eq!(texts[..7], ["Infinity", "NaN", "undefined", "null", "0.1", "1,2", "own"]); + assert!(texts[7].starts_with("function f()"), "{}", texts[7]); + assert_eq!(texts[8], "\u{fffd}x", "a lone surrogate becomes U+FFFD"); + let e = r.run("host.text({toString: function () { throw new Error('no text'); }})").unwrap_err(); + assert!(e.message.contains("no text"), "{}", e.message); +} + #[test] fn errors_from_the_host_can_be_caught_and_an_abort_cannot() { let mut r = realm(1_000_000); @@ -241,6 +260,59 @@ fn errors_from_the_host_can_be_caught_and_an_abort_cannot() { assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Limit(LimitKind::Host), "stopped by the host")); } +#[test] +fn a_marked_host_error_keeps_its_mark_only_while_no_catch_takes_it() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|a| { + let error = match a.first() { + Some(Data::String(k)) if k == "abort" => HostError::Abort("stopped".into()), + _ => HostError::Syntax("bad file".into()), + }; + Err(HostError::Marked { error: Box::new(error), mark: 7 }) + }); + r.define_host_object("host", vec![("f".into(), HostItem::Function(f))]).unwrap(); + let cases = [ + ("host.f();", Some(7)), + ("try { host.f(); } finally { var x = 1; }", Some(7)), + ("try { try { host.f(); } finally { 1; } } finally { 2; }", Some(7)), + ("function g() { host.f(); }\ng();", Some(7)), + ("try { host.f(); } finally { try { try { host.f(); } finally { 1; } } catch (e) {} }", Some(7)), + ("var saved; try { host.f(); } catch (e) { saved = e; }\nthrow saved;", None), + ("try { host.f(); } catch (e) { throw e; }", None), + ("try { try { host.f(); } finally { 1; } } catch (e) { throw e; }", None), + ("var m; try { host.f(); } catch (e) { m = e.message; }\nthrow new SyntaxError(m);", None), + ("do { try { host.f(); } finally { break; } } while (false);\nthrow new Error('other');", None), + ("try { host.f('abort'); } catch (e) { 'caught' }", Some(7)), + ]; + for (source, mark) in cases { + assert!(r.run(source).is_err(), "{source}"); + assert_eq!(r.error_mark(), mark, "{source}"); + } + assert_eq!(r.run("1").unwrap(), JsValue::Number(1.0)); + assert_eq!(r.error_mark(), None, "a later run that ends normally has no mark"); +} + +/// Marked errors that `finally` blocks discard with `return`, `break` or `continue` are collected +/// with the rest of the garbage, so a run that discards many of them stays within its heap. +#[test] +fn marked_errors_a_finally_block_discards_are_collected() { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 200_000_000, heap_bytes: 1 << 20, ..Limits::default() }); + let f: HostFunction = Rc::new(|_| Err(HostError::Marked { error: Box::new(HostError::Syntax("bad file".into())), mark: 7 })); + r.define_host_object("host", vec![("f".into(), HostItem::Function(f))]).unwrap(); + let cases = [ + "function d() { try { host.f(); } finally { return; } }\nfor (var i = 0; i < 20000; i++) d();", + "for (var i = 0; i < 20000; i++) { try { host.f(); } finally { continue; } }", + "for (var i = 0; i < 20000; i++) { do { try { host.f(); } finally { break; } } while (false); }", + ]; + for source in cases { + r.run(source).unwrap_or_else(|e| panic!("{source}: {e:?}")); + assert_eq!(r.error_mark(), None, "{source}"); + } + assert!(r.run("try { host.f(); } finally { 1; }").is_err()); + assert_eq!(r.error_mark(), Some(7)); +} + #[test] fn an_error_says_where_in_the_source_it_was_raised() { let mut r = realm(1_000_000); @@ -258,6 +330,84 @@ fn advancing_without_a_run_is_an_error() { assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Internal, "no run to advance")); } +/// A realm with the global `ask(question)`, which waits for its answer where it can and throws an +/// `Error` where it cannot. → how many times it was called. +fn with_ask(r: &mut Realm) -> Rc> { + let calls: Rc> = Rc::default(); + let (count, can_wait) = (calls.clone(), r.wait_flag()); + let f: HostFunction = Rc::new(move |_| { + count.set(count.get() + 1); + if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) } + }); + r.define_host_function("ask", vec![Arg::Text], f).unwrap(); + calls +} + +#[test] +fn a_waiting_call_pauses_at_the_call_and_takes_its_answer_once() { + let mut r = realm(1_000_000); + let calls = with_ask(&mut r); + r.start("var a = ask('first'); var b = ask('second'); a + '|' + b").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + let fuel = r.fuel_left(); + let e = r.advance(1_000).unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Internal, "the run waits for a host function's result")); + assert_eq!(r.fuel_left(), fuel, "no fuel is spent while the call waits"); + r.answer(Data::String("one".into())).unwrap(); + assert!(!r.waits()); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(Data::Null).unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("one|null".into())); + assert_eq!(calls.get(), 2, "each call ran once"); + let e = r.answer(Data::Null).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Internal); +} + +#[test] +fn only_the_scripts_own_code_in_a_resumable_run_can_wait() { + let mut r = realm(1_000_000); + with_ask(&mut r); + let caught = "var out = []; [1].forEach(function () { try { ask('x'); } catch (e) { out.push(e.message); } }); \ + var o = {}; Object.defineProperty(o, 'g', {get: function () { try { ask('y'); } catch (e) { out.push(e.message); } }}); o.g; \ + try { String({toString: function () { return ask('z'); }}); } catch (e) { out.push(e.message); } out.join()"; + r.start(caught).unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("cannot wait here,cannot wait here,cannot wait here".into())); + let e = r.run("ask('q')").unwrap_err(); + assert!(e.message.contains("cannot wait here"), "a run that cannot pause cannot wait: {}", e.message); + r.start("var f = ask; ask.call(null, 'q'); f.apply(null, ['r'])").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits(), "call and apply from the script's own code wait"); +} + +#[test] +fn a_host_function_that_waits_where_it_cannot_ends_the_run() { + let mut r = realm(1_000_000); + let f: HostFunction = Rc::new(|_| Err(HostError::Wait)); + r.define_host_function("ask", vec![], f).unwrap(); + let e = r.run("try { ask(); } catch (e) { 'caught' }").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Internal); +} + +#[test] +fn a_converted_function_reads_each_argument_as_its_list_says() { + let mut r = realm(1_000_000); + let seen: Rc>>> = Rc::default(); + let log = seen.clone(); + let f: HostFunction = Rc::new(move |args| { + log.borrow_mut().push(args); + Ok(Data::Undefined) + }); + r.define_host_function("conv", vec![Arg::Text, Arg::TextOrUndefined, Arg::Bool], f).unwrap(); + r.run("conv(42, undefined, 'x', function () {}); conv(undefined, null, 0); conv({toString: function () { return 'own'; }}); conv()").unwrap(); + let s = |t: &str| Data::String(t.into()); + let want = vec![vec![s("42"), Data::Undefined, Data::Bool(true)], vec![s("undefined"), s("null"), Data::Bool(false)], vec![s("own")], vec![]]; + assert_eq!(*seen.borrow(), want, "arguments past the list are not read"); + let out = r.run("var a = typeof conv; conv = 1; a + ' ' + conv").unwrap(); + assert_eq!(out, JsValue::String("function 1".into()), "a script may replace the function"); +} + proptest::proptest! { /// A slice size does not change what a script computes. #[test] diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f868149492..be5760e8f9 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -164,6 +164,13 @@ pub(crate) struct Interp { pub(crate) throw_site: Option, /// The last exception a run did not catch. pub(crate) last_thrown: Value, + /// The last `Error` object thrown in this run, caught or not, or `null` (`$.error`). + pub(crate) last_error: Value, + /// An exception passed on rather than thrown again: one a `finally` block restores, or one + /// leaving a nested run. [`Interp::unwind`] does not make it [`Interp::last_error`] again. + pub(crate) passing: Value, + /// The locale `localize` and `Object.prototype.toString` read. + pub(crate) localization: Rc, /// The state of `Math.random`'s generator. pub(crate) random: u64, /// The objects `Array.prototype.join` and `toLocaleString` are joining, innermost last: a @@ -181,10 +188,34 @@ pub(crate) struct Interp { pub(crate) held: Rc, /// Set by the host to end the current slice of a resumable run at the next safe point. pub(crate) pause: Rc>, + /// The outermost loop of a resumable run is running ([`crate::Realm::advance`]). + pub(crate) in_slice: bool, + /// True while a host function runs where it may wait ([`crate::HostError::Wait`]). + pub(crate) can_wait: Rc>, + /// A host function's call waits for its result: the value on top of the stack stands in for it. + pub(crate) waiting: bool, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. pub(crate) data_limits: crate::DataLimits, + /// The tag the source compiled next gets ([`crate::Realm::error_source`]). + pub(crate) source_tag: u32, + /// The sources [`crate::HostItem::Evaluator`] functions have given in this realm. + pub(crate) evaluated: u32, + /// The tag of the source the last run's error was raised in. + pub(crate) error_tag: u32, + /// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is + /// propagating. + pub(crate) thrown_mark: Option, + /// The marked exceptions `finally` blocks are running for, innermost last, each with its mark, + /// which the block's end throws it on with, and the stack slot that holds it while the block + /// runs. An entry whose slot no longer holds its exception belongs to a block that `break`, + /// `continue` or `return` left, and [`Self::drop_left_finally_marks`] removes it. + pub(crate) finally_marks: Vec<(ObjId, u32, usize)>, + /// The mark of the host error the last run ended with. + pub(crate) error_mark: Option, + /// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs. + pub(crate) strict_writes: bool, } /// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's @@ -367,6 +398,9 @@ impl Interp { source_units: 0, throw_site: None, last_thrown: Value::Undefined, + last_error: Value::Null, + passing: Value::Undefined, + localization: Rc::default(), random: random_seed(), join_stack: Vec::new(), held_bytes: 0, @@ -374,8 +408,18 @@ impl Interp { date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), pause: Rc::default(), + in_slice: false, + can_wait: Rc::default(), + waiting: false, host_abort: None, data_limits: crate::DataLimits::default(), + source_tag: crate::realm::UNKNOWN_SOURCE, + evaluated: 0, + error_tag: crate::realm::UNKNOWN_SOURCE, + thrown_mark: None, + finally_marks: Vec::new(), + error_mark: None, + strict_writes: false, }; crate::builtins::install(&mut interp); interp.fuel = limits.fuel; @@ -414,7 +458,7 @@ impl Interp { // ---- the operand stack ---- - fn push(&mut self, v: Value) -> JsResult<()> { + pub(crate) fn push(&mut self, v: Value) -> JsResult<()> { self.stack.push(v); Ok(()) } @@ -529,11 +573,22 @@ impl Interp { Ok(()) } + /// Removes the [`Self::finally_marks`] entries of `finally` blocks that `break`, `continue` or + /// `return` left: those whose stack slot no longer holds their exception. + fn drop_left_finally_marks(&mut self) { + let stack = &self.stack; + self.finally_marks.retain(|&(id, _, slot)| matches!(stack.get(slot), Some(Value::Object(o)) if *o == id)); + } + pub(crate) fn collect_garbage(&mut self) { + self.drop_left_finally_marks(); let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); roots.values.push(&self.last_thrown); + roots.values.push(&self.last_error); + roots.values.push(&self.passing); + roots.objects.extend(self.finally_marks.iter().map(|&(id, _, _)| id)); for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); @@ -619,9 +674,18 @@ impl Interp { /// boundary frame. Returns the exception when no handler takes it before the boundary frame. fn unwind(&mut self, v: Value) -> JsResult<()> { self.note_site(); + let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b); + if !passed + && let Value::Object(o) = v + && self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error)) + { + self.last_error = v.clone(); + } loop { let Some(frame) = self.frames.last_mut() else { return Err(Abrupt::Throw(v)) }; if let Some(h) = frame.code.handler(frame.pc.saturating_sub(1)) { + // A catch clause starts with `PushCatch`; every other handler is a `finally` block's. + let caught = matches!(frame.code.ops.get(h.target as usize), Some(Op::PushCatch(_))); let target_len = frame.base + h.depth as usize; while frame.env_depth > h.env_depth { let outer = self.heap.env(frame.env).and_then(Env::outer); @@ -634,6 +698,10 @@ impl Interp { return internal("handler stack deeper than the stack"); } self.stack.truncate(target_len); + self.drop_left_finally_marks(); + if let (Some(mark), false, Value::Object(id)) = (self.thrown_mark.take(), caught, &v) { + self.finally_marks.push((*id, mark, target_len)); + } self.stack.push(v); self.throw_site = None; return Ok(()); @@ -641,11 +709,18 @@ impl Interp { let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); if frame.boundary { + self.passing = v.clone(); return Err(Abrupt::Throw(v)); } } } + /// Each running frame of script code, outermost first: its code, the index of its next + /// instruction, and whether it runs a function (not global or eval code). + pub(crate) fn script_frames(&self) -> impl Iterator, usize, bool)> { + self.frames.iter().map(|f| (&f.code, f.pc, f.callee.is_some())) + } + fn abort_to_boundary(&mut self) { while let Some(frame) = self.frames.pop() { self.stack.truncate(frame.base); @@ -682,6 +757,18 @@ impl Interp { self.frames.last().is_some_and(|f| f.code.strict) } + /// Does a property write the running code makes throw when it cannot be made? It does in + /// strict mode code and in code from a source with [`crate::bytecode::Source::strict_writes`]. + fn strict_writes(&self) -> bool { + self.frames.last().is_some_and(|f| f.code.strict || f.code.source.strict_writes) + } + + /// [`crate::bytecode::Source::strict_writes`] for source compiled now: the running code's, + /// or the realm's between runs. + pub(crate) fn writes_mode(&self) -> bool { + self.frames.last().map_or(self.strict_writes, |f| f.code.source.strict_writes) + } + fn exec(&mut self, op: Op) -> JsResult<()> { match op { Op::Undefined => self.push(Value::Undefined), @@ -735,7 +822,10 @@ impl Interp { Op::Jump(t) => self.jump_to(t), Op::JumpIfFalse(t) | Op::JumpIfTrue(t) => self.op_branch(t, matches!(op, Op::JumpIfTrue(_)), false), Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) => self.op_branch(t, matches!(op, Op::JumpIfTrueKeep(_)), true), - Op::Throw => Err(Abrupt::Throw(self.pop()?)), + Op::Throw => { + self.thrown_mark = None; + Err(Abrupt::Throw(self.pop()?)) + } Op::ThrowReferenceError(i) => self.op_throw_reference_error(i), Op::EndFinally(t) => self.op_end_finally(t), Op::NewObject => self.op_new_object(), @@ -817,7 +907,15 @@ impl Interp { return self.pop().map(drop); } if kind == 1.0 { - return Err(Abrupt::Throw(self.pop()?)); + let v = self.pop()?; + self.passing = v.clone(); + if let Value::Object(o) = v + && let Some(i) = self.finally_marks.iter().rposition(|&(id, _, _)| id == o) + { + self.thrown_mark = self.finally_marks.get(i).map(|&(_, mark, _)| mark); + self.finally_marks.truncate(i); + } + return Err(Abrupt::Throw(v)); } let k = (kind - 2.0) as usize; let target = self.frame()?.code.finally_tables.get(table as usize).and_then(|t| t.get(k)).copied(); @@ -900,11 +998,14 @@ impl Interp { _ => Ok(()), } } - Resolved::Obj { object, .. } => self.put(object, name.clone(), v, strict), + Resolved::Obj { object, .. } => { + let throw = self.strict_writes(); + self.put(object, name.clone(), v, throw) + } Resolved::Unresolved if strict => Err(self.not_defined(name)), Resolved::Unresolved => { - let global = self.global; - self.put(global, name.clone(), v, false) + let (global, throw) = (self.global, self.strict_writes()); + self.put(global, name.clone(), v, throw) } } } @@ -1435,7 +1536,10 @@ impl Interp { fn put_value(&mut self, base: &Value, k: Key, v: Value) -> JsResult<()> { let strict = self.strict(); match base { - Value::Object(o) => self.put(*o, k, v, strict), + Value::Object(o) => { + let throw = self.strict_writes(); + self.put(*o, k, v, throw) + } Value::Undefined | Value::Null => { let message = format!( "cannot set property '{}' of {}", @@ -1846,10 +1950,13 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } - Func::Data { f, name } => { + Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. - return Ok(Prepared::Done(self.call_data(&f, &name, &args)?)); + return Ok(Prepared::Done(self.call_data(&f, &name, &args, &read)?)); + } + Func::Eval { f, end, strict_writes, name } => { + return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?)); } Func::Host { f: host, .. } => { let js_args: Vec = args.iter().map(|v| self.to_js_value(v)).collect(); @@ -2119,11 +2226,17 @@ impl Interp { /// Parses and compiles source for eval code or a script, counting it against the source /// limit. pub(crate) fn compile_source(&mut self, units: &[u16], strict: bool, kind: CodeKind) -> Result, CompileError> { + let writes = self.writes_mode(); + self.compile_source_writes(units, strict, writes, kind) + } + + /// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`. + pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result, CompileError> { self.source_units = self.source_units.saturating_add(units.len()); let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len())); let options = Options { strict, max_source_units: remaining, ..self.options.clone() }; let program = crate::parse_utf16(units, &options).map_err(CompileError::Syntax)?; - let source = Rc::new(Source { lines: program.lines.clone(), text: units.into() }); + let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes }); compile_program(&program, &source, kind).map_err(|e| match e { CompileFail::Syntax(s) => CompileError::Syntax(s), CompileFail::Internal(m) => CompileError::Internal(m), diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 03d9e6639f..d2a12b5fb0 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -691,6 +691,61 @@ fn a_strict_realm_runs_scripts_as_strict_mode_code() { assert_eq!(realm.run("(function () { return typeof this; })()"), Ok(JsValue::String("object".into()))); } +#[test] +fn strict_writes_are_separate_from_es5_strict() { + let setup = "var ro = {}; Object.defineProperty(ro, 'x', {value: 1}); \ + var getter = {get g() { return 1; }}; var shut = Object.preventExtensions({a: 1}); var open = {};"; + let mut realm = Realm::new(); + realm.set_strict_writes(true); + realm.run(setup).unwrap(); + for (src, why) in [ + ("ro.x = 2", "cannot assign to property 'x': it is read-only"), + ("ro['x'] += 1", "cannot assign to property 'x': it is read-only"), + ("ro.x++", "cannot assign to property 'x': it is read-only"), + ("getter.g = 2", "cannot assign to property 'g': it has only a getter"), + ("shut.b = 2", "cannot assign to property 'b': the object is not extensible"), + ("Object.create(ro).x = 2", "cannot assign to property 'x': it is read-only"), + ("NaN = 1", "cannot assign to property 'NaN': it is read-only"), + ("(function () { ro.x = 2; })()", "cannot assign to property 'x': it is read-only"), + ("eval('ro.x = 2')", "cannot assign to property 'x': it is read-only"), + ("(0, eval)('ro.x = 2')", "cannot assign to property 'x': it is read-only"), + ("Function('ro.x = 2')()", "cannot assign to property 'x': it is read-only"), + ] { + let e = realm.run(src).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Thrown, "{src}"); + assert!(e.message.contains("TypeError") && e.message.contains(why), "{src}: {}", e.message); + } + // Writes that can be made, and the rest of strict mode, are as before. + assert_eq!(realm.run("open.n = 1; shut.a = 5; open.n + shut.a"), Ok(JsValue::Number(6.0))); + assert_eq!(realm.run("with ({w: 2}) { w } "), Ok(JsValue::Number(2.0))); + assert_eq!(realm.run("(function (a, a) { return a; })(1, 2)"), Ok(JsValue::Number(2.0))); + assert_eq!(realm.run("010"), Ok(JsValue::Number(8.0))); + assert_eq!(realm.run("undeclared = 3; undeclared"), Ok(JsValue::Number(3.0))); + assert_eq!(realm.run("(function () { return typeof this; })()"), Ok(JsValue::String("object".into()))); + assert_eq!(realm.run("delete Object.prototype"), Ok(JsValue::Bool(false))); + assert_eq!(realm.run("'abc'.length = 1; 'abc'.extra = 1; 1"), Ok(JsValue::Number(1.0)), "a primitive's properties as in sloppy mode"); + // 'use strict' keeps all of ES5 strict mode. + assert_eq!(realm.run("'use strict'; with ({}) {}").map_err(|e| e.kind), Err(RunErrorKind::Syntax)); + assert_eq!(realm.run("'use strict'; delete Object.prototype").map_err(|e| e.kind), Err(RunErrorKind::Thrown)); + // Off, the same writes are ignored, as in sloppy mode code. + realm.set_strict_writes(false); + assert_eq!(realm.run("ro.x = 2; getter.g = 2; shut.b = 2; NaN = 1; ro.x + getter.g + String(shut.b)"), Ok(JsValue::String("2undefined".into()))); + // A function compiled with the writes on keeps them when called from code without. + let mut realm = Realm::new(); + realm.set_strict_writes(true); + realm.run(&format!("{setup} function w() {{ ro.x = 2; }}")).unwrap(); + realm.set_strict_writes(false); + assert!(realm.run("w()").unwrap_err().message.contains("it is read-only")); + assert_eq!(realm.run("ro.x = 3; ro.x"), Ok(JsValue::Number(1.0))); + // An undeclared name added to a global object that is not extensible. + let mut realm = Realm::new(); + realm.set_strict_writes(true); + let e = realm.run("Object.preventExtensions(this); newName = 1").unwrap_err(); + assert!(e.message.contains("cannot assign to property 'newName': the object is not extensible"), "{}", e.message); + let mut realm = Realm::new(); + assert_eq!(realm.run("Object.preventExtensions(this); newName = 1; typeof newName"), Ok(JsValue::String("undefined".into()))); +} + #[test] fn an_apply_that_throws_while_reading_its_arguments_keeps_nothing_alive() { // Each call reads a fresh array at index 0 before index 1 throws; the arrays must not stay @@ -774,7 +829,7 @@ fn deep_nesting_compiles_on_a_small_stack() { // ---- the verifier ---- fn code(ops: Vec) -> Code { - let source = Rc::new(Source { lines: crate::LineTable::new(&[]), text: Rc::from(Vec::::new()) }); + let source = Rc::new(Source { lines: crate::LineTable::new(&[]), text: Rc::from(Vec::::new()), tag: 0, strict_writes: false }); Code { positions: vec![0; ops.len()], ops, @@ -788,6 +843,7 @@ fn code(ops: Vec) -> Code { max_stack: 0, strict: false, self_name: None, + decl_name: None, params: Vec::new(), vars: Vec::new(), fun_decls: Vec::new(), diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a95a4b8847..bfb5d5c0cb 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -65,11 +65,12 @@ pub use ast::{ AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LogicalOp, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl, }; +pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; -pub use host::{Data, DataLimits, HostError, HostFunction, HostItem}; +pub use host::{Arg, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; -pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind}; +pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, UNKNOWN_SOURCE}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -187,6 +188,8 @@ impl LineTable { #[cfg(test)] mod builtins_tests; #[cfg(test)] +mod extension_tests; +#[cfg(test)] mod host_tests; #[cfg(test)] mod interp_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index a28b150a52..1c2bb6ecf1 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -58,6 +58,10 @@ pub enum LimitKind { Host, } +/// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an +/// evaluator's: code that `eval` or `Function` compiled, or an error with no place. +pub const UNKNOWN_SOURCE: u32 = u32::MAX; + /// The fuel [`Realm::advance`] lets a slice spend, past the slice it was asked for, in a nested run /// it cannot pause. pub const MAX_UNBROKEN_FUEL: u64 = 200_000_000; @@ -170,6 +174,14 @@ impl Realm { self.unbroken_fuel = fuel; } + /// With `on`, the scripts run next (and the code they define and evaluate) throw a + /// `TypeError` when they assign to a read-only or getter-only property or add a property to + /// an object that is not extensible, as strict mode code does, without the rest of strict + /// mode. Off by default. + pub fn set_strict_writes(&mut self, on: bool) { + self.interp.strict_writes = on; + } + pub fn limits(&self) -> &Limits { &self.interp.limits } @@ -217,11 +229,23 @@ impl Realm { interp.source_units = 0; interp.throw_site = None; interp.last_thrown = Value::Undefined; + interp.last_error = Value::Null; interp.host_abort = None; + interp.waiting = false; + interp.error_tag = UNKNOWN_SOURCE; + interp.thrown_mark = None; + interp.finally_marks.clear(); + interp.error_mark = None; let strict = interp.options.strict; - match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) { + interp.source_tag = 0; + let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)); + interp.source_tag = UNKNOWN_SOURCE; + match code { Ok(code) => Ok(code), - Err(CompileError::Syntax(e)) => Err(e.into()), + Err(CompileError::Syntax(e)) => { + interp.error_tag = 0; + Err(e.into()) + } Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), } } @@ -229,11 +253,17 @@ impl Realm { /// The end of a run: its completion value or error, with the interpreter's stacks emptied. fn outcome(&mut self, result: Result) -> Result { let interp = &mut self.interp; - let (line, column) = interp.throw_site.take().map_or((0, 0), |(code, pc)| code.line_column(pc)); + let site = interp.throw_site.take(); + interp.error_tag = site.as_ref().map_or(UNKNOWN_SOURCE, |(code, _)| code.source.tag); + let (line, column) = site.map_or((0, 0), |(code, pc)| code.line_column(pc)); + interp.error_mark = interp.thrown_mark.take().filter(|_| matches!(result, Err(Abrupt::Throw(_) | Abrupt::Limit(LimitKind::Host)))); + interp.finally_marks.clear(); interp.stack.clear(); interp.frames.clear(); interp.temp_roots.clear(); interp.join_stack.clear(); + interp.waiting = false; + interp.passing = Value::Undefined; match result { Ok(v) => Ok(interp.to_js_value(&v)), Err(Abrupt::Throw(v)) => { @@ -263,16 +293,22 @@ impl Realm { /// instruction), and pauses where it can resume: between two instructions of the script's own /// code. A getter, a built-in's callback or another nested run has native frames under it, so /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned - /// [`Progress::Done`] or an error, the run is over. + /// [`Progress::Done`] or an error, the run is over. While a host function's call waits for its + /// result ([`Realm::waits`]), the run does not advance: this gives an internal error. pub fn advance(&mut self, slice: u64) -> Result { let interp = &mut self.interp; if interp.frames.is_empty() { return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0 }); } + if interp.waiting { + return Err(RunError { kind: RunErrorKind::Internal, message: "the run waits for a host function's result".into(), line: 0, column: 0 }); + } let total = interp.fuel; let cap = slice.saturating_add(self.unbroken_fuel).min(total); interp.fuel = cap; + interp.in_slice = true; let r = interp.execute_slice(cap - slice.min(cap)); + interp.in_slice = false; let used = cap - interp.fuel; interp.fuel = total - used; match r { @@ -294,11 +330,56 @@ impl Realm { self.interp.pause.clone() } + /// The flag that is set while a host function runs where it may return + /// [`crate::HostError::Wait`]: called by the script's own code in a run [`Realm::advance`] + /// carries on, and not from a getter, a conversion or a built-in's callback. + pub fn wait_flag(&self) -> std::rc::Rc> { + self.interp.can_wait.clone() + } + + /// Does a host function's call wait for the result [`Realm::answer`] gives it? + pub fn waits(&self) -> bool { + self.interp.waiting + } + + /// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next + /// [`Realm::advance`] goes on from there. A result past the heap limit ends the run with that + /// limit, and with no call waiting this gives an internal error. + pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { + let interp = &mut self.interp; + if !interp.waiting { + return Err(RunError { kind: RunErrorKind::Internal, message: "no host function waits for a result".into(), line: 0, column: 0 }); + } + interp.waiting = false; + // The value on top of the stack stood in for the result. + let r = interp.write_data(d, 0, false).and_then(|v| { + interp.stack.pop(); + interp.push(v) + }); + match r { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Has this realm stop when `interrupt` is set, in place of its own flag. pub fn share_interrupt(&mut self, interrupt: &Interrupt) { self.interp.interrupt = interrupt.0.clone(); } + /// Which source the last error's `line` and `column` are in: 0 for the script given to + /// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a + /// [`crate::HostItem::Evaluator`] gave in this realm, and [`UNKNOWN_SOURCE`] otherwise. + pub fn error_source(&self) -> u32 { + self.interp.error_tag + } + + /// The mark of the host error ([`crate::HostError::Marked`]) the last run ended with, when no + /// `catch` clause took that error's exception on its way out; `None` otherwise. + pub fn error_mark(&self) -> Option { + self.interp.error_mark + } + /// Fuel the run has left. pub fn fuel_left(&self) -> u64 { self.interp.fuel @@ -319,6 +400,32 @@ impl Realm { } } + /// Adds the script extensions: the global `localize(object, ...values)`, which gives a + /// localization object's text for the locale of [`Realm::localization`], the global + /// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text, + /// and the localized `Object.prototype.toString` while [`crate::Localization::enabled`]. + pub fn add_script_extensions(&mut self) -> Result<(), RunError> { + match crate::builtins::extensions::install(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + + /// Defines the global function `name`, whose arguments arrive converted as `args` says + /// ([`crate::HostItem::Converted`]). Unlike a host object, a script may replace or delete it, as + /// it may a built-in function. + pub fn define_host_function(&mut self, name: &str, args: Vec, f: crate::HostFunction) -> Result<(), RunError> { + match self.interp.install_host_function(name, args, f) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + + /// The locale `localize` reads, which the host's functions may change during a run. + pub fn localization(&self) -> std::rc::Rc { + self.interp.localization.clone() + } + /// Defines the global variable `name` holding the exception the last run did not catch /// (`undefined` if there was none). pub fn bind_last_thrown(&mut self, name: &str) { diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 687fcb1566..38f22689a8 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -375,6 +375,7 @@ fn read_opened( show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let page_layer = |b: &mut Builder<'_>, art: Vec>, shown: bool| { let name = if shown { format!("Page {}", number + 1) } else { format!("Page {} (unsorted)", number + 1) }; diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index a90d6a33be..b7163c0e58 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -633,7 +633,7 @@ impl TextLine { let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum(); let size = self.at.size; if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 { - let (tracking, spaces) = spacing(&laid, &[], length - natural, chars, size); + let (tracking, spaces) = spacing(&laid, &[], length - natural, chars, size, spacing_em(&t, size)); t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces); } } @@ -675,7 +675,7 @@ impl TextLine { // left in the file's order. let total: usize = t.runs.iter().map(|r| r.text.len()).sum(); let gaps: Vec<(usize, f64)> = if t.para.direction.is_none() { gaps.into_iter().filter(|(b, _)| *b < total).collect() } else { vec![] }; - let (tracking, spaces) = spacing(&laid, &gaps, length - natural, chars, size); + let (tracking, spaces) = spacing(&laid, &gaps, length - natural, chars, size, spacing_em(&t, size)); t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces); // Tracked: laid out again for its bounds. bounds = vectorcraft_text::layout(db, &t).bounds; @@ -701,16 +701,19 @@ fn pens(laid: &TextLayout, chars: &[usize]) -> Vec> { } /// `t`'s runs with kerning `kern` and each character's tracking from `own` (points, one per -/// character, in thousandths of each run's em), characters alike kept in one run. +/// character, in thousandths of each run's em as its Horizontal Scale draws it), characters alike +/// kept in one run. fn restyled(t: &TextObject, kern: Option, own: &[f64]) -> Vec { let mut out: Vec = Vec::with_capacity(t.runs.len()); // The run of `t` the last character came from. let mut from = None; let mut k = 0; for (i, r) in t.runs.iter().enumerate() { - let size = r.style.size.max(1e-3); + // A PDF scales its character spacing by its horizontal scaling (ISO 32000-1 §9.4.4), as + // layout scales tracking ([`vectorcraft_text::spacing_scale`]). + let em = (r.style.size * vectorcraft_text::spacing_scale(&r.style, t.vertical)).max(1e-3); for c in r.text.chars() { - let tracking = own.get(k).map_or(0.0, |e| (e / size * 1000.0).clamp(-1000.0, 10000.0)); + let tracking = own.get(k).map_or(0.0, |e| (e / em * 1000.0).clamp(-1000.0, 10000.0)); k += 1; // Hundredths of a thousandth of an em: no drift along a line, no noise in the panels. let tracking = (tracking * 100.0).round() / 100.0; @@ -971,8 +974,9 @@ pub(crate) fn median(mut v: Vec) -> Option { /// as `laid`, `extra` points longer, as the file set it: the same after every character, except /// the spaces read from gaps or drawn between glyphs (`gaps`: byte offset, gap in points) where /// that would put the glyphs after them more than a tenth of an em off (a barcode's digits, set in -/// groups apart). Those take their own tracking, given with their byte offsets. -fn spacing(laid: &TextLayout, gaps: &[(usize, f64)], extra: f64, chars: usize, size: f64) -> (f64, Vec<(usize, f64)>) { +/// groups apart). Those take their own tracking, given with their byte offsets. `em`: the em the +/// tracking is thousandths of, in points ([`spacing_em`]). +fn spacing(laid: &TextLayout, gaps: &[(usize, f64)], extra: f64, chars: usize, size: f64, em: f64) -> (f64, Vec<(usize, f64)>) { let pairs = chars.saturating_sub(1).max(1) as f64; // The advance of the first glyph laid out at each byte offset. let space: HashMap = laid.glyphs.iter().rev().map(|g| (g.byte, g.advance)).collect(); @@ -995,8 +999,15 @@ fn spacing(laid: &TextLayout, gaps: &[(usize, f64)], extra: f64, chars: usize, s tracking = if rest >= 1.0 { (extra - own.iter().map(|(_, need)| need).sum::()) / rest } else { 0.0 }; } own.sort_by_key(|(b, _)| *b); - let em = |pts: f64| (pts / size * 1000.0).clamp(-1000.0, 10000.0).round(); - (em(tracking), own.into_iter().map(|(b, need)| (b, em(need - tracking))).collect()) + let thousandths = |pts: f64| (pts / em.max(1e-3) * 1000.0).clamp(-1000.0, 10000.0).round(); + (thousandths(tracking), own.into_iter().map(|(b, need)| (b, thousandths(need - tracking))).collect()) +} + +/// The em the tracking of type `t` set `size` points is thousandths of, in points: the size as its +/// first run's Horizontal Scale draws it in horizontal type ([`vectorcraft_text::spacing_scale`]), +/// as a PDF scales its character spacing by its horizontal scaling (ISO 32000-1 §9.4.4). +fn spacing_em(t: &TextObject, size: f64) -> f64 { + size * t.runs.first().map_or(1.0, |r| vectorcraft_text::spacing_scale(&r.style, t.vertical)) } /// `runs` with tracking `tracking`, and each space at a byte offset of `spaces` (in order) a run diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 365b653890..af744437d5 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -131,6 +131,7 @@ fn one_page_per_artboard_with_sizes() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); d.artboards.push(Artboard { id: 3, @@ -142,6 +143,7 @@ fn one_page_per_artboard_with_sizes() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let bytes = export(&d, &PdfOptions::default()).unwrap(); let pdf = craft_pdf::syntax::Pdf::new(bytes).unwrap(); @@ -162,6 +164,7 @@ fn artboard_range_and_bad_index() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); let bytes = export(&d, &PdfOptions { artboards: Some(vec![1]), ..Default::default() }).unwrap(); let pdf = craft_pdf::syntax::Pdf::new(bytes).unwrap(); @@ -893,6 +896,7 @@ fn import_max_pages_and_multi_page() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); add(&mut d, rect_node(Rect::new(10.0, 10.0, 50.0, 50.0), Color::BLACK)); add(&mut d, rect_node(Rect::new(310.0, 10.0, 350.0, 50.0), Color::BLACK)); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index daf2bab071..2f59563e70 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -33,6 +33,7 @@ fn artboard(id: u32, x: f64) -> Artboard { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, } } diff --git a/crates/pdf/src/tests/text_placement.rs b/crates/pdf/src/tests/text_placement.rs index 45bf5e4098..f275def4dd 100644 --- a/crates/pdf/src/tests/text_placement.rs +++ b/crates/pdf/src/tests/text_placement.rs @@ -286,6 +286,21 @@ fn spacing_and_scaling_keep_each_glyph_where_the_file_put_it() { } } +/// Character spacing in horizontally scaled type: a PDF scales `Tc` by its horizontal scaling +/// (ISO 32000-1 §9.4.4), as layout scales tracking by the Horizontal Scale +/// (`vectorcraft_text::spacing_scale`), so the type's tracking is the file's `Tc` in thousandths of +/// its size: 1.5 pt at 16 pt is 93.75, set 80% wide. +#[test] +fn character_spacing_in_horizontally_scaled_type_is_the_files_tc() { + let bytes = page("BT /F1 16 Tf 1.5 Tc 80 Tz 20 50 Td (Spaced and narrow) Tj ET", ""); + let t = texts(&open_as(&bytes, TextAs::Text)); + assert_eq!(t.len(), 1); + assert!(t[0].runs.iter().all(|r| (r.style.h_scale - 80.0).abs() < 1e-6), "{:?}", t[0].runs); + let tracking: Vec = t[0].runs.iter().map(|r| r.style.tracking).collect(); + assert!(tracking.iter().all(|v| (v - 93.75).abs() < 0.5), "{tracking:?}"); + assert!(displacement(&bytes) < 0.02); +} + /// Word spacing stays on the spaces, as tracking of their own; evenly spaced letters keep one /// tracking value for the line, and a file that didn't kern opens with kerning off. #[test] diff --git a/crates/pdf/src/tests/webview.rs b/crates/pdf/src/tests/webview.rs index 9a4659ddce..a40db425e7 100644 --- a/crates/pdf/src/tests/webview.rs +++ b/crates/pdf/src/tests/webview.rs @@ -31,6 +31,7 @@ fn doc(n: usize, image: bool, on_first: bool) -> Document { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); } let mut png = vec![]; diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 7c18f2c066..ef21a57ef4 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -22,6 +22,10 @@ craft-vectorcraft-format = { workspace = true } sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } wasmi = { workspace = true } +# The monotonic clock of run deadlines and the first-view budget: `std::time::Instant` on the +# desktop, the page's `performance.now()` in the web build. It is MIT OR Apache-2.0 and already in +# the build through eframe. +web-time = "1" [dev-dependencies] wat = { workspace = true } diff --git a/crates/plugins/src/deferred.rs b/crates/plugins/src/deferred.rs new file mode 100644 index 0000000000..1645dd55e0 --- /dev/null +++ b/crates/plugins/src/deferred.rs @@ -0,0 +1,727 @@ +//! Live-effect plug-ins while a document opens: the plug-in effects drawn for its first view share +//! a time budget of [`OPENING_BUDGET_MS`], and a stage that is not run for want of time, or that +//! gives no result, is deferred: it draws its input art and is listed with the reason +//! ([`Deferrals::list`]) until it runs again. +//! +//! One [`Deferrals`] belongs to each open document. Drawing that document on screen runs inside +//! [`Deferrals::view`], which applies its budget and its deferred stages to the plug-in effects +//! evaluated on that thread ([`crate::effect`]): +//! +//! - until [`Deferrals::first_view_done`], every run takes the lesser of its per-call limit and +//! what is left of the budget, no run starts once the budget is spent, and a result that comes +//! back after the budget ran out is not used; +//! - afterwards a deferred stage is not run again while its input and parameters stay the same; a +//! stage whose input or parameters changed runs under the per-call limit; +//! - [`Deferrals::refresh`] runs deferred stages again with a fresh budget. +//! +//! Work outside a view (exports, commands, drawing without a screen) runs every stage under the +//! per-call limit. When such a run gives a result for a stage some document has deferred, +//! [`revision`] changes, so that drawings made with the deferred stage are drawn again. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +/// The time the plug-in effects drawn for a document's first view share, in milliseconds. +pub const OPENING_BUDGET_MS: u64 = 2_000; + +/// Why a stage is deferred. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Reason { + /// It was not run, or its result came too late, because the budget was spent. + Budget, + /// It ran to its per-call time limit. + Timeout, + /// Its plug-in isn't installed as a live effect. + Missing, + /// It trapped, panicked, returned art that was refused, or its parameters were refused. + Failed, + /// Safe Mode is on: no plug-in runs. + SafeMode, +} + +impl Reason { + /// The reason as `effect.deferredStatus` names it. + pub fn name(self) -> &'static str { + match self { + Reason::Budget => "budget", + Reason::Timeout => "timeout", + Reason::Missing => "missing", + Reason::Failed => "failed", + Reason::SafeMode => "safeMode", + } + } +} + +/// Where a plug-in effect sits: the object, the index of the effect in its list, and the fill or +/// stroke whose list that is (`None`: the object's own effects). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Stage { + pub object: u64, + pub effect: usize, + pub item: Option, +} + +/// A deferred stage. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Deferred { + pub stage: Stage, + /// The plug-in's id. + pub plugin: String, + pub reason: Reason, + /// The input and parameters the stage was deferred with (the effect cache's key), 0 when the + /// plug-in was not looked at (Safe Mode, a missing plug-in). + pub(crate) key: u64, +} + +/// What [`Deferrals::refresh`] did with the stages it ran again. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Refreshed { + /// Stages that gave a result. + pub refreshed: usize, + /// Stages left deferred for want of time, or with input the refresh did not run. + pub still_deferred: usize, + /// Stages that ran out of their per-call time, failed or had no plug-in again. + pub failed: usize, +} + +/// Milliseconds on a monotonic clock, `None` from a clock that cannot be read. +pub type Clock = Arc Option + Send + Sync>; + +/// Milliseconds since the first reading in this process, from `web_time::Instant`: the system's +/// monotonic clock on the desktop and the page's `performance.now()` in the web build. +fn monotonic() -> Option { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let start = START.get_or_init(web_time::Instant::now); + Some(u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)) +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Phase { + /// Runs share a budget that started at `started` (`None`: no run yet). `first`: the first + /// view, which reports what it deferred when it ends. + Budgeted { started: Option, first: bool }, + /// Deferred stages are left as they are while their input stays the same. + Open, +} + +struct State { + phase: Phase, + deferred: Vec, + /// How many stages the first view left deferred, until [`Deferrals::take_report`] takes it. + report: Option, + /// The refresh running, if one is ([`Deferrals::refresh`]). + refresh: Option, + clock: Clock, +} + +/// A [`Deferrals::refresh`] while it runs. It applies only to the thread that runs it: drawings +/// of the document on other threads go on as if no refresh ran. +struct Refresh { + thread: std::thread::ThreadId, + /// When its budget started (`None`: no run yet). + started: Option, + /// The objects whose stages run again; the others' stay deferred. + ids: Vec, + /// The cache keys whose cached failures have been run again. + retried: Vec, + /// The stages of `ids` that were drawn. + visited: Vec, + /// The stage inputs of `ids` that ran, or were taken from the cache, or were deferred again. + touched: Vec<(Stage, u64)>, +} + +impl State { + /// The refresh running on this thread. + fn refresh_here(&mut self) -> Option<&mut Refresh> { + let here = std::thread::current().id(); + self.refresh.as_mut().filter(|r| r.thread == here) + } + + /// The phase that applies on this thread: a refresh running here has a budget of its own. + fn phase_here(&mut self) -> Phase { + match self.refresh_here() { + Some(r) => Phase::Budgeted { started: r.started, first: false }, + None => self.phase, + } + } + + /// Is a refresh running here, and does it run the stages of `object`? + fn refreshes(&mut self, object: u64) -> Option { + self.refresh_here().map(|r| r.ids.contains(&object)) + } +} + +impl Drop for State { + fn drop(&mut self) { + for d in &self.deferred { + unmark(d.key); + } + } +} + +/// The deferred stages and the opening budget of one open document. Clones share them. +#[derive(Clone)] +pub struct Deferrals(Arc>); + +impl Default for Deferrals { + fn default() -> Self { + Self::with_clock(Arc::new(monotonic)) + } +} + +impl std::fmt::Debug for Deferrals { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Deferrals").field("deferred", &self.list()).finish() + } +} + +/// What a budgeted run may take. +pub(crate) enum Allowance { + /// No budget applies: the per-call limit. + Unlimited, + /// At most this many milliseconds, which end the budget at `until`. + Until { ms: u64, until: u64 }, + /// The budget is spent: the stage is deferred without running. + Spent, +} + +impl Deferrals { + /// A document's deferrals before its first view, timed by the monotonic clock. + pub fn new() -> Self { + Self::default() + } + + /// [`Deferrals::new`] timed by `clock` (tests give a clock of their own). + pub fn with_clock(clock: Clock) -> Self { + Self(Arc::new(Mutex::new(State { + phase: Phase::Budgeted { started: None, first: true }, + deferred: Vec::new(), + report: None, + refresh: None, + clock, + }))) + } + + fn state(&self) -> std::sync::MutexGuard<'_, State> { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// The deferred stages, by object and effect, each once (a stage drawn with several inputs, + /// such as the paths of a group, is listed with the first one's reason). + pub fn list(&self) -> Vec { + let mut out = self.state().deferred.clone(); + out.sort_by_key(|d| (d.stage.object, d.stage.item, d.stage.effect)); + out.dedup_by_key(|d| d.stage); + out + } + + /// Is the first view still being drawn ([`Deferrals::first_view_done`] not called yet)? + pub fn opening(&self) -> bool { + matches!(self.state().phase, Phase::Budgeted { first: true, .. }) + } + + /// Runs `f` with these deferrals applied to the plug-in effects evaluated on this thread. + pub fn view(&self, f: impl FnOnce() -> T) -> T { + let previous = VIEW.with(|v| v.borrow_mut().replace(self.clone())); + let _ = PASSES.try_with(|p| p.borrow_mut().push(Pass::default())); + let _restore = Restore { previous, current: self.clone() }; + f() + } + + /// One drawing inside [`Deferrals::view`] has ended: a stage that ran after the first view, + /// whether it gave a result or was deferred again, keeps only the records of the inputs that + /// drawing left deferred. The records of its other inputs were made with input it no longer + /// has. + fn settle(&self, pass: Pass) { + if pass.ran.is_empty() { + return; + } + self.state().deferred.retain(|d| { + let keep = !pass.ran.contains(&d.stage) || pass.seen.contains(&(d.stage, d.key)); + if !keep { + unmark(d.key); + } + keep + }); + } + + /// The first view has been drawn: later drawings leave deferred stages deferred, and + /// [`Deferrals::take_report`] gives how many there are. Does nothing after the first call. + pub fn first_view_done(&self) { + let mut s = self.state(); + if let Phase::Budgeted { first: true, .. } = s.phase { + s.phase = Phase::Open; + s.report = Some(s.stages().len()); + } + } + + /// How many stages the first view left deferred, once, after it was drawn. + pub fn take_report(&self) -> Option { + self.state().report.take() + } + + /// Runs the deferred stages of the objects in `objects` (all of them when `None`) again with a + /// fresh budget: `run` is given those objects, draws them inside [`Deferrals::view`] on this + /// thread, and returns the objects it drew whole, every part of them reached. A stage the + /// drawing does not reach (that of a hidden object, say) stays deferred as it was, and so does + /// a stage input it does not reach, unless the object was drawn whole: the input is then one + /// the stage no longer has. The refresh and its budget apply only to this thread. + pub fn refresh(&self, objects: Option<&[u64]>, run: impl FnOnce(&[u64]) -> Vec) -> Refreshed { + let (targets, ids) = { + let mut s = self.state(); + let mut targets: Vec = s.deferred.iter().map(|d| d.stage).filter(|t| objects.is_none_or(|o| o.contains(&t.object))).collect(); + targets.sort_by_key(|t| (t.object, t.item, t.effect)); + targets.dedup(); + let mut ids: Vec = targets.iter().map(|t| t.object).collect(); + ids.dedup(); + let thread = std::thread::current().id(); + let (retried, visited, touched) = (Vec::new(), Vec::new(), Vec::new()); + s.refresh = Some(Refresh { thread, started: None, ids: ids.clone(), retried, visited, touched }); + (targets, ids) + }; + // The refresh ends when `run` returns, also when it unwinds. + struct Reopen<'a>(&'a Deferrals); + impl Drop for Reopen<'_> { + fn drop(&mut self) { + self.0.state().refresh = None; + } + } + let reopen = Reopen(self); + let whole = run(&ids); + let mut s = self.state(); + let touched = match s.refresh.take() { + Some(r) => { + s.deferred.retain(|d| { + let gone = r.visited.contains(&d.stage) && whole.contains(&d.stage.object) && !r.touched.contains(&(d.stage, d.key)); + if gone { + unmark(d.key); + } + !gone + }); + r.touched + } + None => Vec::new(), + }; + drop(s); + drop(reopen); + // A stage fails again when an input it ran with this time is deferred for a reason other + // than time; one with records left that this refresh did not run is still deferred. + let s = self.state(); + let mut out = Refreshed::default(); + for t in &targets { + let mut left = s.deferred.iter().filter(|d| d.stage == *t).peekable(); + if left.peek().is_none() { + out.refreshed += 1; + } else if left.any(|d| d.reason != Reason::Budget && touched.contains(&(d.stage, d.key))) { + out.failed += 1; + } else { + out.still_deferred += 1; + } + } + drop(s); + if out.refreshed > 0 { + REVISION.fetch_add(1, Ordering::Relaxed); + } + out + } + + /// Records `stage` with cache key `key` (of plug-in `plugin`) as deferred for `reason`, in + /// place of what was recorded for that stage and key. After the first view, when the drawing + /// ends, the stage's records of inputs that drawing did not leave deferred are dropped + /// ([`Deferrals::settle`]). + pub(crate) fn defer(&self, stage: Stage, plugin: &str, reason: Reason, key: u64) { + seen(stage, key); + let mut s = self.state(); + s.remove(stage, key); + mark(key); + s.deferred.push(Deferred { stage, plugin: plugin.to_string(), reason, key }); + s.ran_here(stage, key); + } + + /// `stage` gave a result for cache key `key`, from a run or from the cache: it is no longer + /// deferred with that input. After the first view, when the drawing ends, the stage's records + /// of inputs that drawing did not leave deferred are dropped as well ([`Deferrals::settle`]). + pub(crate) fn ran(&self, stage: Stage, key: u64) { + let mut s = self.state(); + s.remove(stage, key); + s.ran_here(stage, key); + } + + /// Should `stage`, with cache key `key`, be left deferred without running? After the first + /// view, a stage deferred with the same input and parameters is, and so is one of an object a + /// refresh does not run. + pub(crate) fn holds(&self, stage: Stage, key: u64) -> bool { + let mut s = self.state(); + let settled = s.phase_here() == Phase::Open || s.refreshes(stage.object) == Some(false); + let held = settled && s.deferred.iter().any(|d| d.stage == stage && d.key == key); + drop(s); + if held { + seen(stage, key); + } + held + } + + /// `stage` is being drawn: a refresh running here that runs its object's stages notes that it + /// reached the stage. + pub(crate) fn visit(&self, stage: Stage) { + let mut s = self.state(); + if let Some(r) = s.refresh_here().filter(|r| r.ids.contains(&stage.object) && !r.visited.contains(&stage)) { + r.visited.push(stage); + } + } + + /// Drops the records of the stages for which `keep` (given the stage and the plug-in id) is + /// false, such as those of effects or objects removed from the document. + pub fn retain(&self, keep: impl Fn(Stage, &str) -> bool) { + self.state().deferred.retain(|d| { + let k = keep(d.stage, &d.plugin); + if !k { + unmark(d.key); + } + k + }); + } + + /// Should the failure cached for `stage` with cache key `key` be run again? Yes once per key + /// while a refresh running here runs the stages of `stage`'s object. + pub(crate) fn retries(&self, stage: Stage, key: u64) -> bool { + let mut s = self.state(); + let Some(r) = s.refresh_here().filter(|r| r.ids.contains(&stage.object) && !r.retried.contains(&key)) else { return false }; + r.retried.push(key); + true + } + + /// What a run starting now may take of the budget: the budget starts with the first run. + /// Without a clock, the first view runs nothing and a refresh runs every stage under its + /// per-call limit. + pub(crate) fn allowance(&self) -> Allowance { + let mut s = self.state(); + let Phase::Budgeted { started, first } = s.phase_here() else { return Allowance::Unlimited }; + let Some(now) = (s.clock)() else { return if first { Allowance::Spent } else { Allowance::Unlimited } }; + let start = started.unwrap_or(now); + match s.refresh_here() { + Some(r) => r.started = Some(start), + None => s.phase = Phase::Budgeted { started: Some(start), first }, + } + let until = start.saturating_add(OPENING_BUDGET_MS); + match until.checked_sub(now).filter(|ms| *ms > 0) { + Some(ms) => Allowance::Until { ms, until }, + None => Allowance::Spent, + } + } + + /// Has the clock passed `until` (a result that came back now is too late)? Without a clock, + /// yes. + pub(crate) fn passed(&self, until: u64) -> bool { + let clock = self.state().clock.clone(); + clock().is_none_or(|now| now > until) + } +} + +impl State { + /// Removes what is recorded for `stage` with cache key `key`. A record without a key (the + /// plug-in was not looked at) stands for any input, so it goes whatever `key` is, and `key` 0 + /// removes every record of the stage. + fn remove(&mut self, stage: Stage, key: u64) { + self.deferred.retain(|d| { + let keep = d.stage != stage || (d.key != key && d.key != 0 && key != 0); + if !keep { + unmark(d.key); + } + keep + }); + } + + /// `stage` was run with cache key `key`, or taken from the cache, by the drawing on this + /// thread: a refresh running here notes the input ([`Deferrals::refresh`]), and after the first + /// view [`Deferrals::settle`] looks at the stage when that drawing ends. + fn ran_here(&mut self, stage: Stage, key: u64) { + if let Some(r) = self.refresh_here().filter(|r| r.ids.contains(&stage.object)) { + r.touched.push((stage, key)); + } + if self.phase_here() == Phase::Open { + let _ = PASSES.try_with(|p| { + if let Some(pass) = p.borrow_mut().last_mut().filter(|pass| !pass.ran.contains(&stage)) { + pass.ran.push(stage); + } + }); + } + } + + /// The deferred stages, each once. + fn stages(&self) -> Vec { + let mut out: Vec = self.deferred.iter().map(|d| d.stage).collect(); + out.sort_by_key(|t| (t.object, t.item, t.effect)); + out.dedup(); + out + } +} + +thread_local! { + static VIEW: RefCell> = const { RefCell::new(None) }; + /// One entry for each [`Deferrals::view`] running on this thread, innermost last. + static PASSES: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// What one drawing inside a view did: the stages that ran after the first view (with a result or +/// deferred again), and the stage inputs it left deferred. +#[derive(Default)] +struct Pass { + ran: Vec, + seen: Vec<(Stage, u64)>, +} + +/// The drawing on this thread left `stage` deferred with cache key `key`. +fn seen(stage: Stage, key: u64) { + let _ = PASSES.try_with(|p| { + if let Some(pass) = p.borrow_mut().last_mut() { + pass.seen.push((stage, key)); + } + }); +} + +/// Ends the drawing and puts the previous view back, also when the work inside unwinds. +struct Restore { + previous: Option, + current: Deferrals, +} + +impl Drop for Restore { + fn drop(&mut self) { + if let Some(pass) = PASSES.try_with(|p| p.borrow_mut().pop()).ok().flatten() { + self.current.settle(pass); + } + let previous = self.previous.take(); + let _ = VIEW.try_with(|v| *v.borrow_mut() = previous); + } +} + +/// The deferrals of the view being drawn on this thread ([`Deferrals::view`]). +pub fn current() -> Option { + VIEW.try_with(|v| v.borrow().clone()).ok().flatten() +} + +/// Changes when deferred stages give results: [`Deferrals::refresh`] ran some, or a run outside a +/// view gave a result for a stage some document has deferred. +pub fn revision() -> u64 { + REVISION.load(Ordering::Relaxed) +} + +static REVISION: AtomicU64 = AtomicU64::new(0); + +/// The cache keys some document's deferred stages were deferred with, and how many stages hold each. +static MARKED: Mutex>> = Mutex::new(None); + +fn mark(key: u64) { + if key != 0 { + *MARKED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new).entry(key).or_default() += 1; + } +} + +fn unmark(key: u64) { + let mut marked = MARKED.lock().unwrap_or_else(|e| e.into_inner()); + let Some(m) = marked.as_mut() else { return }; + if let Some(n) = m.get_mut(&key) { + *n -= 1; + if *n == 0 { + m.remove(&key); + } + } +} + +/// A run gave a result for cache key `key`: when some document deferred a stage with that key, +/// [`revision`] changes. +pub(crate) fn resolved(key: u64) { + let marked = MARKED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&key)); + if marked { + REVISION.fetch_add(1, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A clock that reads `step` milliseconds later each time it is read. + fn stepping(step: u64) -> Clock { + let t = Arc::new(AtomicU64::new(0)); + Arc::new(move || Some(t.fetch_add(step, Ordering::Relaxed))) + } + + #[test] + fn the_budget_starts_with_the_first_run_and_ends_after_it() { + let d = Deferrals::with_clock(stepping(700)); + assert!(matches!(d.allowance(), Allowance::Until { ms: 2_000, until: 2_000 })); + assert!(matches!(d.allowance(), Allowance::Until { ms: 1_300, until: 2_000 })); + assert!(matches!(d.allowance(), Allowance::Until { ms: 600, until: 2_000 })); + assert!(matches!(d.allowance(), Allowance::Spent)); + d.first_view_done(); + assert!(matches!(d.allowance(), Allowance::Unlimited)); + } + + #[test] + fn without_a_clock_the_first_view_runs_nothing_and_a_refresh_everything() { + let d = Deferrals::with_clock(Arc::new(|| None)); + assert!(matches!(d.allowance(), Allowance::Spent)); + assert!(d.passed(u64::MAX)); + d.first_view_done(); + d.defer(Stage::default(), "a", Reason::Budget, 31); + d.refresh(None, |_| { + assert!(matches!(d.allowance(), Allowance::Unlimited)); + vec![] + }); + } + + /// The default clock, which the web build also reads, gives the first view its budget. + #[test] + fn the_default_clock_gives_the_first_view_a_budget() { + let d = Deferrals::new(); + assert!(matches!(d.allowance(), Allowance::Until { ms: OPENING_BUDGET_MS, .. })); + assert!(!d.passed(u64::MAX)); + } + + /// A stage drawn with several inputs (the paths of a group) holds one record for each, and is + /// listed and counted once. + #[test] + fn a_stage_is_listed_and_counted_once() { + let d = Deferrals::with_clock(stepping(1)); + let s = Stage { object: 7, effect: 1, item: None }; + d.defer(s, "a", Reason::Budget, 11); + d.defer(s, "a", Reason::Budget, 12); + d.defer(s, "a", Reason::Timeout, 12); + d.defer(Stage { item: Some(0), ..s }, "a", Reason::Failed, 13); + assert_eq!(d.list().len(), 2); + assert!(!d.holds(s, 12), "the first view runs deferred stages"); + d.first_view_done(); + assert!(d.holds(s, 11) && d.holds(s, 12)); + assert!(!d.holds(s, 14), "other input"); + assert_eq!(d.take_report(), Some(2)); + assert_eq!(d.take_report(), None); + d.first_view_done(); + assert_eq!(d.take_report(), None, "the first view ends once"); + d.ran(s, 11); + assert_eq!(d.list().len(), 2, "the stage is still deferred with its other input"); + d.ran(s, 12); + assert_eq!(d.list().len(), 1); + d.defer(s, "a", Reason::Missing, 0); + d.ran(s, 15); + assert_eq!(d.list().len(), 1, "a record without a key goes with any result"); + } + + /// A refresh runs the deferred stages of the objects asked for with a fresh budget, and counts + /// what became of them; the stages its drawing did not reach stay as they were. Another + /// thread draws the document as if no refresh ran. + #[test] + fn a_refresh_counts_what_became_of_each_stage() { + let d = Deferrals::with_clock(stepping(1)); + d.first_view_done(); + let st = |object, effect| Stage { object, effect, item: None }; + let stages = [ + (st(1, 0), Reason::Budget), + (st(1, 1), Reason::Budget), + (st(1, 2), Reason::Budget), + (st(1, 3), Reason::Timeout), + (st(2, 0), Reason::Budget), + (st(3, 0), Reason::Failed), + ]; + for (stage, reason) in stages { + d.defer(stage, "a", reason, 40 + stage.object * 4 + stage.effect as u64); + } + let seen = std::cell::RefCell::new(vec![]); + let counts = d.refresh(Some(&[1, 3, 9]), |ids| { + seen.borrow_mut().extend_from_slice(ids); + assert!(matches!(d.allowance(), Allowance::Until { .. }), "a fresh budget"); + assert!(d.holds(st(2, 0), 48), "an object not asked for stays deferred"); + d.visit(st(2, 0)); + d.visit(st(1, 0)); + d.visit(st(1, 1)); + d.defer(st(1, 1), "a", Reason::Budget, 45); + std::thread::scope(|scope| { + let other = scope.spawn(|| (matches!(d.allowance(), Allowance::Unlimited), d.holds(st(1, 2), 46), d.retries(st(3, 0), 52))); + assert_eq!(other.join().unwrap(), (true, true, false), "another thread"); + }); + d.visit(st(1, 1)); + assert_eq!(d.list().iter().filter(|x| x.stage == st(1, 1)).count(), 1, "a stage is reached once"); + d.visit(st(3, 0)); + d.defer(st(3, 0), "a", Reason::Failed, 52); + ids.to_vec() + }); + assert_eq!(*seen.borrow(), [1, 3]); + // st(1, 3) timed out before and was not reached: still deferred, not failed again. + assert_eq!(counts, Refreshed { refreshed: 1, still_deferred: 3, failed: 1 }); + assert!(matches!(d.allowance(), Allowance::Unlimited), "the budget ends with the refresh"); + let left = d.list().iter().map(|x| x.stage).collect::>(); + assert_eq!(left, [st(1, 1), st(1, 2), st(1, 3), st(2, 0), st(3, 0)]); + + // An object the drawing did not reach whole keeps the inputs it did not reach: a reached + // stage of it gives a result only for the inputs that ran. + d.defer(st(1, 1), "a", Reason::Budget, 70); + let counts = d.refresh(Some(&[1]), |_| { + d.visit(st(1, 1)); + d.ran(st(1, 1), 45); + vec![] + }); + assert_eq!(counts, Refreshed { refreshed: 0, still_deferred: 3, failed: 0 }); + let keys = |stage| d.state().deferred.iter().filter(|x| x.stage == stage).map(|x| x.key).collect::>(); + assert_eq!(keys(st(1, 1)), [70]); + let counts = d.refresh(Some(&[1]), |_| { + d.visit(st(1, 1)); + vec![1] + }); + assert_eq!(counts, Refreshed { refreshed: 1, still_deferred: 2, failed: 0 }, "drawn whole: an input it no longer has"); + assert_eq!(keys(st(1, 1)), Vec::::new()); + d.retain(|stage, _| stage.object != 1); + assert_eq!(d.list().iter().map(|x| x.stage).collect::>(), [st(2, 0), st(3, 0)]); + } + + /// After the first view, a stage drawn with several inputs (the paths of a group) whose one + /// changed input runs keeps the records of the inputs the same drawing left deferred, and drops + /// the record of the input it no longer has. + #[test] + fn a_stage_that_runs_keeps_the_inputs_its_drawing_left_deferred() { + let d = Deferrals::with_clock(stepping(1)); + let s = Stage { object: 4, effect: 0, item: None }; + let other = Stage { object: 5, ..s }; + for key in [61, 62] { + d.defer(s, "a", Reason::Budget, key); + } + d.defer(other, "a", Reason::Budget, 63); + d.first_view_done(); + d.view(|| { + assert!(d.holds(s, 61), "an unchanged path"); + assert!(!d.holds(s, 64), "the changed path"); + d.ran(s, 64); + }); + let keys = d.state().deferred.iter().map(|x| (x.stage.object, x.key)).collect::>(); + assert_eq!(keys, [(4, 61), (5, 63)]); + + // A changed input that fails again replaces the record of the input it no longer has. + d.view(|| { + assert!(!d.holds(other, 65)); + d.defer(other, "a", Reason::Failed, 65); + }); + let left = d.state().deferred.iter().map(|x| (x.stage.object, x.key, x.reason)).collect::>(); + assert_eq!(left, [(4, 61, Reason::Budget), (5, 65, Reason::Failed)]); + } + + #[test] + fn a_result_for_a_deferred_key_changes_the_revision() { + const KEY: u64 = 0xdef0_0001; + let marked = || MARKED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&KEY)); + let d = Deferrals::with_clock(stepping(1)); + assert!(!marked()); + d.defer(Stage::default(), "a", Reason::Budget, KEY); + let other = d.clone(); + other.defer(Stage { object: 2, ..Stage::default() }, "a", Reason::Budget, KEY); + assert!(marked()); + let before = revision(); + resolved(KEY); + assert!(revision() > before); + other.ran(Stage::default(), KEY); + assert!(marked(), "another stage holds the key"); + drop((d, other)); + assert!(!marked(), "the document closed"); + } +} diff --git a/crates/plugins/src/effect.rs b/crates/plugins/src/effect.rs index 01cedbcc02..f06d17e242 100644 --- a/crates/plugins/src/effect.rs +++ b/crates/plugins/src/effect.rs @@ -12,7 +12,8 @@ //! plug-in installation, parameters, input geometry and paints: the plug-in runs again only when //! one of them changes. Failures are cached too (the geometry is then drawn unchanged) and //! reported by [`last_error`]. The swatches and patterns a painted result names are checked -//! against the document each time it is used. +//! against the document each time it is used. While a document is drawn on screen, its first view +//! shares a time budget and stages without a result are deferred ([`crate::deferred`]). use std::collections::HashMap; use std::hash::{Hash, Hasher}; @@ -22,6 +23,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, AppearanceItem, Document}; use vectorcraft_geom::{FillRule, PathData, Rect}; +use crate::deferred::{Allowance, Reason, Stage}; use crate::objects::{decode, output_geometry, paint_lists}; use crate::painted::{self, Piece, Scope}; use crate::{Error, Kind, Limits, Result, registry}; @@ -69,6 +71,9 @@ pub struct Paints<'a> { /// The index in `appearance.items` of the fill or stroke whose own effects hold this one; /// `None`: one of the object's effects. pub item: Option, + /// The object and the effect's place in its list, which a deferred stage is listed by + /// ([`crate::deferred`]); `None`: not known, listed as object 0. + pub at: Option, } /// [`Paints`] as the plug-in is given them: the input object's `fills` and `strokes`, and @@ -151,7 +156,8 @@ impl Out { #[derive(Default)] struct Cache { - entries: HashMap)>, + /// Each result, or why the run gave none ([`Reason::Timeout`] or [`Reason::Failed`]). + entries: HashMap)>, /// The anchors of the entries' inputs and results ([`CACHE_ANCHORS`]). anchors: usize, } @@ -294,9 +300,10 @@ pub fn paints_output(id: &str) -> bool { /// For an effect that returns painted pieces, the geometry is every piece's path in order, and /// `None` when the swatches and patterns they name are refused as [`apply_painted`] refuses them. pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillRule, paints: Paints, doc: Option<&Document>) -> Option { + let at = paints.at; let (plugin, out) = evaluate(id, params, path, bounds, rule, paints)?; if let Out::Pieces(pieces) = &out { - references_found(id, &plugin, pieces, doc)?; + references_found(id, &plugin, pieces, doc, at)?; } Some(out.geometry()) } @@ -318,9 +325,10 @@ pub fn apply_painted( paints: Paints, doc: Option<&Document>, ) -> Option>> { + let at = paints.at; let (plugin, out) = evaluate(id, params, path, bounds, rule, paints)?; let Out::Pieces(pieces) = out else { return None }; - references_found(id, &plugin, &pieces, doc)?; + references_found(id, &plugin, &pieces, doc, at)?; Some(match doc { Some(d) => painted::with_swatch_colors(pieces, d), None => pieces, @@ -329,11 +337,17 @@ pub fn apply_painted( /// `Some` when every swatch and pattern `pieces` name is in `doc` ([`painted::check_references`]), /// recording the outcome for [`last_error`] when there is a document. The document's swatches and -/// patterns can change while a result stays cached, so each use checks them. -fn references_found(id: &str, plugin: &crate::Plugin, pieces: &[Piece], doc: Option<&Document>) -> Option<()> { +/// patterns can change while a result stays cached, so each use checks them. Inside a document's +/// view, a refusal defers stage `at` as failed. +fn references_found(id: &str, plugin: &crate::Plugin, pieces: &[Piece], doc: Option<&Document>, at: Option) -> Option<()> { let checked = painted::check_references(pieces, doc); if doc.is_some() { note(id, plugin, Origin::References, checked.as_ref().map(|_| ())); + if checked.is_err() + && let Some(v) = crate::deferred::current() + { + v.defer(at.unwrap_or_default(), id, Reason::Failed, 0); + } } checked.ok() } @@ -341,12 +355,36 @@ fn references_found(id: &str, plugin: &crate::Plugin, pieces: &[Piece], doc: Opt /// Runs plug-in `id` as [`apply`] says, or takes its result from the cache: the plug-in and what /// it gave. The launch marker names the plug-in during its first run in this process, and until /// every run that started while it ran has ended too ([`crate::safe_mode::loading`]). +/// +/// Inside a document's view ([`crate::deferred`]), a stage without a result is recorded as +/// deferred with the reason, and one with a result is no longer deferred. During the view's +/// budget a run takes at most what is left of it, none starts once it is spent, and a result +/// that comes back after it ran out is not used; neither is cached or reported by +/// [`last_error`]. After the first view, a stage deferred with the same input is not run again. fn evaluate(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillRule, paints: Paints) -> Option<(Arc, Out)> { + let view = crate::deferred::current(); + let stage = paints.at.unwrap_or_default(); + if let Some(v) = &view { + v.visit(stage); + } + let defer = |reason, key| { + if let Some(v) = &view { + v.defer(stage, id, reason, key); + } + }; if crate::safe_mode::active() { + defer(Reason::SafeMode, 0); return None; } - let plugin = registry::get(id).filter(|p| p.manifest().kind == Kind::Effect)?; - let resolved = Value::Object(plugin.manifest().resolve_params(params).ok()?); + let Some(plugin) = registry::get(id).filter(|p| p.manifest().kind == Kind::Effect) else { + defer(Reason::Missing, 0); + return None; + }; + let Ok(resolved) = plugin.manifest().resolve_params(params) else { + defer(Reason::Failed, 0); + return None; + }; + let resolved = Value::Object(resolved); let given = paints.given(); let key = Key { serial: plugin.serial(), @@ -357,14 +395,44 @@ fn evaluate(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillR path: path.clone(), }; let h = key.hash64(); - if let Some((k, out)) = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref().and_then(|c| c.entries.get(&h)) - && *k == key - { - return out.clone().map(|o| (plugin, o)); + let cached = CACHE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .and_then(|c| c.entries.get(&h)) + .filter(|(k, _)| *k == key) + .map(|(_, out)| out.clone()); + match cached { + // A result from the cache counts as a run that gave it. + Some(Ok(o)) => { + if let Some(v) = &view { + v.ran(stage, h); + } + return Some((plugin, o)); + } + // A refresh runs a stage that failed again. + Some(Err(reason)) if !view.as_ref().is_some_and(|v| v.retries(stage, h)) => { + defer(reason, h); + return None; + } + _ => {} } + let allowance = match &view { + Some(v) if v.holds(stage, h) => return None, + Some(v) => v.allowance(), + None => Allowance::Unlimited, + }; + let (wall_time_ms, until) = match allowance { + Allowance::Unlimited => (WALL_TIME_MS, None), + Allowance::Until { ms, until } => (ms.min(WALL_TIME_MS), Some(until)), + Allowance::Spent => { + defer(Reason::Budget, h); + return None; + } + }; let scope = paints.scope(); let guarded = begin_run(&plugin); - let r = run(&plugin, resolved, path, bounds, rule, given, scope); + let r = run(&plugin, resolved, path, (bounds, rule), given, scope, wall_time_ms); let cancelled = matches!(r, Err(Error::Cancelled)); if guarded { end_run(plugin.serial(), cancelled); @@ -373,11 +441,28 @@ fn evaluate(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillR if cancelled { return None; } + let timed_out = matches!(&r, Err(Error::Limit(l)) if l == crate::host::TIME_BUDGET); + // A run the budget cut short, or whose result came after the budget ran out, says nothing + // about the plug-in either: the stage waits for a later run. + let late = until.is_some_and(|u| view.as_ref().is_some_and(|v| v.passed(u))); + if (timed_out && wall_time_ms < WALL_TIME_MS) || late { + defer(Reason::Budget, h); + return None; + } note(id, &plugin, Origin::Run, r.as_ref().map(|_| ())); - let out = r.ok(); - let size = weight(&key, out.as_ref()); + let out = r.map_err(|_| if timed_out { Reason::Timeout } else { Reason::Failed }); + match &out { + Ok(_) => { + if let Some(v) = &view { + v.ran(stage, h); + } + crate::deferred::resolved(h); + } + Err(reason) => defer(*reason, h), + } + let size = weight(&key, out.as_ref().ok()); if size > CACHE_ANCHORS / 4 { - return out.map(|o| (plugin, o)); + return out.ok().map(|o| (plugin, o)); } let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); let cache = cache.get_or_insert_with(Cache::default); @@ -385,15 +470,24 @@ fn evaluate(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillR *cache = Cache::default(); } if let Some((old, old_out)) = cache.entries.insert(h, (key, out.clone())) { - cache.anchors = cache.anchors.saturating_sub(weight(&old, old_out.as_ref())); + cache.anchors = cache.anchors.saturating_sub(weight(&old, old_out.as_ref().ok())); } cache.anchors += size; - out.map(|o| (plugin, o)) + out.ok().map(|o| (plugin, o)) } -/// One run of `plugin` on `path`, with the object's paints as `given`: geometry, or for an effect -/// that declares `paintOutput` its pieces, checked for an effect in `scope`. -fn run(plugin: &crate::Plugin, mut params: Value, path: &PathData, bounds: Rect, rule: FillRule, given: Given, scope: Scope) -> Result { +/// One run of `plugin` on `path` (reference box and fill rule `(bounds, rule)`), with the object's +/// paints as `given`, stopped after `wall_time_ms`: geometry, or for an effect that declares +/// `paintOutput` its pieces, checked for an effect in `scope`. +fn run( + plugin: &crate::Plugin, + mut params: Value, + path: &PathData, + (bounds, rule): (Rect, FillRule), + given: Given, + scope: Scope, + wall_time_ms: u64, +) -> Result { let b = json!([bounds.x0, bounds.y0, bounds.x1, bounds.y1]); params["_context"] = json!({"mode": "effect", "bounds": b, "item": given.item}); let rule_name = match rule { @@ -404,7 +498,9 @@ fn run(plugin: &crate::Plugin, mut params: Value, path: &PathData, bounds: Rect, json!({"objects": [{"type": "path", "path": path, "fillRule": rule_name, "bounds": b, "fills": given.fills, "strokes": given.strokes}]}); let (input, params) = (serde_json::to_vec(&input), serde_json::to_vec(¶ms)); let (Ok(input), Ok(params)) = (input, params) else { return Err(Error::Params("can't encode the input".into())) }; - let limits = Limits { wall_time_ms: WALL_TIME_MS, ..plugin.limits().clone() }; + let limits = Limits { wall_time_ms, ..plugin.limits().clone() }; + #[cfg(test)] + tests::RUNS_STARTED.with(|n| n.set(n.get() + 1)); let output = plugin.run_limited(&input, ¶ms, &limits)?; if plugin.manifest().paint_output { return Ok(Out::Pieces(Arc::new(painted::decode(&output, scope, rule)?))); @@ -420,6 +516,11 @@ mod tests { use super::*; + thread_local! { + /// How many plug-in runs this thread started ([`run`]). + pub(super) static RUNS_STARTED: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + /// Fills and strokes come in paint order, and the item an effect sits on is counted among the /// fills or among the strokes. #[test] @@ -427,7 +528,7 @@ mod tests { let fill = |c| AppearanceItem::Fill(FillLayer::new(Paint::solid(c))); let stroke = |w| AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), w)); let ap = Appearance { items: vec![fill(Color::WHITE), stroke(2.0), fill(Color::BLACK), stroke(5.0)], ..Appearance::default() }; - let given = |item| Paints { appearance: Some(&ap), item }.given(); + let given = |item| Paints { appearance: Some(&ap), item, at: None }.given(); let g = given(None); assert_eq!((g.fills.len(), g.strokes.len(), &g.item), (2, 2, &json!("object"))); assert_eq!(g.strokes.iter().map(|s| s["width"].clone()).collect::>(), [json!(2.0), json!(5.0)]); @@ -494,9 +595,141 @@ mod tests { assert!(last_error(ID).unwrap().contains("trapped")); assert!(draw(&short).is_none(), "from the cache, refused again"); assert!(last_error(ID).unwrap().contains("swatch")); + // Inside a document's view, the refused stage is deferred as failed, also from the cache. + let view = crate::deferred::Deferrals::with_clock(Arc::new(|| Some(0))); + let at = Stage { object: 3, effect: 1, item: None }; + let in_view = || { + view.view(|| { + apply_painted( + ID, + &json!({}), + &short, + Rect::new(0.0, 0.0, 1.0, 1.0), + FillRule::NonZero, + Paints { at: Some(at), ..Paints::default() }, + Some(&doc), + ) + }) + }; + assert!(in_view().is_none()); + let listed = || view.list().iter().map(|d| (d.stage, d.reason)).collect::>(); + assert_eq!(listed(), [(at, Reason::Failed)]); + view.first_view_done(); + assert!(in_view().is_none()); + assert_eq!(listed(), [(at, Reason::Failed)], "a later drawing leaves it listed"); registry::remove(ID); } + /// A clock that reads `step` milliseconds later each time it is read. + fn stepping(step: u64) -> crate::deferred::Clock { + let t = Arc::new(std::sync::atomic::AtomicU64::new(0)); + Arc::new(move || Some(t.fetch_add(step, std::sync::atomic::Ordering::Relaxed))) + } + + /// A line of `n` points: a distinct input for each `n`. + fn line(n: usize) -> PathData { + PathData::single(SubPath::polyline(&(0..n).map(|i| Point::new(i as f64, 0.0)).collect::>(), false)) + } + + /// Plug-in `id` drawn on `path` as effect `effect` of object 1: whether it gave a result. + fn drawn(id: &str, path: &PathData, effect: usize) -> bool { + let at = Some(Stage { object: 1, effect, item: None }); + apply(id, &json!({}), path, Rect::new(0.0, 0.0, 1.0, 1.0), FillRule::NonZero, Paints { at, ..Paints::default() }, None).is_some() + } + + /// The effects of a first view share its budget: once it is spent no run starts, and a result + /// that comes back after it ran out is not used. Later drawings leave the deferred stages + /// deferred; a drawing outside the view (an export) runs them, and the view then uses the + /// result. + #[test] + fn the_first_view_shares_the_budget_and_defers_the_rest() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + const ID: &str = "test.effect.budget"; + let src = crate::wat::returning(&crate::wat::manifest(ID, "effect", "{}"), r#"{"objects":[]}"#); + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + // Each run takes 900 ms by this clock (it is read before and after each run). + let view = crate::deferred::Deferrals::with_clock(stepping(450)); + let ran = view.view(|| (0..4).map(|i| drawn(ID, &line(i + 2), i)).collect::>()); + assert_eq!(ran, [true, true, false, false], "the third result comes back at 2,250 ms, the fourth doesn't start"); + let listed = view.list().iter().map(|d| (d.stage.effect, d.reason, d.plugin.clone())).collect::>(); + assert_eq!(listed, [(2, Reason::Budget, ID.to_string()), (3, Reason::Budget, ID.to_string())]); + view.first_view_done(); + assert_eq!(view.take_report(), Some(2)); + assert!(!view.view(|| drawn(ID, &line(4), 2)), "a later drawing leaves it deferred"); + assert!(view.view(|| drawn(ID, &line(9), 3)), "an edit to its input runs it"); + assert_eq!(view.list().len(), 1); + assert!(drawn(ID, &line(4), 2), "outside the view it runs"); + assert_eq!(view.list().len(), 1, "until the view draws it again"); + assert!(view.view(|| drawn(ID, &line(9), 2)), "an edit to an input whose result is cached"); + assert!(view.list().is_empty(), "the record of the input it no longer has goes"); + assert!(view.view(|| drawn(ID, &line(4), 2)), "from the cache"); + assert!(view.list().is_empty()); + registry::remove(ID); + } + + /// A stage that fails, or whose plug-in is missing, is deferred with that reason, from a run or + /// from the cache; a failure is cached and reported as before. + #[test] + fn failed_and_missing_stages_are_deferred_with_their_reason() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + const ID: &str = "test.effect.deferfailed"; + // Runs to its instruction budget. + let src = crate::wat::spinning(&crate::wat::manifest(ID, "effect", "{}"), 1_000_000_000, r#"{"objects":[]}"#); + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()); + let view = crate::deferred::Deferrals::with_clock(stepping(1)); + assert!(!view.view(|| drawn(ID, &line(2), 0))); + assert!(last_error(ID).is_some()); + assert!(!view.view(|| drawn("test.effect.notinstalled", &line(2), 1))); + let reasons = |v: &crate::deferred::Deferrals| v.list().iter().map(|d| d.reason).collect::>(); + assert_eq!(reasons(&view), [Reason::Failed, Reason::Missing]); + let other = crate::deferred::Deferrals::with_clock(stepping(1)); + assert!(!other.view(|| drawn(ID, &line(2), 0))); + assert_eq!(reasons(&other), [Reason::Failed], "from the cache, in another document"); + // A refresh runs a stage whose failure is cached again, once, and later drawings take the + // failure from the cache. + other.first_view_done(); + let runs = || RUNS_STARTED.with(std::cell::Cell::get); + let before = runs(); + let counts = other.refresh(None, |_| { + other.view(|| (drawn(ID, &line(2), 0), drawn(ID, &line(2), 0))); + vec![] + }); + assert_eq!((counts.failed, runs() - before), (1, 1)); + assert!(!other.view(|| drawn(ID, &line(2), 0))); + assert_eq!((reasons(&other), runs() - before), (vec![Reason::Failed], 1)); + registry::remove(ID); + } + + /// A run the budget cuts short is deferred for want of time: it is not cached, and the plug-in + /// reports no error. + #[test] + fn a_run_the_budget_cuts_short_is_deferred_for_time() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + const ID: &str = "test.effect.cutshort"; + const FAST: &str = "test.effect.cutshort.fast"; + let src = crate::wat::spinning(&crate::wat::manifest(ID, "effect", "{}"), 10_000_000, r#"{"objects":[]}"#); + let limits = Limits { fuel_base: 1_000_000_000, ..Limits::default() }; + registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), limits).unwrap()); + let fast = crate::wat::returning(&crate::wat::manifest(FAST, "effect", "{}"), r#"{"objects":[]}"#); + registry::install(crate::Plugin::load(&wat::parse_str(&fast).unwrap(), Limits::default()).unwrap()); + // The first run starts the budget at 0 ms and ends at 1,999: the next has 1 ms left, and + // ten million steps take longer. + let reads = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let clock: crate::deferred::Clock = + Arc::new(move || Some(if reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { 0 } else { 1_999 })); + let view = crate::deferred::Deferrals::with_clock(clock); + assert!(view.view(|| drawn(FAST, &line(2), 0))); + assert!(!view.view(|| drawn(ID, &line(2), 1))); + assert_eq!(view.list().iter().map(|d| (d.stage.effect, d.reason)).collect::>(), [(1, Reason::Budget)]); + assert_eq!(last_error(ID), None); + assert!(drawn(ID, &line(2), 1), "not cached: outside the view it runs to the end"); + registry::remove(ID); + registry::remove(FAST); + } + /// A first run that is cancelled leaves the next run to be the first: the launch marker names /// the plug-in during that one. #[test] diff --git a/crates/plugins/src/export.rs b/crates/plugins/src/export.rs index b51fcfdb97..76b1316b7c 100644 --- a/crates/plugins/src/export.rs +++ b/crates/plugins/src/export.rs @@ -24,8 +24,7 @@ use crate::{Error, Kind, Limits, Plugin, Result, registry}; /// document: 200 times a filter's base budget. pub const FUEL: u64 = 10_000_000_000; -/// Wall-clock budget of one export, in milliseconds (native builds; the web build has no clock, -/// and the instruction budget alone bounds it there). +/// Wall-clock budget of one export, in milliseconds. pub const WALL_TIME_MS: u64 = 300_000; /// Most warnings an export reports. diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index 182456aa71..b98407cb7c 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -318,33 +318,27 @@ pub struct Report { pub truncated: bool, } -/// When a run must stop (native: a wall-clock deadline). +/// The limit a run past its wall-clock deadline exceeded ([`Error::Limit`]). +pub(crate) const TIME_BUDGET: &str = "time budget"; + +/// When a run must stop: a deadline on the monotonic clock (`web_time::Instant`, the page's +/// `performance.now()` in the web build). #[derive(Clone, Copy)] pub(crate) struct Deadline { - #[cfg(not(target_arch = "wasm32"))] - at: std::time::Instant, + at: web_time::Instant, } impl Deadline { pub(crate) fn new(wall_time_ms: u64) -> Self { - #[cfg(target_arch = "wasm32")] - let _ = wall_time_ms; - Self { - #[cfg(not(target_arch = "wasm32"))] - at: std::time::Instant::now() + std::time::Duration::from_millis(wall_time_ms), - } + Self { at: web_time::Instant::now() + std::time::Duration::from_millis(wall_time_ms) } } pub(crate) fn passed(&self) -> bool { - #[cfg(not(target_arch = "wasm32"))] - if std::time::Instant::now() >= self.at { - return true; - } - false + web_time::Instant::now() >= self.at } pub(crate) fn check(&self) -> Result<()> { - if self.passed() { Err(Error::Limit("time budget".into())) } else { Ok(()) } + if self.passed() { Err(Error::Limit(TIME_BUDGET.into())) } else { Ok(()) } } } @@ -813,6 +807,15 @@ mod tests { Run::new("test", true, false, Deadline::new(60_000)) } + /// A deadline reads the monotonic clock that the web build also reads: one of 0 ms has + /// passed, and one a day away has not. + #[test] + fn a_deadline_passes_on_the_monotonic_clock() { + assert!(Deadline::new(0).passed()); + assert!(matches!(Deadline::new(0).check(), Err(Error::Limit(l)) if l == TIME_BUDGET)); + assert!(!Deadline::new(86_400_000).passed()); + } + /// Progress is clamped: negative counts are 0 and `done` never passes a known total. #[test] fn progress_is_clamped() { diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index b4faf543db..8b57adbe63 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -9,7 +9,7 @@ //! permission): no WASI, file system, network, clock or randomness. A module that //! imports anything else is rejected; //! - an **instruction budget** (fuel) per call, metered in slices so a wall-clock deadline is -//! also enforced (native builds), so infinite loops end with an error. A filter may ask for a +//! also enforced, so infinite loops end with an error. A filter may ask for a //! larger one ([`Budget::Heavy`]), which the host lets the user allow before installing it; //! - a **linear-memory cap**, a **recursion-depth cap** and wasmi's strict module limits; //! - a **fresh instance per run**, so no state leaks between calls; what a plug-in keeps is only @@ -34,6 +34,7 @@ //! runs through `vc_run` with the command's id in `_context`. #![forbid(unsafe_code)] +pub mod deferred; pub mod dialog; pub mod effect; pub mod export; diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 5abaa0bf48..863ec0a3a5 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -29,7 +29,7 @@ const FUEL_COSTS: CustomFuelCosts = CustomFuelCosts { bytes_copied_per_fuel: 64, /// the host learns that only once the run has ended. pub const HEAVY_FUEL: u64 = 1_000_000_000; -/// Wall-clock budget of a heavy filter's run, in milliseconds (native builds). +/// Wall-clock budget of a heavy filter's run, in milliseconds. pub const HEAVY_WALL_TIME_MS: u64 = 300_000; /// The limit a run reports when its input and parameters together are past half its memory. @@ -56,8 +56,8 @@ pub struct Limits { pub fuel_per_byte: u64, /// Deepest call nesting. pub max_recursion_depth: usize, - /// Wall-clock budget for one run, in milliseconds. Native builds only: the web build has no - /// monotonic clock in `std`, so the fuel budget alone bounds it there. + /// Wall-clock budget for one run, in milliseconds. The web build measures it with the page's + /// `performance.now()`. pub wall_time_ms: u64, /// The most a heavy filter ([`crate::Budget::Heavy`]) is given instead of `fuel_base` and /// `wall_time_ms`: what the host allows, which the module's manifest can ask for but never diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6c9c7c5541..141c3524c5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -283,6 +283,7 @@ use frame::{ #[cfg(test)] use frame::{OFFSCREEN_PIXELS, Slices}; pub use geometry::region_pixels; +pub use node_checks::draws_plugin_effects; use node_checks::holds_plugin_effect; #[cfg(test)] use node_checks::painted_items; diff --git a/crates/render/src/node_checks.rs b/crates/render/src/node_checks.rs index c4c81b3373..900a59c836 100644 --- a/crates/render/src/node_checks.rs +++ b/crates/render/src/node_checks.rs @@ -1,4 +1,4 @@ -use super::{Affine, AppearanceItem, Arc, BezPath, Node, NodeKind, StrokeLayer, brush_fx, effects}; +use super::{Affine, AppearanceItem, Arc, BezPath, Document, Node, NodeKind, StrokeLayer, brush_fx, effects}; /// Most pixels from the origin that a shape handed to the rasterizer may reach, or a stroke be /// wide. A document's art stays within 4 million points, 2.6 billion pixels at the closest zoom. @@ -142,6 +142,16 @@ pub(crate) fn holds_plugin_effect(n: &Node) -> bool { holds } +/// Does `doc` draw a plug-in effect, so that installing or removing a plug-in +/// ([`effects::plugin_revision`]) can change how it draws? It does when an object in its layers, in +/// the art of its symbols or patterns, or in the art of its brushes holds one ([`holds_plugin_effect`]). +pub fn draws_plugin_effects(doc: &Document) -> bool { + let symbols = doc.symbols.iter().map(|s| &s.art); + let patterns = doc.patterns.iter().flat_map(|p| &p.art); + doc.layers.iter().chain(symbols).chain(patterns).any(|a| holds_plugin_effect(a)) + || vectorcraft_brush::library(doc).iter().any(|b| b.art().into_iter().any(holds_plugin_effect)) +} + /// A symbol instance's stain ([`vectorcraft_brush::stain`]) as bits for a cache key: its color /// model, the color's components and the amount (all 0 without a stain). pub(crate) fn stain_bits(stain: Option<(vectorcraft_color::Color, f32)>) -> [u32; 6] { diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index 3827829d05..6daf192fc4 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -425,7 +425,8 @@ impl Renderer { if !k.is_finite() || k <= 1e-12 { return; } - // The art in its own coordinates, with its own resources. + // The art in its own coordinates, with its own resources (its composite fonts included). + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&e.doc.composite_fonts); let symbols = e.doc.symbol_boxes().quick(); let visible = m.inverse().transform_rect_bbox(f.visible); let inner = Frame { doc: &e.doc, symbols: &symbols, view: f.view * m, visible, px: f.px / k, output: f.output * m, ..*f }; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index a5bfcbf26e..431e0aa97c 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -105,8 +105,11 @@ impl Renderer { } } - /// Render `doc` into a `width`×`height` image using `view` (document → pixel transform). + /// Render `doc` into a `width`×`height` image using `view` (document → pixel transform). Type + /// set in one of the document's composite fonts draws in the document's definition, also when + /// no session has registered it (a document that is not in front, or read from a file). pub fn render(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered { + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); self.render_as(doc, width, height, view, opts, false, 1) } @@ -258,8 +261,7 @@ impl Renderer { }; // `reset` keeps the threshold of the previous render: set it every time. ctx.set_aliasing_threshold(opts.anti_alias.threshold()); - let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed }; - self.raster = vello_cpu::RasterizerSettings { render_mode, ..Default::default() }; + self.raster = raster_settings(opts); if opts.artboards && !opts.outline { // Paper: white on screen, no ink on the ink planes. ctx.set_transform(f.view); @@ -340,6 +342,7 @@ impl Renderer { pub fn render_region_inks(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Vec { let (w, h) = region_pixels(region, scale); let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0)); + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); self.render_as(doc, w, h, view, opts, true, 1).pixels } @@ -356,22 +359,62 @@ impl Renderer { /// [`Self::render_node`] with `opts` (e.g. [`RenderOptions::mark_undecoded_images`]). pub fn render_node_with(&mut self, doc: &Document, n: &Arc, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option { + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); self.check_plugins(doc); self.check_symbols(doc); - let inv = view.inverse(); - let visible = inv.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); + let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); + let pixels = self.node_pixels(doc, n, (w, h), view, visible, opts, false, 1); + Some(Rendered { width: w as u32, height: h as u32, pixels }) + } + + /// Node `n` drawn into `w`×`h` transparent pixels through `view`, culled to `visible` (document + /// space); `forced` draws it whatever its visibility and bounds. With [`RenderOptions::supersample`] + /// and Art Optimized edges the art is drawn with hard edges at several times the size and + /// averaged down, and [`RenderOptions::precise`] picks the quality render mode, as in a page + /// render ([`Self::render_as`], [`Self::draw_frame`]). `cell` is as in [`Self::render_as`]. + #[allow(clippy::too_many_arguments)] + fn node_pixels( + &mut self, + doc: &Document, + n: &Arc, + (w, h): (u16, u16), + view: Affine, + visible: Rect, + opts: &RenderOptions, + forced: bool, + cell: u32, + ) -> Vec { + if opts.supersample + && opts.anti_alias == AntiAlias::Art + && let Some(k) = supersample_factor(u32::from(w), u32::from(h)) + { + let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() }; + // `supersample_factor` keeps each side within MAX_CONTEXT_SIDE, so it fits in a u16. + let (bw, bh) = (u32::from(w) * k, u32::from(h) * k); + let hairline = std::mem::replace(&mut self.hairline, f64::from(k)); + let big = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k); + self.hairline = hairline; + return downsample(&big, bw as usize, bh as usize, k as usize); + } let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); let mut ctx = single_threaded_context(w, h); ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let symbols = doc.symbol_boxes().quick(); - let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output: view, plates: None }; + let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; + let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; + let raster = std::mem::replace(&mut self.raster, raster_settings(opts)); self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); self.clip_paths.clear(); - self.draw_arc(&mut ctx, &frame, n); - let pm = self.finish(&mut ctx, vello_cpu::RasterizerSettings::default()); + if forced { + self.draw_forced_arc(&mut ctx, &frame, n); + } else { + self.draw_arc(&mut ctx, &frame, n); + } + let pm = self.finish(&mut ctx, self.raster); self.end_frame(); - Some(Rendered { width: w as u32, height: h as u32, pixels: pm.data_as_u8_slice().to_vec() }) + self.raster = raster; + pm.data_as_u8_slice().to_vec() } /// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into @@ -395,6 +438,7 @@ impl Renderer { background: Option<[u8; 4]>, opts: &RenderOptions, ) -> Option { + let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); self.check_plugins(doc); self.check_symbols(doc); let b = brush_fx::cull_bounds(&doc.symbol_boxes(), n)?; @@ -402,28 +446,7 @@ impl Renderer { // A 1-pixel margin on each side, unless the thumbnail is too small to keep one. let s = (w as f64 - 2.0).max(1.0) / b.width().max(b.height()).max(1e-6); let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2()); - let mut ctx = single_threaded_context(w, w); - ctx.set_aliasing_threshold(opts.anti_alias.threshold()); - let symbols = doc.symbol_boxes().quick(); - let frame = Frame { - mt: false, - doc, - symbols: &symbols, - view, - visible: b.inflate(1.0, 1.0), - px: 1.0 / s, - opts, - ink: Ink::Display, - output: view, - plates: None, - }; - self.begin_frame(); - (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); - self.clip_paths.clear(); - self.draw_forced_arc(&mut ctx, &frame, &Arc::new(n.clone())); - let pm = self.finish(&mut ctx, vello_cpu::RasterizerSettings::default()); - self.end_frame(); - let mut pixels = pm.data_as_u8_slice().to_vec(); + let mut pixels = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1); if let Some(bg) = background { over_background(&mut pixels, bg); } @@ -431,6 +454,12 @@ impl Renderer { } } +/// The rasterizer settings for `opts`: the quality render mode when [`RenderOptions::precise`] is set. +fn raster_settings(opts: &RenderOptions) -> vello_cpu::RasterizerSettings { + let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed }; + vello_cpu::RasterizerSettings { render_mode, ..Default::default() } +} + /// Premultiplied RGBA `pixels` drawn over the solid color `background` (`[r, g, b, a]`, straight). pub(crate) fn over_background(pixels: &mut [u8], [r, g, b, a]: [u8; 4]) { let alpha = u32::from(a); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index a12e79e867..d5c129e5c1 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -425,6 +425,29 @@ fn an_instance_is_culled_by_the_art_nested_9_slice_guides_move() { assert_eq!(img.pixel(95, 50), [255, 0, 0, 255]); } +#[test] +fn an_instance_that_only_moves_is_culled_by_the_art_its_9_slice_guides_move() { + // A symbol made in the app: art in the 20 × 20 square, a natural size of 2 × 2, and guides a + // quarter in. An instance that only moves draws it at 20 × 20, ten times its natural size. The + // bar from x −9.9 to 0.1 crosses the left guide and is placed by the middle column's map, + // x → 1.9x: moved 115 pt right, it draws from x 96.19 to 115.19 while its art box starts at + // x 105, out of view. + let mut d = Document::new(100.0, 100.0); + let bar = rect_node(&mut d, Rect::new(-9.9, -1.0, 0.1, 1.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(bar) }); + let frame = rect_node(&mut d, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::None, Paint::None, 0.0); + let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY }); + let art = Node::group(d.alloc_id(), vec![Arc::new(frame), Arc::new(inner)]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Panel".into(), art: Arc::new(art) }); + d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [2.0, 2.0] })); + d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default())); + let (id, l) = (d.alloc_id(), d.layers[0].id); + let xf = Affine::translate((115.0, 50.0)); + d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Panel".into(), xf })).unwrap(); + let img = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(img.pixel(98, 50), [255, 0, 0, 255]); +} + #[test] fn an_instance_with_a_geometry_effect_is_culled_by_its_reshaped_art() { // The art, (0, 0) to (20, 20), drawn from (-100, 10) is out of view, and the Transform effect @@ -952,6 +975,43 @@ fn node_renders_follow_the_anti_alias_option() { assert!(drawn(&thumb) && !partial(&thumb), "render_node_thumbnail_with: every alpha is 0 or 255"); } +/// Node renders follow `supersample` and `precise` as a page render does: two rectangles that meet +/// at x = 50.37 leave no seam when supersampled, and a node render gives the pixels of a page +/// render of the same art with the same options. +#[test] +fn node_renders_follow_the_supersample_and_precise_options() { + let mut d = Document::new(100.0, 100.0); + let left = rect_node(&mut d, Rect::new(10.0, 10.0, 50.37, 90.0), Paint::solid(Color::BLACK), Paint::None, 0.0); + let right = rect_node(&mut d, Rect::new(50.37, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(0.2, 0.6, 0.9)), Paint::None, 0.0); + // Blended at half opacity over both, so the group composites offscreen. + let mut over = rect_node(&mut d, Rect::new(30.0, 60.0, 70.0, 80.0), Paint::solid(Color::rgb(0.9, 0.7, 0.1)), Paint::None, 0.0); + over.opacity = 0.5; + over.blend = vectorcraft_color::BlendMode::Multiply; + let group = Node::group(d.alloc_id(), vec![Arc::new(left), Arc::new(right), Arc::new(over)]); + let l = d.layers[0].id; + d.insert(Some(l), 0, group.clone()).unwrap(); + let node = Arc::new(group.clone()); + let page = |opts: &RenderOptions| RenderOptions { background: None, artboards: false, ..opts.clone() }; + let mut r = Renderer::new(); + for (supersample, precise) in [(false, false), (true, false), (false, true), (true, true)] { + let opts = RenderOptions { supersample, precise, ..Default::default() }; + let case = format!("supersample {supersample}, precise {precise}"); + let img = r.render_node_with(&d, &node, 100, 100, Affine::IDENTITY, &opts).unwrap(); + let whole = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &page(&opts)); + assert!(img.pixels == whole.pixels, "{case}: render_node_with draws as a page render does"); + // Pixel column 50 at row 50: the black rectangle covers 37% of it and the blue one the rest. + let seam = img.pixels[(50 * 100 + 50) * 4 + 3]; + assert_eq!(seam == 255, supersample, "{case}: render_node_with seam alpha {seam}"); + // A 37-pixel thumbnail draws 0.4375 pixels a point, the seam at x = 18.66. + let thumb = r.render_node_thumbnail_with(&d, &group, 37, None, &opts).unwrap(); + let view = Affine::translate((18.5, 18.5)) * Affine::scale(0.4375) * Affine::translate((-50.0, -50.0)); + let whole = Renderer::new().render(&d, 37, 37, view, &page(&opts)); + assert!(thumb.pixels == whole.pixels, "{case}: the thumbnail draws as a page render does"); + let seam = thumb.pixels[(18 * 37 + 18) * 4 + 3]; + assert_eq!(seam == 255, supersample, "{case}: thumbnail seam alpha {seam}"); + } +} + #[test] fn opacity_mask_with_undecodable_image_leaves_out_object() { use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind, OpacityMask}; diff --git a/crates/render/src/tests/fontchange.rs b/crates/render/src/tests/fontchange.rs index 82c5c77ff7..8f6d68f575 100644 --- a/crates/render/src/tests/fontchange.rs +++ b/crates/render/src/tests/fontchange.rs @@ -138,6 +138,78 @@ fn composite_font_parts_are_not_highlighted_as_substituted_glyphs() { assert!(g.substituted_glyphs.elements().is_empty() && g.substituted_fonts.elements().is_empty()); } +/// Type in one of a document's composite fonts draws in the document's definition when nothing has +/// registered it: in a render, an ink render, a thumbnail and a placed document's art, as type set +/// in the part's font draws. +/// The font database is left without it afterwards. +#[test] +fn a_documents_own_composite_font_draws_without_being_registered() { + use vectorcraft_doc::{CompositeFont, CompositePart, CompositeParts}; + let _adding = adding_fonts(); + const NAME: &str = "CF Unregistered"; + let db = vectorcraft_text::FontDb::global(); + let typed = |family: &str| { + let mut d = Document::new(300.0, 150.0); + let style = CharStyle { size: 60.0, font_family: family.into(), ..Default::default() }; + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 100.0), "Hamburg", style)))); + let l = d.layers[0].id; + let id = d.insert(Some(l), 0, n).unwrap(); + (d, id) + }; + let (mut composite, id) = typed(NAME); + let mut parts = CompositeParts::all(CompositePart::new("Source Sans 3", "Regular")); + parts.roman = CompositePart::new("JetBrains Mono", "Regular"); + composite.composite_fonts.push(CompositeFont { name: NAME.into(), parts }); + let (plain, plain_id) = typed("JetBrains Mono"); + assert!(db.composite_font(NAME).is_none()); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::IDENTITY; + assert_eq!( + Renderer::new().render(&composite, 300, 150, view, &opts).pixels, + Renderer::new().render(&plain, 300, 150, view, &opts).pixels, + "rendered" + ); + let region = Rect::new(0.0, 0.0, 300.0, 150.0); + assert_eq!( + Renderer::new().render_region_inks(&composite, region, 1.0, &opts), + Renderer::new().render_region_inks(&plain, region, 1.0, &opts), + "rendered as ink amounts" + ); + let thumbnail = |d: &Document, id| Renderer::new().render_thumbnail(d, id, 64).map(|r| r.pixels); + assert_eq!(thumbnail(&composite, id), thumbnail(&plain, plain_id), "thumbnail"); + let placed = |d: &Document| crate::placed_document::render_inside(&mut Renderer::new(), d, &d.layers[0], 300, 150, view).map(|r| r.pixels); + assert_eq!(placed(&composite), placed(&plain), "a placed document's art"); + // A page that places the document, drawn exactly (no bitmap of the placed art). + let page = |d: &Document, id: NodeId, key: &str| { + use vectorcraft_doc::{ImageBlob, LinkInfo, PlacedDocument}; + let blob = ImageBlob::new("application/json", key.as_bytes().to_vec()); + let p = PlacedDocument { + link: LinkInfo::new("/art/type.vectorcraft"), + key: key.into(), + bounding: false, + page_box: Default::default(), + width: 300.0, + height: 150.0, + xf: Affine::IDENTITY, + placement: Default::default(), + }; + let art = d.node(id).unwrap().clone(); + vectorcraft_doc::placed_document::prime(&p, blob.bytes.clone(), (d.clone(), art, Rect::new(0.0, 0.0, 300.0, 150.0))); + let mut page = Document::new(300.0, 150.0); + page.images.insert(key.into(), blob); + let n = Node::new(page.alloc_id(), NodeKind::PlacedDocument(Box::new(p))); + let l = page.layers[0].id; + page.insert(Some(l), 0, n).unwrap(); + Renderer::new().render(&page, 300, 150, view, &opts).pixels + }; + assert_eq!( + page(&composite, id, "fontchange-composite-placed"), + page(&plain, plain_id, "fontchange-plain-placed"), + "a placed document's art drawn exactly" + ); + assert!(db.composite_font(NAME).is_none(), "given back after each render"); +} + /// Type at 80% opacity, in Multiply and with a drop shadow redraws in a font that becomes /// available: the glyph geometry kept for it is laid out again. #[test] diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index d8b267cb9e..d5e6919f0d 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -1824,6 +1824,44 @@ fn pattern_and_symbol_art_with_plugin_effects_follow_the_plugins_installed() { plugin_change_draws_as_new(with_art(d, vec![group]), ID, Some(triangle(82.0, 32.0, 10.0)), Some(triangle(82.0, 32.0, 30.0))); } +/// A document draws plug-in effects ([`draws_plugin_effects`]) when an object in its layers, in a +/// symbol's or a pattern's art, or in a brush's art has a visible plug-in effect, and not when its +/// objects have no effect, another effect or a hidden plug-in effect. +#[test] +fn a_document_draws_plugin_effects_where_any_of_its_art_has_one() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind}; + use vectorcraft_geom::shapes::rectangle; + let plugin = || effect("plugin.test.render.draws", serde_json::json!({})); + let square = |d: &mut Document, effects: Vec| { + filled(d, rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::BLACK), effects) + }; + let mut cases: Vec<(&str, Document, bool)> = vec![]; + for (name, effects, draws) in [ + ("no effect", vec![], false), + ("another effect", vec![drop_shadow()], false), + ("hidden plug-in effect", vec![vectorcraft_doc::Effect { visible: false, ..plugin() }], false), + ("plug-in effect", vec![plugin()], true), + ] { + let mut d = Document::new(200.0, 100.0); + let n = square(&mut d, effects); + cases.push((name, with_art(d, vec![n]), draws)); + } + let mut d = Document::new(200.0, 100.0); + let art = square(&mut d, vec![plugin()]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Shaped".into(), art: Arc::new(art) }); + cases.push(("symbol art", d, true)); + let mut d = Document::new(200.0, 100.0); + let art = square(&mut d, vec![plugin()]); + d.patterns.push(vectorcraft_doc::pattern::PatternDef::new("Shaped", vec![Arc::new(art)])); + cases.push(("pattern art", d, true)); + let mut d = Document::new(200.0, 100.0); + let art = square(&mut d, vec![plugin()]); + vectorcraft_brush::store(&mut d, &[Brush { name: "Shaped".into(), kind: BrushKind::Art(ArtBrush { art, ..Default::default() }) }]); + cases.push(("brush art", d, true)); + let wrong: Vec<&str> = cases.iter().filter(|(_, d, draws)| draws_plugin_effects(d) != *draws).map(|(name, ..)| *name).collect(); + assert!(wrong.is_empty(), "{wrong:?}"); +} + fn effect(id: &str, params: serde_json::Value) -> vectorcraft_doc::Effect { vectorcraft_doc::Effect { id: id.into(), params, visible: true } } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index a0fdc084ab..b5dd2299eb 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -156,8 +156,6 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if n == catalog::DOLLAR_EVAL_FILE { self.acc.feature(FeatureId::DollarEvalFile, line); self.acc.outside(OutsideId::UnseenCode, line, None); - } else if n == catalog::LOCALIZE { - self.acc.feature(FeatureId::Localize, line); } else { self.acc.feature(FeatureId::Dollar, line); } diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 50ddee3a16..7ee71c9eea 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -16,6 +16,8 @@ pub(crate) const DOLLAR_EVAL_FILE: &str = "evalFile"; // https://extendscript.docsforadobe.dev/extendscript-tools-features/user-notification-dialogs/ pub(crate) const NOTIFY: &[&str] = &["alert", "confirm", "prompt"]; +// The global function. `$.localize` is a property of `$` (the Dollar object page above), so it is +// a `$` member: // https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/ pub(crate) const LOCALIZE: &str = "localize"; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 21025a6e9a..e7ead63a4f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -35,6 +35,7 @@ const FEATURE_CASES: &[(&str, &str, &str)] = &[ ("directive.target", " //@target acme", "x(); //@target acme"), ("directive.targetengine", "#targetengine session", "var targetengine = 'session';"), ("dollar", "$.writeln('hi');", "log.writeln('hi');"), + ("dollar", "$.localize = true;", "obj.localize = true;"), ("dollar.env", "var home = $.getenv('HOME');", "var home = env.getenv('HOME');"), ("dollar.evalFile", "$.evalFile(f);", "loader.evalFile(f);"), ("dynamicCode", "eval(code);", "safe.eval(code);"), @@ -68,7 +69,6 @@ const FEATURE_CASES: &[(&str, &str, &str)] = &[ ("file.write", "Folder.temp.remove();", "cache.temp.remove();"), ("hostCheck", "if (parseInt(app.version) < 20) {}", "if (parseInt(appVersion) < 20) {}"), ("localize", "var s = localize(text);", "var s = text.localize;"), - ("localize", "var s = $.localize(text);", "var s = obj.localize(text);"), ("menuCommand", "app.executeMenuCommand('acmecopyall');", "executeMenuCommand('acmecopyall');"), ("notify", "alert('done');", "panel.alert('done');"), ("notify", "if (confirm('Go?')) {}", "function confirm(m) {}"), @@ -103,6 +103,15 @@ fn each_feature_is_found_where_it_is_and_nowhere_else() { } } +#[test] +fn the_dollar_objects_localize_property_is_not_the_global_localize_function() { + for src in ["$.localize = true;", "if ($.localize) {}", "var s = $.localize(text);"] { + let r = report(src); + assert!(feature(&r, "dollar").is_some(), "{src}: {:?}", r.features); + assert!(feature(&r, "localize").is_none(), "{src}: {:?}", r.features); + } +} + #[test] fn features_are_listed_in_alphabetical_order_of_their_ids() { let ids: Vec<&str> = FeatureId::ALL.iter().map(|f| f.id()).collect(); diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 78113dcd8c..bdabab2acd 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -160,10 +160,13 @@ pub(crate) fn font_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { /// written by `len`. pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { let mut p = Props::new(); - // Tracking and manual kerning both add space after every character. + // Tracking and manual kerning both add space after every character, in thousandths of the em + // of the font size written (the vertical scale, see `font_props`). The canvas spaces them by + // the horizontal scale: a uniform scale is the same, and `textLength` stretches type scaled + // horizontally alone, glyphs and spacing together, from the one to the other. let spacing = st.tracking + st.kerning.unwrap_or(0.0); if spacing != 0.0 { - p.push(("letter-spacing", len(spacing / 1000.0 * st.size))); + p.push(("letter-spacing", len(spacing / 1000.0 * st.size * st.v_scale / 100.0))); } if st.kerning.is_some() { // Manual kerning replaces the font's pair kerning. diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index d8cf3bcd58..8bdadb0318 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -192,49 +192,58 @@ const MAX_CLIP_DEPTH: usize = 16; /// multiply the work at every level: without this, a few lines of SVG would never finish. const MAX_CLIP_READS: usize = 1024; -/// The shapes of clip path `cp` on an element whose user space `ts` maps to the document. -pub(super) fn clip_shapes(cp: &usvg::ClipPath, ts: Affine) -> Vec<(BezPath, FillRule)> { +/// The shapes a text placeholder path in a clip path stands for (the text's glyph outlines), given +/// the path and the transform `m` that maps its user space to the document; `None` for any other +/// path. +pub(super) type ClipText<'a> = &'a dyn Fn(&usvg::Path, Affine) -> Option>; + +/// The shapes of clip path `cp` on an element whose user space `ts` maps to the document, with the +/// glyph outlines `text` gives for the text in it. +pub(super) fn clip_shapes(cp: &usvg::ClipPath, ts: Affine, text: ClipText) -> Vec<(BezPath, FillRule)> { let mut reads = MAX_CLIP_READS; - clip_shapes_depth(cp, ts, 0, &mut reads) + clip_shapes_depth(cp, ts, 0, &mut reads, text) } /// Recursively collect shapes for `cp` in document space up to `MAX_CLIP_DEPTH`, and while `reads` /// are left. -fn clip_shapes_depth(cp: &usvg::ClipPath, ts: Affine, depth: usize, reads: &mut usize) -> Vec<(BezPath, FillRule)> { +fn clip_shapes_depth(cp: &usvg::ClipPath, ts: Affine, depth: usize, reads: &mut usize, text: ClipText) -> Vec<(BezPath, FillRule)> { if depth > MAX_CLIP_DEPTH || *reads == 0 { return Vec::new(); } *reads -= 1; - fn collect(g: &usvg::Group, m: Affine, depth: usize, reads: &mut usize, out: &mut Vec<(BezPath, FillRule)>) { + fn collect(g: &usvg::Group, m: Affine, depth: usize, reads: &mut usize, text: ClipText, out: &mut Vec<(BezPath, FillRule)>) { for c in g.children() { match c { usvg::Node::Group(g) => { let m_child = m * aff(g.transform()); if let Some(child_cp) = g.clip_path() { let mut child_shapes = Vec::new(); - collect(g, m_child, depth + 1, reads, &mut child_shapes); + collect(g, m_child, depth + 1, reads, text, &mut child_shapes); if !child_shapes.is_empty() { - let clip_paths = clip_shapes_depth(child_cp, m_child, depth + 1, reads); + let clip_paths = clip_shapes_depth(child_cp, m_child, depth + 1, reads, text); intersect_shapes(&child_shapes, &clip_paths, out); } } else { - collect(g, m_child, depth, reads, out); + collect(g, m_child, depth, reads, text, out); } } - usvg::Node::Path(p) => out.push((bezpath(p.data(), m), p.fill().map(|f| rule(f.rule())).unwrap_or_default())), + usvg::Node::Path(p) => match text(p, m) { + Some(glyphs) => out.extend(glyphs), + None => out.push((bezpath(p.data(), m), p.fill().map(|f| rule(f.rule())).unwrap_or_default())), + }, _ => {} } } } let mut shapes = Vec::new(); - collect(cp.root(), ts * aff(cp.transform()), depth, reads, &mut shapes); + collect(cp.root(), ts * aff(cp.transform()), depth, reads, text, &mut shapes); if !shapes.is_empty() && depth > 0 && depth < MAX_CLIP_DEPTH && *reads > 0 && let Some(parent_cp) = cp.clip_path() { - let parent_shapes = clip_shapes_depth(parent_cp, ts, depth + 1, reads); + let parent_shapes = clip_shapes_depth(parent_cp, ts, depth + 1, reads, text); let mut intersected = Vec::new(); intersect_shapes(&shapes, &parent_shapes, &mut intersected); shapes = intersected; @@ -267,7 +276,7 @@ fn intersect_shapes(shapes: &[(BezPath, FillRule)], clips: &[(BezPath, FillRule) /// Does clip path `cp` (on an element whose user space `ts` maps to the document) leave `art`, /// placed by `xf`, whole? (Only its bounds are checked: the box must be inside a clip shape.) -pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine) -> bool { +pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine, text: ClipText) -> bool { let Some(b) = art.visual_bounds() else { return false }; if cp.clip_path().is_some() { return false; @@ -275,7 +284,7 @@ pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine) -> // Art touching the clip's edge isn't cut by it. let e = 1e-6 * (b.width() + b.height()).max(1e-9); let b = b.inflate(-e, -e); - let shapes = clip_shapes(cp, ts); + let shapes = clip_shapes(cp, ts, text); let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; corners.iter().all(|c| shapes.iter().any(|(s, _)| kurbo::Shape::contains(s, xf * *c))) } diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 6324e53809..56efe7b3a8 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -194,7 +194,7 @@ impl Importer { _ => self.named("", NodeKind::Group { children: kids, clip: false })?, }; // usvg clips a `` of a symbol to its viewport: that only counts when it cuts the art. - let whole = g.clip_path().is_none_or(|cp| uncut(cp, ts, &art, xf)); + let whole = g.clip_path().is_none_or(|cp| uncut(cp, ts, &art, xf, &|p, m| self.clip_text(p, m))); let name = match self.symbols.get(&sym) { Some(made) if whole && made.art == without_ids(&art) && made.reuse.allows(xf) => made.name.clone(), Some(_) => return None, @@ -519,7 +519,10 @@ impl Importer { } fn clip_node(&mut self, cp: &usvg::ClipPath, ts: Affine) -> Option { - let mut shapes = clip_shapes(cp, ts); + if let Some(n) = self.clip_type(cp, ts) { + return Some(n); + } + let mut shapes = clip_shapes(cp, ts, &|p, m| self.clip_text(p, m)); let id = cp.id().to_string(); if shapes.len() == 1 { let (bp, r) = shapes.pop()?; @@ -540,6 +543,53 @@ impl Importer { self.named(&id, NodeKind::Group { children, clip: false }) } + /// The glyph outlines, in the document, of the text a clip placeholder path `p` stands for (see + /// [`text`]), whose user space `m` maps to the document; nothing when the text is hidden. `None` + /// when `p` isn't a placeholder: in a clip path only its id tells (usvg paints clip path content + /// black). + fn clip_text(&self, p: &usvg::Path, m: Affine) -> Option> { + if p.id().is_empty() { + return None; + } + let i = self.slots.find(p)?; + let t = self.slots.texts.get(i)?; + if !p.is_visible() { + return Some(vec![]); + } + let mut bp = BezPath::clone(&*self.slots.outlines(i)?); + bp.apply_affine(m * self.slots.inner(p) * t.obj.xf); + let r = p.fill().map(|f| rule(f.rule())).unwrap_or_default(); + Some(if bp.elements().is_empty() { vec![] } else { vec![(bp, r)] }) + } + + /// Clip path `cp` (on an element whose user space `ts` maps to the document) as live type, when + /// all it holds is one visible text that clips by the non-zero rule and has no clip path of its + /// own: the text object with no fill or stroke, the same structure Make Clipping Mask produces + /// for type. + fn clip_type(&mut self, cp: &usvg::ClipPath, ts: Affine) -> Option { + let mut m = ts * aff(cp.transform()); + let mut kids = cp.root().children(); + while let [usvg::Node::Group(g)] = kids + && g.clip_path().is_none() + { + m *= aff(g.transform()); + kids = g.children(); + } + let [usvg::Node::Path(p)] = kids else { return None }; + if p.id().is_empty() || !p.is_visible() || p.fill().is_some_and(|f| f.rule() == usvg::FillRule::EvenOdd) { + return None; + } + let mut obj = self.slots.texts.get(self.slots.find(p)?)?.obj.clone(); + obj.xf = m * self.slots.inner(p) * obj.xf; + let grow = text::size_scale(&obj, obj.xf); + for run in &mut obj.runs { + run.style.fill = Paint::None; + run.style.stroke = Paint::None; + } + text::fold_scale(&mut obj, grow); + self.named(cp.id(), NodeKind::Text(Box::new(obj))) + } + /// One clip path child: a path, or a compound path of its subpaths when it has several. fn clip_shape(&mut self, bp: &BezPath, r: FillRule, clipping: bool) -> Option { let subs = PathData::from_bezpath(bp).subpaths; diff --git a/crates/svg/src/import/layers.rs b/crates/svg/src/import/layers.rs index 04e3887945..15a77e37f0 100644 --- a/crates/svg/src/import/layers.rs +++ b/crates/svg/src/import/layers.rs @@ -146,6 +146,7 @@ pub(super) fn inkscape_pages(xml: &roxmltree::Document, user: Affine) -> Option< show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }) .collect(); (!pages.is_empty()).then_some(pages) diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index 2502bd2bd6..904b76cd13 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -10,6 +10,13 @@ //! gradients and patterns in the text's user space; the importer swaps each placeholder for the //! [`PendingText`] it stands for. //! +//! usvg accepts only shapes, `` and `` as the children of a ``, so a `` +//! there (and a `` there that shows one) becomes a placeholder path instead, which the importer +//! finds by its id (`{prefix}{i}-…`). The importer clips by the text's glyph outlines, or uses the +//! text itself as live type. A `` in a clip path that has an id also gets the usual +//! placeholder group after its path, and a `` there with an id keeps a copy in a `` +//! after its path, for `` elements outside the clip path. +//! //! Characters keep SVG's per-character `x`/`y`/`dx`/`dy`/`rotate` lists: a character with an //! absolute `x` that moves down by at least half a line starts a new line (the leading becomes the //! line spacing), other vertical moves become baseline shift, horizontal moves become kerning (an @@ -166,14 +173,21 @@ pub(super) struct PendingText { pub(super) struct TextSlots { prefix: String, pub texts: Vec, + /// The transform between a clip placeholder path's user space and its text's, by placeholder + /// id, where the placeholder leaves it out (see [`clip_uses`]). + inner: HashMap, + /// The glyph outlines of each text laid out so far, in text space, by index. + outlines: RefCell>>, } impl TextSlots { - /// The text a placeholder's main path stands for: by its id, or inside `` instances - /// (where usvg drops ids) by its colour (the index) and its rectangle. + /// The text a placeholder's main path stands for: by its id (`{prefix}{index}`, or + /// `{prefix}{index}-{k}` for the clip placeholders), or inside `` instances (where usvg + /// drops ids) by its colour (the index) and its rectangle. pub fn find(&self, p: &usvg::Path) -> Option { if !p.id().is_empty() { - return p.id().strip_prefix(&self.prefix)?.parse().ok(); + let rest = p.id().strip_prefix(&self.prefix)?; + return rest.split_once('-').map_or(rest, |(i, _)| i).parse().ok(); } let Some(usvg::Paint::Color(c)) = p.fill().map(|f| f.paint()) else { return None }; if p.stroke().is_some() || p.data().segments().count() != 5 { @@ -185,6 +199,23 @@ impl TextSlots { let near = |a: f32, b: f64| (a as f64 - b).abs() <= 1e-3 * b.abs().max(1.0); (near(b.left(), m.x0) && near(b.top(), m.y0) && near(b.right(), m.x1) && near(b.bottom(), m.y1)).then_some(i) } + + /// The transform from the user space of clip placeholder path `p` to the space of the text it + /// stands for (the identity unless [`clip_uses`] left the text's transform out of it). + pub fn inner(&self, p: &usvg::Path) -> Affine { + self.inner.get(p.id()).copied().unwrap_or(Affine::IDENTITY) + } + + /// The glyph outlines of text `i` in text space, laid out once however many clips use it. + pub fn outlines(&self, i: usize) -> Option> { + if let Some(bp) = self.outlines.borrow().get(&i) { + return Some(bp.clone()); + } + let t = self.texts.get(i)?; + let bp = Rc::new(vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath()); + self.outlines.borrow_mut().insert(i, bp.clone()); + Some(bp) + } } /// Replace every `` usvg would draw by a placeholder group (see the module docs). @@ -200,10 +231,11 @@ pub(super) fn prepare<'s>( while xml.descendants().any(|n| n.attribute("id").is_some_and(|id| id.starts_with(&prefix))) { prefix.insert(0, '_'); } - let mut slots = TextSlots { prefix, texts: vec![] }; + let mut slots = TextSlots { prefix, ..TextSlots::default() }; let style_xml = original_xml.unwrap_or(xml); let cx = Ctx::new(style_xml, dpi); - let mut out = String::new(); + // The replacements, in source order: each element's range and what takes its place. + let mut edits: Vec<(Range, String)> = vec![]; let mut copied = 0; let is_text = |n: &XNode| { n.is_element() @@ -211,52 +243,227 @@ pub(super) fn prepare<'s>( && n.tag_name().namespace() == Some(SVG_NS) && !n.ancestors().any(|a| a.has_tag_name("style")) }; + // The slot of each text, by element, for the `` elements in clip paths below. + let mut slot_of = HashMap::new(); for (t, style_t) in xml.descendants().filter(is_text).zip(style_xml.descendants().filter(is_text)) { let label = t.attribute("id").map_or_else(|| "a text".to_string(), |id| format!("text '{id}'")); - if t.ancestors().skip(1).any(|a| a.is_element() && a.tag_name().name() == "clipPath") { + // CSS Masking Module Level 1 §6.1 (https://www.w3.org/TR/css-masking-1/#ClipPathElement): + // text is clip path content only as a child of the ``. + let clip_child = in_clip_path(t); + if !clip_child && t.ancestors().skip(1).any(|a| a.is_element() && a.tag_name().name() == "clipPath") { warnings.push(format!("{label} in a clip path ignored")); continue; } let r = t.range(); - // The element's qualified name (`text` or `svg:text`), so the placeholder lands in the same - // namespace; skip anything whose source range isn't the element itself (entity expansions). - let Some(qname) = svg - .get(r.start..r.end) - .and_then(|s| s.strip_prefix('<')) - .map(|s| s.split(|c: char| c.is_whitespace() || c == '>' || c == '/').next().unwrap_or("")) - else { - continue; - }; + let Some(q) = qualifier(svg, t) else { continue }; let flowed = t.tag_name().name() == "flowRoot"; - let Some(q) = qname.strip_suffix(t.tag_name().name()).filter(|q| q.is_empty() || q.ends_with(':')) else { continue }; if cx.css.own(style_t, "display").as_deref() == Some("none") || r.start < copied { continue; } let built = if flowed { cx.build_flow(style_t, &label, warnings) } else { cx.build(style_xml, style_t, &label, warnings) }; let Some((text, paints)) = built else { continue }; - out.push_str(&svg[copied..r.start]); - placeholder(&mut out, q, &cx.css, t, style_t, &slots.prefix, slots.texts.len(), text.marker, &paints); + let mut out = String::new(); + let index = slots.texts.len(); + if clip_child { + let id = format!("{}{index}-c", slots.prefix); + let props = clip_props(&cx.css, Some(style_t), None); + clip_placeholder(&mut out, q, &id, &own_transform(&cx.css, style_t), &props, t, text.marker); + // A `` elsewhere can still show the text by its id: the clip path leaves out this + // group (a group isn't clip path content), but the `` finds it. + if t.attribute("id").is_some() { + placeholder(&mut out, q, &cx.css, t, style_t, &slots.prefix, index, text.marker, &paints); + } + } else { + placeholder(&mut out, q, &cx.css, t, style_t, &slots.prefix, index, text.marker, &paints); + } copied = r.end; + edits.push((r, out)); + slot_of.insert(t.id(), index); slots.texts.push(text); } if slots.texts.is_empty() { return (Cow::Borrowed(svg), slots); } - out.push_str(&svg[copied..]); + clip_uses(svg, xml, style_xml, &cx, &slot_of, &mut slots, &mut edits, warnings); + edits.sort_by_key(|(r, _)| r.start); + let mut out = String::with_capacity(svg.len()); + let mut copied = 0; + for (r, s) in edits { + if r.start < copied { + continue; + } + out.push_str(svg.get(copied..r.start).unwrap_or("")); + out.push_str(&s); + copied = r.end; + } + out.push_str(svg.get(copied..).unwrap_or("")); (Cow::Owned(out), slots) } +/// Is `n` a child of a ``? +fn in_clip_path(n: XNode) -> bool { + n.parent_element().is_some_and(|p| p.tag_name().name() == "clipPath" && p.tag_name().namespace() == Some(SVG_NS)) +} + +/// The namespace prefix of element `n` as the source writes it (empty, or `svg:` and the like), so +/// what replaces it lands in the same namespace. `None` when its source range isn't the element +/// itself (entity expansions). +fn qualifier<'s>(svg: &'s str, n: XNode) -> Option<&'s str> { + let r = n.range(); + let qname = svg + .get(r.start..r.end) + .and_then(|s| s.strip_prefix('<')) + .map(|s| s.split(|c: char| c.is_whitespace() || c == '>' || c == '/').next().unwrap_or(""))?; + qname.strip_suffix(n.tag_name().name()).filter(|q| q.is_empty() || q.ends_with(':')) +} + +/// Replace each `` in a clip path that shows a text by the clip placeholder of that text, +/// placed by the `` (usvg drops ids and paints clip path content black, so the text a +/// placeholder group stands for couldn't be found again inside one). +#[allow(clippy::too_many_arguments)] +fn clip_uses( + svg: &str, + xml: &roxmltree::Document, + style_xml: &roxmltree::Document, + cx: &Ctx, + slot_of: &HashMap, + slots: &mut TextSlots, + edits: &mut Vec<(Range, String)>, + warnings: &mut Vec, +) { + let is_use = |n: &XNode| n.is_element() && n.tag_name().name() == "use" && n.tag_name().namespace() == Some(SVG_NS) && in_clip_path(*n); + if !xml.descendants().any(|n| is_use(&n)) { + return; + } + let (ids, style_ids) = (first_ids(xml), first_ids(style_xml)); + for (k, (u, style_u)) in xml.descendants().filter(is_use).zip(style_xml.descendants().filter(is_use)).enumerate() { + let Some(id) = href(u).and_then(|h| h.strip_prefix('#')) else { continue }; + let Some(t) = ids.get(id) else { continue }; + let Some(&i) = slot_of.get(&t.id()) else { continue }; + let Some(marker) = slots.texts.get(i).map(|text| text.marker) else { continue }; + let Some(q) = qualifier(svg, u) else { continue }; + // An undisplayed `` adds nothing to the clip (usvg leaves it out as it is). + if cx.css.own(style_u, "display").is_some_and(|d| d.trim() == "none") { + continue; + } + let style_t = style_ids.get(id).copied().filter(|s| s.tag_name() == t.tag_name()); + let em = cx.font_size(style_u); + let length = |a: &str, pct: f64| u.attribute(a).and_then(|v| cx.length(v, em, pct)).unwrap_or(0.0); + let (x, y) = (length("x", cx.viewport.0), length("y", cx.viewport.1)); + let placed = format!("{} translate({x} {y})", own_transform(&cx.css, style_u)); + let text_xf = match style_t { + Some(s) => own_transform(&cx.css, s), + None => t.attribute("transform").unwrap_or("").to_string(), + }; + // One element can carry one clip path. The text's own clip path is in the text's user space + // and wins; a clip path of the `` is in the ``'s, so the text's transform moves + // to the importer instead. + let clipped = |n: XNode| cx.css.own(n, "clip-path").is_some_and(|v| v.trim() != "none"); + let id = format!("{}{i}-{k}", slots.prefix); + let transform = if style_t.is_some_and(clipped) { + if clipped(style_u) { + let label = u.attribute("id").map_or_else(|| "a use of a text".to_string(), |id| format!("'{id}'")); + warnings.push(format!("clip path of {label} in a clip path ignored: the text's own applies")); + } + format!("{placed} {text_xf}") + } else { + slots.inner.insert(id.clone(), parse_transform(Some(&text_xf))); + placed + }; + let props = clip_props(&cx.css, style_t, Some(style_u)); + let mut out = String::new(); + clip_placeholder(&mut out, q, &id, &transform, &props, u, marker); + // Another `` can still show this one by its id: a copy of it stays in a ``, which + // the clip path leaves out, with the properties style rules gave it written out. + if u.attribute("id").is_some() { + use_copy(&mut out, q, &cx.css, u, style_u); + } + edits.push((u.range(), out)); + } +} + +/// Write a copy of `` `u` in a ``: its attributes in no namespace, its link as `href`, +/// and the properties set on it by rules and its `style` (from `style_u`) as its `style`. +fn use_copy(out: &mut String, q: &str, css: &Styles, u: XNode, style_u: XNode) { + let _ = write!(out, "<{q}defs><{q}use"); + for a in u.attributes().filter(|a| a.namespace().is_none() && !matches!(a.name(), "style" | "href")) { + let _ = write!(out, " {}=\"{}\"", a.name(), xml_escape(a.value())); + } + if let Some(h) = href(u) { + let _ = write!(out, " href=\"{}\"", xml_escape(h)); + } + let declared = css.declared(style_u); + let mut props: Vec<_> = declared.iter().collect(); + props.sort(); + let style: String = props.into_iter().map(|(k, v)| format!("{k}:{v};")).collect(); + let _ = write!(out, " style=\"{}\"/>", xml_escape(&style)); +} + +/// The identity transform, as a `transform` value usvg reads. +const IDENTITY: &str = "matrix(1 0 0 1 0 0)"; + +/// The transform of element `n`: a `transform` declaration in a rule or its `style` (which the +/// prepass has written in SVG syntax), else its `transform` attribute; empty when it has none. +fn own_transform(css: &Styles, n: XNode) -> String { + css.own(n, "transform").filter(|v| !v.eq_ignore_ascii_case("none")).unwrap_or_default() +} + +/// Each id of `doc` with the first element that has it (a reference goes to that one, as in usvg). +fn first_ids<'a, 'i>(doc: &'a roxmltree::Document<'i>) -> HashMap<&'a str, XNode<'a, 'i>> { + let mut ids = HashMap::new(); + for n in doc.descendants() { + if let Some(id) = n.attribute("id") { + ids.entry(id).or_insert(n); + } + } + ids +} + +/// The properties of clip path content that the placeholder of text `t` keeps, as a `style` value: +/// its `clip-path` (or that of the `` `u` showing it, when the text has none), and its +/// computed `clip-rule` and `visibility`, inherited from `u` when there is one. Every value is +/// written out, so no style rule that matches the placeholder path applies to it. +fn clip_props(css: &Styles, t: Option, u: Option) -> String { + let set = |n: XNode, p: &str| css.own(n, p).filter(|v| v.trim() != "inherit"); + let clip = |n: XNode| css.own(n, "clip-path").filter(|v| v.trim() != "none"); + let mut style = format!("clip-path:{};", t.and_then(clip).or_else(|| u.and_then(clip)).unwrap_or_else(|| "none".into())); + for (p, initial) in [("clip-rule", "nonzero"), ("visibility", "visible")] { + let v = t.and_then(|t| set(t, p)).or_else(|| u.or(t).and_then(|n| css.prop(n, p))).unwrap_or_else(|| initial.into()); + let _ = write!(style, "{p}:{v};"); + } + style +} + +/// Write the placeholder of a text in a clip path: a path over the text's bounds `b` with id `id`, +/// transform `transform`, properties `props` ([`clip_props`]) and the conditions of element `n`. +/// usvg drops a group in a clip path and paints clip path content black whatever its fill, so the +/// placeholder is a path, and the importer finds it by its id ([`TextSlots::find`]). +fn clip_placeholder(out: &mut String, q: &str, id: &str, transform: &str, props: &str, n: XNode, b: Rect) { + let _ = write!(out, "<{q}path id=\"{}\"", xml_escape(id)); + for a in ["systemLanguage", "requiredFeatures", "requiredExtensions"] { + if let Some(v) = n.attribute(a) { + let _ = write!(out, " {a}=\"{}\"", xml_escape(v)); + } + } + // In `style`, so no rule that matches the path moves it. + let transform = if transform.trim().is_empty() { IDENTITY } else { transform }; + let _ = write!(out, " style=\"transform:{};{}display:inline\"", xml_escape(transform), xml_escape(props)); + let _ = write!(out, " d=\"M{} {}H{}V{}H{}Z\"/>", b.x0, b.y0, b.x1, b.y1, b.x0); +} + /// Write the placeholder group for text `t` (namespace prefix `q`), slot `index`. #[allow(clippy::too_many_arguments)] fn placeholder(out: &mut String, q: &str, css: &Styles, t: XNode, style_t: XNode, prefix: &str, index: usize, b: Rect, paints: &[String]) { let _ = write!(out, "<{q}g"); - for a in ["id", "transform", "systemLanguage", "requiredFeatures", "requiredExtensions"] { + for a in ["id", "systemLanguage", "requiredFeatures", "requiredExtensions"] { if let Some(v) = t.attribute(a) { let _ = write!(out, " {a}=\"{}\"", xml_escape(v)); } } - // The text's own non-inherited properties, overriding any rule that matches the ``. - let mut style = String::new(); + // The text's own non-inherited properties, overriding any rule that matches the ``. The + // transform too: a `transform` declaration in a rule or `style` beats the attribute. + let transform = own_transform(css, style_t); + let mut style = format!("transform:{};", if transform.is_empty() { IDENTITY } else { &transform }); for (p, initial) in [("opacity", "1"), ("clip-path", "none"), ("mask", "none"), ("filter", "none"), ("mix-blend-mode", "normal"), ("isolation", "auto")] { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index a3ad7a069e..8a447f6c38 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -78,8 +78,11 @@ //! 64 periods). //! * `` files are read through [`ImportOptions`]: rasters stay linked, SVG files (and SVG //! `data:` URLs) become art (without their text), missing ones a placeholder keeping the link. -//! * Text lines after the first start at the first line's x; text in a clip path is ignored; -//! absolute positions inside type on a path are ignored; vertical text sets every glyph sideways. +//! * Text lines after the first start at the first line's x; absolute positions inside type on a +//! path are ignored; vertical text sets every glyph sideways. +//! * A `` in a ``, or a `` there that shows one, clips by its glyph outlines. +//! When a clip path holds only one text, and that text has no clip path of its own and no +//! even-odd clip rule, the clip group's clipping path is the text as live type that paints nothing. //! //! ## Import text //! diff --git a/crates/svg/tests/it/clip_text.rs b/crates/svg/tests/it/clip_text.rs new file mode 100644 index 0000000000..07773dd5f8 --- /dev/null +++ b/crates/svg/tests/it/clip_text.rs @@ -0,0 +1,429 @@ +//! SVG import of clip paths made of text (CSS Masking Module Level 1 §6.1, +//! https://www.w3.org/TR/css-masking-1/#ClipPathElement: `` and `` are clip path +//! content). + +use vectorcraft_color::Paint; +use vectorcraft_doc::{Document, Node, NodeKind, TextKind}; +use vectorcraft_geom::kurbo::Shape; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_svg::{ExportOptions, export, import, import_with_report}; + +fn svg(body: &str) -> String { + format!(r#"{body}"#) +} + +fn open(body: &str) -> Document { + import(&svg(body)).unwrap_or_else(|e| panic!("{e}")) +} + +/// The top-level objects of the first layer. +fn top(d: &Document) -> &[std::sync::Arc] { + d.layers[0].children().unwrap() +} + +/// The clip group `n` is, with its clipping path and the art it clips. +fn clip_group(n: &Node) -> (&Node, &[std::sync::Arc]) { + let NodeKind::Group { children, clip: true } = &n.kind else { panic!("not a clip group: {:?}", n.kind) }; + let (first, rest) = children.split_first().unwrap(); + (first, rest) +} + +/// The bounds of the region a clipping path clips to. +fn clip_bounds(clip: &Node) -> Rect { + let (bp, _) = vectorcraft_effects::clip_outline(clip).expect("the clipping path clips to something"); + bp.bounding_box() +} + +fn near(a: f64, b: f64, tol: f64) -> bool { + (a - b).abs() <= tol +} + +#[test] +fn a_text_clip_path_clips_by_the_text_as_live_type() { + let d = open( + r##"HI + "##, + ); + let objects = top(&d); + assert_eq!(objects.len(), 1, "{objects:?}"); + let (clip, art) = clip_group(&objects[0]); + assert_eq!(art.len(), 1); + assert_eq!(art[0].name.as_deref(), Some("art")); + // The clipping path is the text object with no fill or stroke, as after Make Clipping Mask. + let NodeKind::Text(t) = &clip.kind else { panic!("the clipping path is {:?}", clip.kind) }; + assert_eq!(t.plain_text(), "HI"); + assert!(t.runs.iter().all(|r| r.style.fill == Paint::None && r.style.stroke == Paint::None)); + assert!(near(t.runs[0].style.size, 100.0, 1e-9), "{}", t.runs[0].style.size); + assert!(t.xf.translation().to_point().distance(Point::new(20.0, 150.0)) < 1e-9, "{:?}", t.xf); + let p = clip.clip_paint(); + assert!(p.fill.is_none() && p.stroke.is_none(), "a clip path paints nothing"); + // It clips to the glyphs: inside the line, not the whole rectangle. + let b = clip_bounds(clip); + assert!(b.x0 >= 20.0 - 1e-6 && b.x1 < 220.0 && b.y1 <= 150.0 + 1e-6 && b.y0 > 50.0 && b.width() > 40.0, "{b:?}"); +} + +#[test] +fn text_and_shapes_in_one_clip_path_clip_to_their_union() { + let d = open( + r##"O + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let shapes = clip.clip_shapes(None); + assert_eq!(shapes.len(), 2, "the rectangle and the glyph outlines: {shapes:?}"); + let rect = shapes[0].0.bounding_box(); + assert!(near(rect.x0, 300.0, 1e-6) && near(rect.y1, 50.0, 1e-6), "{rect:?}"); + let glyphs = shapes[1].0.bounding_box(); + assert!(glyphs.x0 >= 20.0 - 1e-6 && glyphs.x1 < 120.0 && glyphs.y1 < 160.0 && glyphs.y0 > 50.0, "{glyphs:?}"); + let b = clip_bounds(clip); + assert!(near(b.x1, 350.0, 1e-6) && near(b.y0, 10.0, 1e-6), "{b:?}"); +} + +#[test] +fn a_text_clip_path_keeps_its_units_and_transforms() { + // The clip path's box units and the text's own transform place the type. + let d = open( + r##" + I + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let b = clip_bounds(clip); + // The box maps x 0.5…1 to 200…300 and y 0…1 to 100…200. + assert!(b.x0 >= 200.0 - 1e-6 && b.x1 <= 300.0 && b.y0 >= 100.0 && b.y1 <= 180.0 + 1e-6 && b.height() > 30.0, "{b:?}"); + // The clip path's transform moves it, as it moves a shape in it. + let d = open( + r##"HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(120.0, 170.0)) < 1e-9, "{:?}", t.xf); +} + +#[test] +fn a_text_clip_path_with_a_clip_rule_or_a_clip_of_its_own_clips_by_its_outlines() { + // The text's own clip path cuts its glyphs: the clip keeps their part inside the rectangle. + let d = open( + r##" + HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(!matches!(clip.kind, NodeKind::Text(_)), "outlines, as the clip of the text cuts them"); + let b = clip_bounds(clip); + assert!(b.y1 <= 120.0 + 1e-6 && b.y0 > 50.0 && b.x0 >= 20.0 - 1e-6, "{b:?}"); + // An even-odd text clip keeps its rule on the outlines. + let d = open( + r##"O + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let shapes = clip.clip_shapes(None); + assert_eq!(shapes.len(), 1); + assert_eq!(shapes[0].1, vectorcraft_geom::FillRule::EvenOdd); +} + +#[test] +fn tspans_and_type_on_a_path_clip_too() { + let d = open( + r##"AB + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.plain_text().contains('A') && t.plain_text().contains('B'), "{:?}", t.plain_text()); + let b = clip_bounds(clip); + assert!(b.y0 < 80.0 && b.y1 > 150.0, "both lines clip: {b:?}"); + + let d = open( + r##" + Around + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(matches!(t.kind, TextKind::OnPath { .. }), "{:?}", t.kind); + assert!(clip_bounds(clip).width() > 50.0); +} + +#[test] +fn a_use_of_a_text_in_a_clip_path_clips_where_the_use_places_it() { + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(20.0, 150.0)) < 1e-9, "{:?}", t.xf); + // Font-relative positions count in the ``'s font size; an undisplayed `` adds nothing. + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("only the displayed use: {:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(80.0, 120.0)) < 1e-9, "{:?}", t.xf); + // The same text drawn as well as used in a clip path. + let d = open( + r##"HI + + "##, + ); + let objects = top(&d); + assert_eq!(objects.len(), 2, "{objects:?}"); + assert!(matches!(objects[0].kind, NodeKind::Text(_))); + let (clip, _) = clip_group(&objects[1]); + let shapes = clip.clip_shapes(None); + assert_eq!(shapes.len(), 2, "{shapes:?}"); + let glyphs = shapes[0].0.bounding_box(); + assert!(glyphs.x0 >= 200.0 - 1e-6 && glyphs.y1 <= 100.0 + 1e-6 && glyphs.y0 > 40.0, "{glyphs:?}"); +} + +#[test] +fn a_clip_path_on_a_use_of_a_text_is_in_the_use_s_user_space() { + // The text's transform moves its glyphs to x 200…; the ``'s clip keeps x < 250 of its own + // user space, which the text's transform doesn't move. + let d = open( + r##" + HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let b = clip_bounds(clip); + assert!(b.x0 >= 200.0 - 1e-6 && near(b.x1, 250.0, 1e-6), "{b:?}"); + // Without a clip on the ``, the text's transform still places the type. + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(200.0, 160.0)) < 1e-9, "{:?}", t.xf); +} + +#[test] +fn a_css_transform_places_a_text_in_a_clip_path() { + let d = open( + r##" + HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(120.0, 170.0)) < 1e-9, "{:?}", t.xf); +} + +#[test] +fn css_transforms_place_a_use_of_a_text_in_a_clip_path() { + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let NodeKind::Text(t) = &clip.kind else { panic!("{:?}", clip.kind) }; + assert!(t.xf.translation().to_point().distance(Point::new(25.0, 150.0)) < 1e-9, "{:?}", t.xf); +} + +#[test] +fn a_use_refers_to_the_first_element_with_its_id() { + let d = open( + r##"HI + + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(!matches!(clip.kind, NodeKind::Text(_)), "the rectangle clips: {:?}", clip.kind); + let b = clip_bounds(clip); + assert!(near(b.x0, 300.0, 1e-6) && near(b.x1, 350.0, 1e-6) && near(b.y1, 50.0, 1e-6), "{b:?}"); +} + +#[test] +fn a_text_in_a_clip_path_can_be_shown_by_a_use_elsewhere() { + let d = open( + r##"HI + + "##, + ); + let objects = top(&d); + assert_eq!(objects.len(), 2, "{objects:?}"); + let (clip, _) = clip_group(&objects[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let mut shown = vec![]; + objects[1].walk(&mut |n: &Node| { + if let NodeKind::Text(t) = &n.kind { + shown.push(t.plain_text()); + } + }); + assert_eq!(shown, ["HI"], "the use shows the text: {:?}", objects[1]); +} + +#[test] +fn a_use_in_a_clip_path_can_be_shown_by_another_use() { + let d = open( + r##"HI + + + "##, + ); + let objects = top(&d); + assert_eq!(objects.len(), 2, "{objects:?}"); + let (clip, _) = clip_group(&objects[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let mut shown = vec![]; + objects[1].walk(&mut |n: &Node| match &n.kind { + NodeKind::Text(t) => shown.push(t.plain_text()), + NodeKind::Path { .. } => shown.push("a path".into()), + _ => {} + }); + assert_eq!(shown, ["HI"], "the other use shows the text: {:?}", objects[1]); + // A rule that styles the `` where it stands still applies to what the other use shows. + let d = open( + r##" + HI + + + "##, + ); + let objects = top(&d); + let mut at = vec![]; + objects[1].walk(&mut |n: &Node| { + if let NodeKind::Text(t) = &n.kind { + at.push(t.xf.translation().to_point()); + } + }); + assert!(at.len() == 1 && at[0].distance(Point::new(60.0, 200.0)) < 1e-9, "{at:?}"); +} + +#[test] +fn style_rules_for_paths_do_not_reach_a_text_in_a_clip_path() { + let d = open( + r##" + HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "the visible, non-zero text: {:?}", clip.kind); + // The text's own values, and those it inherits, still apply. + let d = open( + r##" + O + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let shapes = clip.clip_shapes(None); + assert_eq!(shapes.len(), 1); + assert_eq!(shapes[0].1, vectorcraft_geom::FillRule::EvenOdd); +} + +#[test] +fn a_hidden_text_alone_in_a_clip_path_is_not_live_type() { + let d = open( + r##"HI + "##, + ); + let objects = top(&d); + let clips = objects.iter().filter_map(|n| match &n.kind { + NodeKind::Group { children, clip: true } => children.first(), + _ => None, + }); + for clip in clips { + assert!(!matches!(clip.kind, NodeKind::Text(_)), "a hidden text clips nothing: {:?}", clip.kind); + } +} + +#[test] +fn a_text_left_out_by_its_conditions_clips_nothing() { + let d = open( + r##"HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let b = clip_bounds(clip); + assert!(near(b.x1, 10.0, 1e-6) && near(b.y1, 10.0, 1e-6), "only the rectangle: {b:?}"); +} + +#[test] +fn a_text_clip_on_a_symbol_instance_cuts_art_between_the_letters() { + // The art sits in the space between the two letters, inside the text's box: the glyphs cut it, + // so it stays clipped art instead of becoming an instance without the clip. + let body = |clip: &str| { + format!( + r##" + {clip} + "## + ) + }; + let instances = |d: &Document| { + let mut n = 0; + d.walk(|node| n += usize::from(matches!(node.kind, NodeKind::SymbolInstance { .. }))); + n + }; + let d = open(&body(r#"I I"#)); + assert_eq!(instances(&d), 0, "{:?}", top(&d)[0].kind); + assert!(matches!(top(&d)[0].kind, NodeKind::Group { clip: true, .. })); + // A clip around the art leaves it whole: an instance. + let d = open(&body(r#""#)); + assert_eq!(instances(&d), 1); +} + +#[test] +fn a_clip_path_clipped_by_a_text_clip_path_nests() { + let d = open( + r##"HI + + "##, + ); + let (clip, art) = clip_group(&top(&d)[0]); + assert!(matches!(clip.kind, NodeKind::Text(_)), "the outermost clip is the text: {:?}", clip.kind); + let (inner, _) = clip_group(&art[0]); + assert!(matches!(inner.kind, NodeKind::Path { clipping: true, .. }), "{:?}", inner.kind); +} + +#[test] +fn hidden_text_in_a_clip_path_clips_nothing() { + let d = open( + r##"HI + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + let b = clip_bounds(clip); + assert!(near(b.x1, 10.0, 1e-6) && near(b.y1, 10.0, 1e-6), "only the rectangle: {b:?}"); +} + +#[test] +fn text_further_down_in_a_clip_path_is_still_not_clip_path_content() { + let body = r##"No + "##; + let (_, warnings) = import_with_report(&svg(body)).unwrap(); + assert!(warnings.iter().any(|w| w.contains("in a clip path ignored")), "{warnings:?}"); +} + +#[test] +fn a_text_clip_survives_a_round_trip_through_svg_export() { + let d = open( + r##"HI + "##, + ); + let before = clip_bounds(clip_group(&top(&d)[0]).0); + let again = import(&export(&d, &ExportOptions::default())).unwrap(); + let mut clips = vec![]; + again.walk(|n| { + if let NodeKind::Group { children, clip: true } = &n.kind { + clips.push(children[0].clone()); + } + }); + assert_eq!(clips.len(), 1); + let after = clip_bounds(&clips[0]); + let tol = 0.01 * before.width().max(before.height()); + assert!( + near(after.x0, before.x0, tol) && near(after.x1, before.x1, tol) && near(after.y0, before.y0, tol) && near(after.y1, before.y1, tol), + "{before:?} → {after:?}" + ); +} diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index 7d0e08c0be..a30bc193b0 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -108,6 +108,19 @@ fn text_keeps_its_z_order_between_shapes() { assert!(t.xf.translation().to_point().distance(Point::new(5.0, 20.0)) < 1e-9); } +#[test] +fn a_css_transform_places_text() { + // A `transform` declaration in a rule or `style` beats the attribute, as on shapes. + for body in [ + r#"Moved"#, + r#"Moved"#, + ] { + let d = open(body); + let t = only_text(&d); + assert!(t.xf.translation().to_point().distance(Point::new(10.0, 40.0)) < 1e-9, "{body}: {:?}", t.xf); + } +} + #[test] fn text_keeps_its_parent_group_clip_and_mask() { let d = open( diff --git a/crates/svg/tests/it/main.rs b/crates/svg/tests/it/main.rs index 3605bd014d..09c175a37a 100644 --- a/crates/svg/tests/it/main.rs +++ b/crates/svg/tests/it/main.rs @@ -4,6 +4,7 @@ mod basic_shapes; mod blend_export; +mod clip_text; mod colorized_images; mod colour_glyphs; mod container_export; diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index adcc101f25..a031de7412 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -554,6 +554,18 @@ fn ragged_lines_keep_their_character_spacing() { } } +/// Tracking and manual kerning in type scaled uniformly, which no `textLength` stretches, take the +/// scale in a viewer as they do on the canvas. +#[test] +fn spacing_in_uniformly_scaled_type_takes_the_scale() { + for st in [ + CharStyle { h_scale: 200.0, v_scale: 200.0, tracking: 100.0, ..style(12.0) }, + CharStyle { h_scale: 150.0, v_scale: 150.0, kerning: Some(80.0), ..style(12.0) }, + ] { + assert_drawn_in_place(&area_doc(vec![run("tracked wide", st)], 280.0, Justify::Left)); + } +} + /// Type scaled horizontally before a tab is stretched to its own width, not to the tab's gap. #[test] fn scaled_type_before_a_tab_keeps_its_width() { diff --git a/crates/testkit/src/strategies.rs b/crates/testkit/src/strategies.rs index 4dbac8f6ec..10b0608001 100644 --- a/crates/testkit/src/strategies.rs +++ b/crates/testkit/src/strategies.rs @@ -502,10 +502,26 @@ pub fn param_keys(doc: &str) -> Vec { out } -/// Parameter-name keys that name filesystem paths: fuzzing these with arbitrary strings could -/// write files anywhere, so callers substitute a temp path. +/// Parameter-name keys that name a file or folder a command may write: fuzzing these with +/// arbitrary strings could write files anywhere, so callers substitute a temp path. pub fn is_path_key(k: &str) -> bool { - k == "path" + matches!(k, "path" | "diffPath") || is_folder_key(k) +} + +/// Path keys that name a folder a command creates or writes files into. +pub fn is_folder_key(k: &str) -> bool { + matches!(k, "folder" | "destinationFolder") +} + +/// The location to send under the path key `k`: `safe_path` for a file, a folder next to it for +/// a folder key. +pub fn safe_location(k: &str, safe_path: &str) -> String { + if is_folder_key(k) { format!("{safe_path}-folder") } else { safe_path.to_string() } +} + +/// `v`, or the temp location for `k` when `k` is a path key and `v` is a string. +pub fn safe_value(k: &str, v: &Value, safe_path: &str) -> Value { + if is_path_key(k) && v.is_string() { json!(safe_location(k, safe_path)) } else { v.clone() } } /// A deterministic list of junk param objects for `doc` (the command's params doc): each @@ -516,7 +532,7 @@ pub fn junk_params(doc: &str, safe_path: &str) -> Vec { let mut out = vec![Value::Null, json!([]), json!("str"), json!(42), json!({"unknownKey": 1})]; for k in &keys { for (i, v) in junk.iter().enumerate() { - let v = if is_path_key(k) && v.is_string() { json!(safe_path) } else { v.clone() }; + let v = safe_value(k, v, safe_path); // Sparse: one key at a time with every junk value, plus a few combos. let mut o = serde_json::Map::new(); o.insert(k.clone(), v.clone()); @@ -524,7 +540,7 @@ pub fn junk_params(doc: &str, safe_path: &str) -> Vec { if i % 5 == 0 { let mut all = serde_json::Map::new(); for k2 in &keys { - let v2 = if is_path_key(k2) { json!(safe_path) } else { v.clone() }; + let v2 = if is_path_key(k2) { json!(safe_location(k2, safe_path)) } else { v.clone() }; all.insert(k2.clone(), v2); } out.push(Value::Object(all)); diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 8e594c0369..15b71ae233 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -93,6 +93,34 @@ fn takes_cell(g: &SGlyph) -> bool { g.adv > 0.0 || g.face.advance(g.gid) > 0.0 } +/// Vertical type on a path: the turn that takes upright glyph `g` (of size `em`, its glyph space +/// mapped onto the path by `pre`) from its local transform `local` (`unturned` takes its Character +/// Rotation off) to the path, and where the next glyph of its cluster goes in its glyph space. +/// +/// It stands in glyph space as it stands in vertical point type's line space: a quarter turn +/// counterclockwise from horizontal path type's pose about the center of its cell, a baseline shift +/// kept across the column and a leading space taken off moving it along the path, then moved across +/// the path as a glyph lying on its side is. +fn upright_path_turn(g: &SGlyph, em: f64, pre: Affine, local: Affine, unturned: Affine, angle: f64, advance: f64) -> (Affine, f64) { + let cell = if takes_cell(g) { upright_cell(g) } else { advance }; + let (shift, unshift) = (Affine::translate((0.0, -g.bshift)), Affine::translate((0.0, g.bshift))); + let about = Point::new(cell * 0.5, -upright_centre(g, cell, em)); + let mut turn = + Affine::translate((-g.lead, g.face.ideographic_centre() * em)) * shift * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, about) * unshift; + // The effects that keep the glyph's axes fixed (Stair Step) leave its top toward the path's end on + // a path that runs to the left: it turns half a turn about its cell's center. + let tangent = Vec2::new(angle.cos(), angle.sin()); + let placed = pre * turn * local * unturned; + if (placed * Point::new(0.0, -1.0) - placed * Point::ZERO).dot(tangent) > 0.0 { + let centre = turn * shift * about; + turn = Affine::translate(centre.to_vec2() * 2.0) * Affine::scale(-1.0) * turn; + } + // Its own advance across, from where the cell centers it: where the shaper set the next glyph of + // its cluster. + let across = g.face.advance(g.gid) * g.sx; + (pre * turn, (cell - across) * 0.5 + across) +} + /// Clear the caret stops of each glyph that shares its cluster with another glyph: only a glyph /// that alone stands for its characters is a ligature. fn keep_lone_ligature_carets(glyphs: &mut [PositionedGlyph]) { @@ -137,6 +165,10 @@ struct Ctx<'a> { /// next glyph of its cluster would take, the turn it got, the line-space x that next glyph is /// set after), so that a combining mark shaped into the same cluster turns with it. upright_cluster: Option<(usize, usize, Affine, f64)>, + /// Vertical type on a path: the tate-chu-yoko block [`Self::emit`] is placing, as (the + /// block's transform from its first glyph's place on the path, the center of its em in the + /// column before that transform), so that the block's other glyphs stand with it on a curve. + tcy_block: Option<(Affine, Point)>, out: TextLayout, } @@ -329,7 +361,7 @@ impl Ctx<'_> { }; // A glyph whose leading space was taken off (mojikumi) is drawn that much earlier: an // upright one in vertical type by moving it up the column once it stands upright. - let upright = self.vertical && !self.on_path && g.tcy.is_none() && stands_upright(g); + let upright = self.vertical && g.tcy.is_none() && stands_upright(g) && !(self.on_path && g.inline.is_some()); let lead = if upright { 0.0 } else { g.lead }; let local = match &g.inline { // Inline graphics: art space to glyph space (no font outline), moved along the line by @@ -365,28 +397,75 @@ impl Ctx<'_> { let proportional = g.vpal.filter(|_| g.face.vertical_glyph(g.gid).is_some()).map_or(0.0, |a| a.advance) / g.sy; (cell + proportional, top) }); - if self.vertical && self.on_path { - // Vertical path type keeps the baseline path and turns each glyph across it. - m = Affine::rotate_about(std::f64::consts::FRAC_PI_2, origin) * m; - if let Some((cell, top)) = path_cell { - // An upright glyph whose top then faces the path's end turns half a turn about the - // center of its cell (without its Character Rotation), so that its top faces the - // path's start and the characters of an upright ligature read along the path in - // order. The effects that keep the glyph's up direction fixed already turn it so on - // a path that runs to the left. - let turned = m * unturned; - let tangent = Vec2::new(angle.cos(), angle.sin()); - let along = |y: f64| (turned * Point::new(0.0, y) - origin).dot(tangent); - if along(-top) > along(cell - top) { - let centre = turned * Point::new(g.face.advance(g.gid) * 0.5, cell * 0.5 - top); - m = Affine::translate(centre.to_vec2() * 2.0) * Affine::scale(-1.0) * m; + // Vertical type on a path: the column is centered on the line Align to Path puts the baseline + // on, so the em boxes of upright glyphs, tate-chu-yoko blocks and glyphs lying on their side + // straddle the path. Glyph space here is horizontal path type's: x runs along the path and y + // across it, to the right of the path's direction. + if let (true, true, Some(t)) = (self.vertical, self.on_path, g.tcy) { + // Tate-chu-yoko stands upright as one block: set across the column, centered on its em of + // it and on the path, its top toward the path's start, then moved by + // its Up/Down toward the path's start and by its Left/Right to the path's left, whatever + // the effect does to the glyph's axes. The block's first glyph sets where the block + // stands; the others take its em, its place on the path and its column, so the block + // stays whole on a curve. + let (block, centre) = match self.tcy_block.filter(|_| t.pen > 0.0) { + Some(b) => b, + None => { + // A later glyph without its first glyph: placed back by its pen offset. + let (em, back) = + if t.pen > 0.0 { (t.pen, Affine::translate((-t.pen, 0.0))) } else { (self.style_at(g.byte).size, Affine::IDENTITY) }; + let centre = Point::new(em * 0.5, 0.0); + let squeeze = + Affine::translate((centre.x, 0.0)) * Affine::scale_non_uniform(t.squeeze, 1.0) * Affine::translate((-centre.x, 0.0)); + let on_path = pre * back; + let mut block = on_path * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, centre) * squeeze; + // The effects that keep the glyph's axes fixed leave the block's top toward the + // path's end on a path that runs to the left: it turns half a turn about its + // center, as an upright glyph does. + let tangent = Vec2::new(angle.cos(), angle.sin()); + if (block * Point::new(centre.x, centre.y - 1.0) - block * centre).dot(tangent) > 0.0 { + block = Affine::translate((on_path * centre).to_vec2() * 2.0) * Affine::scale(-1.0) * block; + } + let left = Vec2::new(tangent.y, -tangent.x); + block = Affine::translate(-tangent * t.up + left * t.right) * block; + self.tcy_block = Some((block, centre)); + (block, centre) } + }; + let em = centre.x * 2.0; + let across = Affine::translate((centre.x - t.width * 0.5 + t.ink, centre.y + g.face.ideographic_centre() * em)); + m = block * across * local; + } else if self.vertical && self.on_path && (g.inline.is_some() || !stands_upright(g)) { + // A glyph lying on its side (and an inline graphic) is a quarter turn clockwise from an + // upright glyph, as horizontal type on the path sets it: its baseline runs along the path + // and its top faces the path's left. It moves across the path so that the center of its + // ideographic em box lies on the path. + // + // + let centre = g.face.ideographic_centre() * g.face.units_per_em() * g.sy; + m = pre * Affine::translate((0.0, centre)) * local; + } else if self.vertical && self.on_path { + // An upright glyph is turned in glyph space ([`upright_path_turn`]), so every effect bends it + // as it bends glyphs lying on their side: its top faces the path's start and the characters + // of an upright ligature read along the path in order. + let next = self.out.glyphs.len(); + let after_base = self.out.glyphs.last().is_some_and(|p| p.byte == g.byte && p.line == line && p.len > 0); + if let Some((_, _, turn, after)) = cluster.filter(|c| c.0 == g.byte && c.1 == next && after_base && g.len > 0) { + // A later glyph of an upright glyph's cluster: set after it as the shaper placed it, + // and turned with it, in its glyph space. + m = turn * Affine::translate((after, 0.0)) * local; + self.upright_cluster = Some((g.byte, next + 1, turn, after)); + } else { + let (turn, after) = upright_path_turn(g, self.style_at(g.byte).size, pre, local, unturned, angle, advance); + m = turn * local; + self.upright_cluster = (g.len > 0).then_some((g.byte, next + 1, turn, after)); } } else if let (true, Some(t)) = (self.vertical, g.tcy) { // Tate-chu-yoko: the block set across the column, centred on its em of it, then moved up // by its Up/Down and right by its Left/Right (line x runs down the column and line y - // from right to left across it). - let em = self.style_at(g.byte).size; + // from right to left across it). Every glyph of the block takes the em of its first + // glyph, the pen offset of the others. + let em = if t.pen > 0.0 { t.pen } else { self.style_at(g.byte).size }; let start = origin.x - t.pen; let centre = Point::new(start + em * 0.5, origin.y - g.face.ideographic_centre() * em); let across = Affine::translate((centre.x - t.width * 0.5 + t.ink - origin.x, 0.0)); @@ -629,6 +708,7 @@ mod emit_kashida_mark_last { system_layout: false, fractional_widths: true, upright_cluster: None, + tcy_block: None, out: TextLayout::default(), }; // Last visual glyph of the cluster: a mark that wrongly keeps the mark run (run 1). @@ -692,6 +772,7 @@ mod emit_kashida_mark_last { system_layout: false, fractional_widths: true, upright_cluster: None, + tcy_block: None, out: TextLayout::default(), }; // Simulate the pre-fix path: clone run from the mark glyph only. diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 805c4dead4..79a7ebd8d8 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -374,6 +374,7 @@ fn layout_runs(db: &FontDb, t: &TextObject, opts: &LayoutOptions, set: Option<&T system_layout: t.system_layout, fractional_widths: t.fractional_widths, upright_cluster: None, + tcy_block: None, out: TextLayout::default(), }; // Vertical type: line space turned a quarter turn clockwise (lines become columns, each next diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index aafe175310..398928ee98 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -174,6 +174,15 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, let s = style_metrics(cx.face_at(0).as_deref(), cx.style_at(0)); (s.0, s.1) }); + // Vertical type: the caret and the selection span the column, half its em on each side of the + // line Align to Path puts the baseline on. + let m = if cx.vertical { + let half = sg.iter().map(|g| g.face.units_per_em() * g.sx * 0.5).fold(f64::NAN, f64::max); + let half = if half.is_finite() { half } else { cx.style_at(0).size * 0.5 }; + (half, half) + } else { + m + }; if ap.is_empty() { cx.out.overflow = !sg.is_empty(); cx.out.lines.push(LineInfo { diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 30f8d76eb8..c94d25f897 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -136,6 +136,7 @@ fn composition_trim_stays_along_the_line_when_a_character_rotates() { system_layout: false, fractional_widths: true, upright_cluster: None, + tcy_block: None, out: TextLayout::default(), }; cx.emit(&glyph, pre, origin, angle, 30.0 - lead, 0); diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index cbc5157edd..011bb6eb20 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -49,6 +49,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout}; use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, fit_first_line, fit_source_lines, layout, layout_with, scaled}; +pub use shape::spacing_scale; pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index ae44ce433d..a58e8ef57e 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -357,6 +357,19 @@ pub(crate) fn cap_x_heights(face: Option<&FontFace>, st: &CharStyle) -> (f64, f6 (face.cap_height * k, face.x_height * k) } +/// The share of the em that tracking and manual kerning (thousandths of an em) of characters in +/// style `st` are measured in. In horizontal type that is the Horizontal Scale: they are +/// thousandths of the em as the scale draws it, so at 50% a tracking of 100 adds 0.05 em, half as +/// much as at 100%, as the page of users' `.ai` files spaces such type (and as PDF scales its +/// character and word spacing by its horizontal scaling, ISO 32000-1 §9.4.4). Baking a horizontal +/// scale of the type's transform into the Horizontal Scale then keeps the spacing. In vertical +/// type, whose advances down the column don't all take the Horizontal Scale, the em itself: 1. A +/// scale that isn't a positive number counts as 100%. +pub fn spacing_scale(st: &CharStyle, vertical: bool) -> f64 { + let hs = st.h_scale / 100.0; + if vertical || !(hs.is_finite() && hs > 0.0) { 1.0 } else { hs } +} + /// Shape `text[range]`, where `runs` gives each run's byte range in `text` and style, `inlines` /// (parallel to `runs`) the inline graphic of each run that is one, and `levels` each byte's bidi /// embedding level from `range.start` (empty: all left to right). Glyphs come out in logical @@ -736,7 +749,8 @@ fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range< let right_y = right.dy - right.bshift; let Some(left_style) = runs.get(left.run).map(|(_, s)| *s) else { continue }; let em = left.sx * left.face.upem / (left_style.h_scale / 100.0); - let tracking = left_style.tracking / 1000.0 * em; + // The tracking shaping added: thousandths of the em as its Horizontal Scale draws it. + let tracking = left_style.tracking / 1000.0 * em * spacing_scale(left_style, false); // A manual kerning value on the left glyph is part of its advance and, right to left, of // its offset too (it spaces the left glyph from its left neighbor): it is not taken off. let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv).sum::() - tracking; @@ -931,8 +945,10 @@ fn shaping_script(c: char) -> Script { /// vertical centre on the middle of the cap height raised by the inline's shift (see /// [`InlineArt`]). Its advance is the scaled art width plus tracking and its character's manual /// kerning, which right to left in horizontal type also moves the art right by the value, as it -/// moves a letter's glyph. The glyph's ascent and descent grow to the art's extent so a tall -/// graphic opens up its line. A missing symbol takes a square of the same height and draws nothing. +/// moves a letter's glyph. The art doesn't take the run's Horizontal Scale; the tracking and the +/// kerning do, as after a letter ([`spacing_scale`]). The glyph's ascent and descent grow to the +/// art's extent so a tall graphic opens up its line. A missing symbol takes a square of the same +/// height and draws nothing. #[allow(clippy::too_many_arguments)] fn inline_glyph( face: &Arc, @@ -959,8 +975,9 @@ fn inline_glyph( } _ => (kurbo::Affine::IDENTITY, h, None), }; - let tracking = st.tracking / 1000.0 * size; - let manual_kern = st.kerning.map(|v| v / 1000.0 * size).filter(|k| k.is_finite()).unwrap_or(0.0); + let spacing_em = size * spacing_scale(st, vertical); + let tracking = st.tracking / 1000.0 * spacing_em; + let manual_kern = st.kerning.map(|v| v / 1000.0 * spacing_em).filter(|k| k.is_finite()).unwrap_or(0.0); let adv = width + if tracking.is_finite() { tracking } else { 0.0 } + manual_kern; SGlyph { face: face.clone(), @@ -1063,6 +1080,9 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let km = full / face.upem; let hs = st.h_scale / 100.0; let vs = st.v_scale / 100.0; + // The em the tracking and manual kerning are thousandths of: in horizontal type, as the + // Horizontal Scale draws it ([`spacing_scale`]; the runs shaped together share the scale). + let spacing_em = size * spacing_scale(st, feats.vertical); let ascent = face.ascent * km * vs; let descent = face.descent * km * vs; let cap = face.cap_height * km * vs; @@ -1379,7 +1399,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe if ch == SOFT_HYPHEN || ch == '\u{2028}' { adv = 0.0; } else { - let manual_kern = gst.kerning.map(|v| v / 1000.0 * size).unwrap_or(0.0); + let manual_kern = gst.kerning.map(|v| v / 1000.0 * spacing_em).unwrap_or(0.0); // Manual kerning spaces a character from the next one in reading order. Right to left, // that one is drawn to its left: the cluster's glyphs move right along the baseline by // the value, so that the space its last glyph's advance gains is at the cluster's left. @@ -1387,7 +1407,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe kern_shift = manual_kern; } if last_in_cluster { - let tracking = gst.tracking / 1000.0 * size; + let tracking = gst.tracking / 1000.0 * spacing_em; adv += tracking + manual_kern; } } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 2dd3c424c6..a7a0724ee1 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -225,6 +225,46 @@ fn tracking_and_scale() { assert!(b.y1 < -4.0, "shifted up: {b:?}"); } +/// In horizontally scaled type, tracking and manual kerning are thousandths of the em as the scale +/// draws it (`spacing_scale`): at 50% they add half the space they add at 100%, after every +/// character, as the page of users' `.ai` files spaces such type. +#[test] +fn tracking_and_manual_kerning_take_the_horizontal_scale() { + let laid = + |h_scale: f64, tracking: f64, kerning: Option| layout(db(), &point("Wave", CharStyle { h_scale, tracking, kerning, ..style(20.0) })); + let advances = |l: &TextLayout| l.glyphs.iter().map(|g| g.advance).collect::>(); + let line = |l: &TextLayout| l.lines[0].x1 - l.lines[0].x0; + // 200/1000 of a 20 pt em: 4 pt after each character at 100%, 2 pt at 50%. + for (h_scale, extra) in [(100.0, 4.0), (50.0, 2.0)] { + for (name, plain, spaced) in [ + ("tracking", laid(h_scale, 0.0, None), laid(h_scale, 200.0, None)), + ("manual kerning", laid(h_scale, 0.0, Some(0.0)), laid(h_scale, 0.0, Some(200.0))), + ] { + let (a, b) = (advances(&plain), advances(&spaced)); + assert_eq!(a.len(), 4, "{name}: {a:?}"); + assert_eq!(a.len(), b.len(), "{name}"); + for (p, s) in a.iter().zip(&b) { + assert!((s - p - extra).abs() < 1e-9, "{name} at {h_scale}%: {extra} pt more after each character: {a:?} {b:?}"); + } + let longer = line(&spaced) - line(&plain); + assert!((longer - 4.0 * extra).abs() < 1e-9, "{name} at {h_scale}%: the line is {} pt longer, not {longer}", 4.0 * extra); + } + } +} + +/// The factor tracking and manual kerning take from the Horizontal Scale: the scale in horizontal +/// type, 1 in vertical type and for a scale that isn't a positive number. +#[test] +fn spacing_scale_is_the_horizontal_scale_of_horizontal_type() { + let at = |h_scale: f64, vertical: bool| spacing_scale(&CharStyle { h_scale, ..style(20.0) }, vertical); + assert_eq!(at(50.0, false), 0.5); + assert_eq!(at(250.0, false), 2.5); + assert_eq!(at(50.0, true), 1.0, "vertical type keeps the em"); + for junk in [0.0, -50.0, f64::NAN, f64::INFINITY] { + assert_eq!(at(junk, false), 1.0, "{junk}"); + } +} + #[test] fn underline_and_strikethrough_bars() { let mut t = point("ab", style(20.0)); diff --git a/crates/text/src/tests/inline.rs b/crates/text/src/tests/inline.rs index 76c90e65b6..01db5393cf 100644 --- a/crates/text/src/tests/inline.rs +++ b/crates/text/src/tests/inline.rs @@ -71,6 +71,10 @@ fn shift_tracking_and_missing_symbols() { let mut t = text("A", art(1.0), "B", 20.0); t.runs[1].style.tracking = 100.0; assert!((inline_glyph(&layout(db(), &t)).advance - 42.0).abs() < 1e-6); + // At 50% Horizontal Scale the tracking adds half as much, as after a glyph; the art keeps its + // width. + t.runs[1].style.h_scale = 50.0; + assert!((inline_glyph(&layout(db(), &t)).advance - 41.0).abs() < 1e-6); // Unresolved (missing symbol): a square of the height, nothing to draw. let t = text("A", InlineArt::new("gone"), "B", 20.0); let l = layout(db(), &t); diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index a93d1a9cd1..a1e06887a7 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -655,7 +655,7 @@ fn vertical_only_settings_keep_a_horizontal_ligature_whole() { } /// On a path, an upright ligature in vertical type stands with its top toward the path's start, and -/// its cell runs from 0.12 em before the pen to 0.88 em after it, with or without the font's vertical +/// its cell runs one em from the pen, as in vertical point type, with or without the font's vertical /// metrics. The inner stop lies at the middle of that cell, and the first character's selection ends /// there. #[test] @@ -673,21 +673,21 @@ fn an_upright_ligature_on_a_path_takes_its_stop_in_its_turned_cell() { assert!(l.on_path); let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; assert_eq!(g.carets, vec![(1, 0.5)], "{family}"); - assert!((g.width - 100.0).abs() < 1e-9 && (g.width_start + 12.0).abs() < 1e-9, "{family}: {} {}", g.width, g.width_start); + assert!((g.width - 100.0).abs() < 1e-9 && g.width_start.abs() < 1e-9, "{family}: {} {}", g.width, g.width_start); let x = |b| caret_position(&l, b).0.x - g.origin.x; - assert!((x(1) - 38.0).abs() < 1e-6, "{family}: {}", x(1)); + assert!((x(1) - 50.0).abs() < 1e-6, "{family}: {}", x(1)); let q = selection_quads(&l, 0, 1); assert_eq!(q.len(), 1, "{q:?}"); - assert!(((q[0][1] - q[0][0]).hypot() - 38.0).abs() < 1e-6, "{family}: {q:?}"); - // A baseline shift moves the turned glyph along the path, and its stop with it. - let ink = g.outline.bounding_box().x0; + assert!(((q[0][1] - q[0][0]).hypot() - 50.0).abs() < 1e-6, "{family}: {q:?}"); + // A baseline shift moves the turned glyph across the path, and leaves its stop in place. + let ink = g.outline.bounding_box(); t.runs[0].style.baseline_shift = 10.0; let l = layout(&db, &t); let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; - let moved = s.outline.bounding_box().x0 - ink; - assert!(moved.abs() > 1.0, "{family}: the shift moves the glyph along the path: {moved}"); + let moved = s.outline.bounding_box().center() - ink.center(); + assert!((moved.x.abs()) < 1e-6 && (moved.y + 10.0).abs() < 1e-6, "{family}: the shift moves the glyph to the path's left: {moved:?}"); let stop = caret_position(&l, 1).0.x - s.origin.x; - assert!((stop - 38.0 - moved).abs() < 1e-6, "{family}: {stop} against {}", 38.0 + moved); + assert!((stop - 50.0).abs() < 1e-6, "{family}: {stop}"); // Horizontal Scale widens the glyph across the path; its stop stays inside the glyph. t.runs[0].style.baseline_shift = 0.0; t.runs[0].style.h_scale = 200.0; @@ -718,7 +718,7 @@ fn an_upright_ligature_on_a_path_takes_its_stop_in_its_turned_cell() { /// On a path, an upright ligature in vertical type reads along the path in order: the top of its /// cell comes first, and its font caret (600 units down the cell) is drawn where the caret, a click /// and the selection put the stop, on a path running either way with any path effect. A glyph lying -/// on its side keeps its top toward the path's end. +/// on its side is a quarter turn clockwise from that, as horizontal type on the path sets it. #[test] fn an_upright_ligature_on_a_path_reads_along_it_in_order() { use vectorcraft_doc::PathEffect; @@ -763,8 +763,8 @@ fn an_upright_ligature_on_a_path_reads_along_it_in_order() { let (q0, q1) = (along(q[0][0]), along(q[0][1])); assert!((q0.min(q1) - drawn.min(0.0)).abs() < 1e-6 && (q0.max(q1) - drawn.max(0.0)).abs() < 1e-6, "{to} {effect:?}: {q:?} against {drawn}"); } - // Without Standard Vertical Roman Alignment the letter lies on its side: its top still faces - // the path's end and its advance runs across the path, to its right. + // Without Standard Vertical Roman Alignment the letter lies on its side: its top faces the + // path's left and its advance runs along the path. let mut line = BezPath::new(); line.move_to((0.0, 0.0)); line.line_to((1000.0, 0.0)); @@ -774,9 +774,9 @@ fn an_upright_ligature_on_a_path_reads_along_it_in_order() { let l = layout(&db, &t); let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; let tangent = Vec2::new(s.angle.cos(), s.angle.sin()); - let right = Vec2::new(-tangent.y, tangent.x); + let left = Vec2::new(tangent.y, -tangent.x); let (pen, up, ahead) = (s.xf * Point::ZERO, s.xf * Point::new(0.0, -500.0), s.xf * Point::new(500.0, 0.0)); - assert!((up - pen).dot(tangent) > 1.0 && (ahead - pen).dot(right) > 1.0, "{pen:?} {up:?} {ahead:?}"); + assert!((up - pen).dot(left) > 1.0 && (ahead - pen).dot(tangent) > 1.0, "{pen:?} {up:?} {ahead:?}"); } /// On a path, an upright ligature whose cell Proportional Metrics shortens (`vpal`, from 1000 units diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 4b8bdbc09e..4790b642af 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -66,6 +66,24 @@ fn optical_pairs_cross_paint_runs_and_manual_and_tracking_are_independent() { assert!((pair_advance(&rtl_manual) - pair_advance(&rtl_pair_zero) - 20.0).abs() < 0.01, "manual spacing changes the adjacent right-to-left pair"); } +/// At 50% Horizontal Scale the tracking adds half the space it adds at 100% (`spacing_scale`), +/// and the Optical pairs measure their gaps without it: tracked, each advance is the untracked +/// Optical one and the tracking, the corrections unchanged. +#[test] +fn optical_pairs_in_horizontally_scaled_type_measure_without_the_scaled_tracking() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, h_scale: 50.0, ..CharStyle::default() }; + let advances = |st: CharStyle| layout(db(), &TextObject::point(Point::ZERO, "IIAV", st)).glyphs.iter().map(|g| g.advance).collect::>(); + let optical = advances(st.clone()); + let unkerned = advances(CharStyle { kerning: Some(0.0), ..st.clone() }); + assert!((optical[0] - unkerned[0]).abs() > 0.1, "Optical changes the monospaced pair at 50%: {optical:?} {unkerned:?}"); + let tracked = advances(CharStyle { tracking: 100.0, ..st }); + assert_eq!(optical.len(), tracked.len()); + for (o, t) in optical.iter().zip(&tracked) { + // 100/1000 of the 100 pt em drawn 50% wide. + assert!((t - o - 5.0).abs() < 0.01, "{optical:?} {tracked:?}"); + } +} + #[test] fn rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order() { for optical_kerning in [false, true] { diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index 225395d348..2bc1c2ff70 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -184,6 +184,304 @@ fn type_on_a_path_stays_horizontal() { assert!(!layout(FontDb::global(), &t).vertical); } +/// `text` in vertical type on a straight path from `from` to `to`, with path effect `effect`. +fn on_vertical_path(text: &str, from: (f64, f64), to: (f64, f64), effect: vectorcraft_doc::PathEffect) -> TextObject { + let mut t = vertical(text); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new(from, to).to_path(0.1)), start: 0.0, end: None }; + t.path_effect = effect; + t +} + +/// Glyph `i`'s top (its ascender direction) and its own advance direction in text space, as unit +/// vectors. +fn top_and_ahead(l: &TextLayout, i: usize) -> (Vec2, Vec2) { + let g = &l.glyphs[i]; + let pen = g.xf * Point::ZERO; + let unit = |v: Vec2| v / v.hypot(); + (unit(g.xf * Point::new(0.0, -500.0) - pen), unit(g.xf * Point::new(500.0, 0.0) - pen)) +} + +/// On a vertical path with Rainbow, an upright glyph's top faces the path's start, and a letter lying +/// on its side is a quarter turn clockwise from it: its top faces the path's left and its baseline +/// runs along the path. Both turn with the path when it runs the other way. The effects that keep +/// the glyphs' axes fixed on the page keep that relation only on a path that runs to the right. +#[test] +fn on_a_vertical_path_letters_lie_a_quarter_turn_clockwise_from_upright_glyphs() { + use vectorcraft_doc::PathEffect; + for to in [(0.0, 1000.0), (0.0, -1000.0), (1000.0, 0.0), (-1000.0, 0.0), (700.0, 700.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§L", (0.0, 0.0), to, PathEffect::Rainbow)); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let left = Vec2::new(tangent.y, -tangent.x); + let (upright, _) = top_and_ahead(&l, 0); + let (side, ahead) = top_and_ahead(&l, 1); + assert!((upright + tangent).hypot() < 1e-6, "{to:?}: the upright top faces the start: {upright:?}"); + // A clockwise quarter turn with y down takes (x, y) to (-y, x). + assert!((side - Vec2::new(-upright.y, upright.x)).hypot() < 1e-6, "{to:?}: {side:?} against {upright:?}"); + assert!((side - left).hypot() < 1e-6 && (ahead - tangent).hypot() < 1e-6, "{to:?}: {side:?} {ahead:?}"); + } + // Skew, 3D Ribbon and Stair Step keep axes of the glyphs fixed on the page: on a path that runs + // to the right the relation holds. On one that runs to the left, Skew and 3D Ribbon mirror both + // kinds, and Stair Step keeps letters level while upright glyphs still face the path's start, so + // letters are a quarter turn counterclockwise from upright glyphs there. + for effect in [PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep] { + for to in [(1000.0, 0.0), (700.0, 700.0), (0.0, 1000.0), (0.0, -1000.0), (-1000.0, 0.0), (-700.0, 300.0)] { + // Skew and 3D Ribbon slant glyphs on a slanted path, where no turn relates them exactly. + if to.1 != 0.0 && effect != PathEffect::StairStep { + continue; + } + let l = layout(FontDb::global(), &on_vertical_path("§L", (0.0, 0.0), to, effect)); + let (upright, _) = top_and_ahead(&l, 0); + let (side, _) = top_and_ahead(&l, 1); + let clockwise = to.0 >= 0.0; + let want = if clockwise { Vec2::new(-upright.y, upright.x) } else { Vec2::new(upright.y, -upright.x) }; + assert!((side - want).hypot() < 1e-6, "{effect:?} {to:?}: {side:?} against {upright:?}"); + } + } +} + +/// On a vertical path, letters lying on their side are set as horizontal type on the same path sets +/// them, with every path effect and on a path running either way, and they follow one another along +/// the path without overlapping where the effect keeps them square to it. +#[test] +fn on_a_vertical_path_letters_keep_the_horizontal_path_pose() { + use vectorcraft_doc::PathEffect; + for effect in [PathEffect::Rainbow, PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep, PathEffect::Gravity] { + for to in [(1000.0, 0.0), (-1000.0, 0.0), (700.0, 300.0)] { + let mut vertical = on_vertical_path("LLl", (0.0, 0.0), to, effect); + let v = layout(FontDb::global(), &vertical); + vertical.vertical = false; + let h = layout(FontDb::global(), &vertical); + for i in 0..3 { + let (a, b) = (v.glyphs[i].xf.as_coeffs(), h.glyphs[i].xf.as_coeffs()); + assert!(a.iter().zip(b).take(4).all(|(a, b)| (a - b).abs() < 1e-9), "{effect:?} {to:?} glyph {i}: {a:?} against {b:?}"); + } + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let span = |i: usize| { + let along = v.glyphs[i].outline.elements().iter().filter_map(|el| el.end_point()).map(|p| p.to_vec2().dot(tangent)); + along.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), d| (lo.min(d), hi.max(d))) + }; + // Skew slants the letters, Stair Step keeps them level and Gravity fans them toward the + // path's center, so their ink can reach past the next letter's. + if matches!(effect, PathEffect::Rainbow | PathEffect::Ribbon3d) { + assert!((0..2).all(|i| span(i).1 <= span(i + 1).0 + 1e-6), "{effect:?} {to:?}: {:?}", (0..3).map(span).collect::>()); + } + } + } +} + +/// On a vertical path, the column is centered on the path: the em boxes of upright glyphs, of letters +/// lying on their side and of a tate-chu-yoko block straddle it, their centers on the path line, on +/// a path running any way. +#[test] +fn on_a_vertical_path_the_column_is_centered_on_the_path() { + use vectorcraft_doc::PathEffect; + let Some(face) = FontDb::global().face("Source Sans 3", "Regular") else { panic!("the bundled face") }; + let (em, centre) = (face.units_per_em(), face.ideographic_centre()); + for to in [(0.0, 1000.0), (0.0, -1000.0), (1000.0, 0.0), (-700.0, 700.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§H12§", (0.0, 0.0), to, PathEffect::Rainbow)); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let across = |p: Point| p.to_vec2().dot(Vec2::new(tangent.y, -tangent.x)); + // An upright glyph (the shaper centers a narrow one in its em box, as off a path) has its + // ink centered on the path. + for i in [0, 4] { + let mid = across(ink(&l, i).center()); + assert!(mid.abs() < 1.0, "{to:?}: upright glyph {i} is {mid} off the path"); + } + // A letter lying on its side: its em box's center is `centre` em above its baseline. + let mid = across(l.glyphs[1].xf * Point::new(0.0, -centre * em)); + assert!(mid.abs() < 1e-6, "{to:?}: the letter's em box is {mid} off the path"); + // The digits of the block stand side by side across the path, the block centered on it. + let block = (across(ink(&l, 2).center()) + across(ink(&l, 3).center())) * 0.5; + assert!(block.abs() < 1.5, "{to:?}: the block is {block} off the path"); + } +} + +/// On a vertical path, the caret and the selection span the column, half its em on each side of the +/// path, as the glyphs do. +#[test] +fn on_a_vertical_path_the_caret_and_selection_span_the_column() { + use vectorcraft_doc::PathEffect; + for to in [(0.0, 1000.0), (1000.0, 0.0), (-700.0, 700.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§L§", (0.0, 0.0), to, PathEffect::Rainbow)); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let across = |p: Point| p.to_vec2().dot(Vec2::new(tangent.y, -tangent.x)); + let (top, bottom) = caret_position(&l, "§".len()); + assert!((across(top) - 10.0).abs() < 1e-6 && (across(bottom) + 10.0).abs() < 1e-6, "{to:?}: caret {top:?} {bottom:?}"); + for q in selection_quads(&l, 0, "§L§".len()) { + let (lo, hi) = q.iter().map(|p| across(*p)).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), a| (lo.min(a), hi.max(a))); + assert!((lo + 10.0).abs() < 1e-6 && (hi - 10.0).abs() < 1e-6, "{to:?}: highlight from {lo} to {hi}"); + } + } +} + +/// On a straight path running down from the anchor, vertical type sets every glyph where vertical +/// point type sets it: upright glyphs with a horizontal scale stay centered on the column, a baseline +/// shift moves an upright glyph across the column, every upright glyph keeps its own cell along the +/// path, and a combining mark stays on its upright letter. +#[test] +fn on_a_downward_vertical_path_glyphs_sit_where_vertical_point_type_sets_them() { + use crate::test_fonts::{VERTICAL_FAMILY, vertical_font}; + let run = |text: &str, style: CharStyle| TextRun { text: text.into(), style, inline: None }; + let runs = |plain: CharStyle| { + vec![ + run("§×", plain.clone()), + run("§", CharStyle { h_scale: 150.0, ..plain.clone() }), + run("§", CharStyle { baseline_shift: 3.0, ..plain.clone() }), + run("§", CharStyle { rotation: 30.0, ..plain.clone() }), + run("L", CharStyle { h_scale: 150.0, ..plain.clone() }), + run("L", CharStyle { baseline_shift: 3.0, ..plain.clone() }), + run("q\u{301}x", CharStyle { standard_vertical_roman: true, ..plain.clone() }), + run("§", plain), + ] + }; + let compare = |db: &FontDb, point: &TextObject, name: &str| { + let mut on_path = point.clone(); + on_path.kind = + TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (0.0, 3000.0)).to_path(0.1)), start: 0.0, end: None }; + let (p, v) = (layout(db, point), layout(db, &on_path)); + assert_eq!(p.glyphs.len(), v.glyphs.len(), "{name}"); + let apart: Vec<_> = (p.glyphs.iter().zip(&v.glyphs).enumerate()) + .filter(|(_, (a, b))| a.xf.as_coeffs().iter().zip(b.xf.as_coeffs()).any(|(a, b)| (a - b).abs() > 1e-6)) + .map(|(i, (a, b))| format!("glyph {i}: {:?} on the path, {:?} in point type", b.xf.as_coeffs(), a.xf.as_coeffs())) + .collect(); + assert!(apart.is_empty(), "{name}: {apart:#?}"); + }; + let mut point = vertical(""); + point.runs = runs(CharStyle { size: 20.0, ..CharStyle::default() }); + compare(FontDb::global(), &point, "the bundled face"); + // A face with vertical metrics, whose cells hang from their vertical origins. + let db = FontDb::with_font_dirs(vec![]); + db.add_font(vertical_font(true).unwrap()); + point.runs = runs(CharStyle { size: 20.0, font_family: VERTICAL_FAMILY.into(), ..CharStyle::default() }); + compare(&db, &point, "vertical metrics"); + // The horizontally scaled upright glyph is wider across the column, centered where the plain one is. + point.kind = TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (0.0, 3000.0)).to_path(0.1)), start: 0.0, end: None }; + let l = layout(&db, &point); + let (plain, wide) = (ink(&l, 0), ink(&l, 2)); + assert!(wide.width() > plain.width() * 1.4 && (wide.center().x - plain.center().x).abs() < 1e-6, "{plain:?} {wide:?}"); +} + +/// With Skew on a curved vertical path, every glyph's axis along the path follows the tangent and +/// its axis across the path stays upright on the page: an upright glyph's top runs back along the +/// tangent and its own x axis points up the page, and a letter lying on its side keeps its top up +/// the page and its baseline along the tangent. +#[test] +fn on_a_curved_vertical_path_skew_keeps_the_axis_across_the_path_upright() { + use vectorcraft_doc::PathEffect; + let mut arc = kurbo::BezPath::new(); + arc.move_to((0.0, 0.0)); + arc.curve_to((40.0, 0.0), (80.0, 40.0), (80.0, 120.0)); + let mut t = vertical("§L§L§"); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&arc), start: 0.0, end: None }; + t.path_effect = PathEffect::Skew; + let l = layout(FontDb::global(), &t); + let page_up = Vec2::new(0.0, -1.0); + for (i, g) in l.glyphs.iter().enumerate() { + let tangent = Vec2::new(g.angle.cos(), g.angle.sin()); + let (top, ahead) = top_and_ahead(&l, i); + if i % 2 == 0 { + assert!((top + tangent).hypot() < 1e-6 && (ahead - page_up).hypot() < 1e-6, "upright glyph {i}: {top:?} {ahead:?} at {tangent:?}"); + } else { + assert!((top - page_up).hypot() < 1e-6 && (ahead - tangent).hypot() < 1e-6, "letter {i}: {top:?} {ahead:?} at {tangent:?}"); + } + } + let turns = l.glyphs.iter().map(|g| g.angle).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), a| (lo.min(a), hi.max(a))); + assert!(turns.1 - turns.0 > 0.3, "the glyphs sit on the curve: {turns:?}"); +} + +/// A tate-chu-yoko block whose characters differ in size stays one block: every character stands on +/// the block's baseline in the em of its first character, in vertical type and on a vertical path. +#[test] +fn a_tate_chu_yoko_block_of_mixed_sizes_shares_its_first_characters_em() { + let run = |text: &str, size: f64| TextRun { text: text.into(), style: CharStyle { size, ..CharStyle::default() }, inline: None }; + let mut t = vertical(""); + t.runs = vec![run("§", 20.0), run("1", 20.0), run("2", 10.0), run("§", 20.0)]; + let mut on_path = t.clone(); + on_path.kind = + TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (0.0, 1000.0)).to_path(0.1)), start: 0.0, end: None }; + for (name, t) in [("vertical", &t), ("on a path", &on_path)] { + let l = layout(FontDb::global(), t); + assert!(l.glyphs[2].advance == 0.0, "{name}: 12 is one block: {:?}", l.glyphs.iter().map(|g| g.advance).collect::>()); + let (one, two) = (ink(&l, 1), ink(&l, 2)); + assert!((one.y1 - two.y1).abs() < 0.5 && two.center().x > one.center().x, "{name}: on one baseline: {one:?} {two:?}"); + } +} + +/// On a vertical path, Tate-chu-yoko Settings Up/Down move a marked block toward the path's start +/// and Left/Right move it to the right of its upright characters (the path's left), with every +/// effect on a path running any way. +#[test] +fn on_a_vertical_path_tate_chu_yoko_settings_keep_their_directions() { + use vectorcraft_doc::PathEffect; + for effect in [PathEffect::Rainbow, PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep, PathEffect::Gravity] { + for to in [(1000.0, 0.0), (-1000.0, 0.0), (0.0, 1000.0), (-700.0, -700.0)] { + let at = |up: f64, right: f64| { + let marked = CharStyle { size: 20.0, tate_chu_yoko: true, tcy_up_down: up, tcy_left_right: right, ..CharStyle::default() }; + let mut t = on_vertical_path("", (0.0, 0.0), to, effect); + t.runs = vec![ + TextRun { text: "§".into(), style: CharStyle { size: 20.0, ..CharStyle::default() }, inline: None }, + TextRun { text: "12".into(), style: marked, inline: None }, + ]; + ink(&layout(FontDb::global(), &t), 1).center().to_vec2() + }; + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let left = Vec2::new(tangent.y, -tangent.x); + let (plain, up, right) = (at(0.0, 0.0), at(4.0, 0.0), at(0.0, 3.0)); + assert!((up - plain + tangent * 4.0).hypot() < 1e-6, "{effect:?} {to:?}: Up/Down moved it {:?}", up - plain); + assert!((right - plain - left * 3.0).hypot() < 1e-6, "{effect:?} {to:?}: Left/Right moved it {:?}", right - plain); + } + } +} + +/// On a vertical path, a tate-chu-yoko block stands upright like the glyphs around it: its digits +/// read across the column, their tops toward the path's start, centered on the column. +#[test] +fn on_a_vertical_path_tate_chu_yoko_stands_upright() { + use vectorcraft_doc::PathEffect; + for to in [(0.0, 1000.0), (0.0, -1000.0), (1000.0, 0.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§12§", (0.0, 0.0), to, PathEffect::Rainbow)); + assert!(l.glyphs[1].outline.elements().len() > 1, "{to:?}: the 1 draws"); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + let left = Vec2::new(tangent.y, -tangent.x); + let (upright, _) = top_and_ahead(&l, 0); + for i in [1, 2] { + let (top, ahead) = top_and_ahead(&l, i); + assert!((top - upright).hypot() < 1e-6 && (ahead - left).hypot() < 1e-6, "{to:?} digit {i}: {top:?} {ahead:?}"); + } + let centre = |i: usize| ink(&l, i).center().to_vec2(); + let (one, two) = (centre(1), centre(2)); + assert!((two - one).dot(left) > 3.0 && (two - one).dot(tangent).abs() < 1.0, "{to:?}: 12 side by side: {one:?} {two:?}"); + let across = |v: Vec2| v.dot(left); + let block = (across(one) + across(two)) * 0.5; + assert!((block - across(centre(0))).abs() < 2.0, "{to:?}: the block is centered on the column: {block} against {}", across(centre(0))); + let (before, after) = ((centre(0)).dot(tangent), (centre(3)).dot(tangent)); + assert!(before < one.dot(tangent) && one.dot(tangent) < after, "{to:?}: the block stands between the marks"); + } + // On a curve the block stays whole: both digits turn alike and stand on one baseline. + let mut arc = kurbo::BezPath::new(); + arc.move_to((0.0, 0.0)); + arc.curve_to((0.0, 40.0), (20.0, 60.0), (60.0, 60.0)); + let mut t = vertical("§12§"); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&arc), start: 0.0, end: None }; + let l = layout(FontDb::global(), &t); + let (a, b) = (l.glyphs[1].xf.as_coeffs(), l.glyphs[2].xf.as_coeffs()); + assert!(a.iter().zip(b).take(4).all(|(a, b)| (a - b).abs() < 1e-9), "{a:?} against {b:?}"); + let (top, ahead) = top_and_ahead(&l, 1); + let (p1, p2) = (l.glyphs[1].xf * Point::ZERO, l.glyphs[2].xf * Point::ZERO); + assert!((p2 - p1).dot(top).abs() < 1e-6 && (p2 - p1).dot(ahead) > 3.0, "{p1:?} {p2:?}"); + // With every effect, on a path running either way, the block's top faces the path's start. + for effect in [PathEffect::Rainbow, PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep, PathEffect::Gravity] { + for to in [(1000.0, 0.0), (-1000.0, 0.0)] { + let l = layout(FontDb::global(), &on_vertical_path("§12§", (0.0, 0.0), to, effect)); + let tangent = Vec2::new(to.0, to.1) / Vec2::new(to.0, to.1).hypot(); + for i in [1, 2] { + let (top, _) = top_and_ahead(&l, i); + assert!(top.dot(tangent) < -0.5, "{effect:?} {to:?} digit {i}: {top:?}"); + } + } + } +} + #[test] fn three_digits_stand_across_the_column_squeezed_into_one_em() { let l = layout(FontDb::global(), &vertical("§100§")); @@ -343,6 +641,20 @@ fn tracking_spaces_upright_marks_without_moving_them_off_the_centre_line() { assert!((step - 24.0).abs() < 1e-6, "one em plus 200/1000 em of tracking: {step}"); } +/// Vertical type keeps its tracking in thousandths of the em itself at any Horizontal Scale +/// (`spacing_scale`): its advances down the column don't all take the scale. +#[test] +fn vertical_tracking_keeps_the_em_at_any_horizontal_scale() { + let step = |h_scale: f64, tracking: f64| { + let l = layout(FontDb::global(), &vertical_styled("§§", CharStyle { size: 20.0, h_scale, tracking, ..CharStyle::default() })); + ink(&l, 1).center().y - ink(&l, 0).center().y + }; + for h_scale in [100.0, 50.0] { + let more = step(h_scale, 200.0) - step(h_scale, 0.0); + assert!((more - 4.0).abs() < 1e-6, "{h_scale}%: 200/1000 of the 20 pt em: {more}"); + } +} + /// Baseline shift moves an upright glyph across the column, as it moves a letter lying on its /// side, at any Character Rotation, and leaves its neighbors where they are. The glyph turns about /// its shifted pen position (`xf * pivot`), and `xf * unturned` places the shifted glyph without diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index 4ee448830d..68c19cc676 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -548,8 +548,8 @@ impl Tool for SmartPenTool { } /// A path being drawn: Escape ends it. - fn ends_on_escape(&self, _cx: &ToolContext) -> bool { - self.path.is_some() + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.active(cx).is_some() } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 53fbd3f3f5..7a3d3de765 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -5,8 +5,8 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use serde_json::{Value, json}; use vectorcraft_doc::{ - Node, - dimension::{self, Dimension, DimensionMode, DimensionOptions, DimensionSource, PointRef, SegmentRef}, + Node, NodeId, + dimension::{self, Dimension, DimensionMode, DimensionOptions, DimensionSource, FreePoint, Orientation, PointRef, SegmentRef}, }; use vectorcraft_geom::{BezPath, Point, Vec2}; @@ -69,6 +69,42 @@ pub struct DimensionTool { snapped: Option<(Point, Option)>, /// Whether the press under way began on an anchor a Linear click picks. press_on_anchor: bool, + /// The second point clicked for the Linear dimension being placed, and where the pointer was + /// for that click (a snap or Shift can move the point away from it): placed with the pointer + /// still at either, it is aligned. + second: Option<(Point, Point)>, +} + +/// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is +/// placed (VectorCraft's own rule). Beside the points, where the nearest point of the line +/// through them lies between them, the dimension is aligned: it measures the distance between +/// them. Past either point it measures along an axis. The line through the points and the +/// perpendicular at that point bound a quarter on each side; the pointer's quarter holds either +/// the straight up or down direction, which gives the horizontal distance, or the straight left +/// or right direction, which gives the vertical distance. Points on one horizontal or vertical +/// line only give an aligned dimension. +fn orientation_at(a: Point, b: Point, p: Point) -> Orientation { + let u = b - a; + let len = u.hypot(); + if len < 1e-9 { + return Orientation::Aligned; + } + let along = (p - a).dot(u) / (len * len); + if (0.0..=1.0).contains(&along) { + return Orientation::Aligned; + } + // Out past the nearer point, and the side of the line the pointer is on. + let (out, side) = (if along > 1.0 { u } else { -u }, u.cross(p - a)); + let axes = [ + (Vec2::new(0.0, 1.0), Orientation::Horizontal), + (Vec2::new(0.0, -1.0), Orientation::Horizontal), + (Vec2::new(1.0, 0.0), Orientation::Vertical), + (Vec2::new(-1.0, 0.0), Orientation::Vertical), + ]; + let within = len * 1e-9; + axes.into_iter() + .find(|(axis, _)| axis.dot(out) > within && u.cross(*axis).abs() > within && u.cross(*axis) * side > 0.0) + .map_or(Orientation::Aligned, |(_, orientation)| orientation) } /// How near an anchor (screen pixels) a pick snaps to it. @@ -177,6 +213,30 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { (q.x.is_finite() && q.y.is_finite()).then_some(q) } +/// What a dimension between two picked points links to. A point on an anchor links to the anchor. +/// A point on a segment keeps its place along the segment. Any other point is held +/// against the anchors of the path under it, or, with no path under it, the path of the other +/// point, so that it moves with that path. None when neither point has a path to link to. +fn points_source(cx: &ToolContext, (a, ra): (Point, &Option), (b, rb): (Point, &Option)) -> Option { + let (edge_a, edge_b) = (pick(cx, a), pick(cx, b)); + let node = |r: &Option, e: &Option| r.as_ref().map(|r| r.node).or_else(|| e.as_ref().map(|e| e.node)); + let (path_a, path_b) = (node(ra, &edge_a), node(rb, &edge_b)); + let free = |p: Point, r: &Option, edge: &Option, own: Option, other: Option| { + if r.is_some() { + return None; + } + edge.as_ref().and_then(|e| FreePoint::on_segment(cx.doc, e, p)).or_else(|| own.or(other).and_then(|node| FreePoint::on(cx.doc, node, p))) + }; + let (free_a, free_b) = (free(a, ra, &edge_a, path_a, path_b), free(b, rb, &edge_b, path_b, path_a)); + (ra.is_some() || rb.is_some() || free_a.is_some() || free_b.is_some()).then(|| DimensionSource::Points { + a: ra.clone(), + b: rb.clone(), + vertex: None, + free_a, + free_b, + }) +} + impl DimensionTool { /// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as /// a link to its path); else where Smart Guides put it (another object's anchor or centre, in @@ -214,7 +274,18 @@ impl DimensionTool { } } fn recipe(&self, mode: DimensionMode, a: Point, b: Point, vertex: Point, source: Option) -> Dimension { - Dimension { mode, a, b, vertex, offset: 0.0, length: a.distance(b), options: self.style.clone(), source, moved: None } + Dimension { + mode, + a, + b, + vertex, + offset: 0.0, + length: a.distance(b), + options: self.style.clone(), + source, + orientation: Orientation::Aligned, + moved: None, + } } /// The dimension a target gives when dragged from. fn dimension_for(&self, target: &Target, p: Point) -> Option { @@ -247,6 +318,9 @@ impl DimensionTool { if let Some(source) = &d.source { p["source"] = json!(source); } + if d.orientation != Orientation::Aligned { + p["orientation"] = json!(d.orientation); + } p } fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec { @@ -256,6 +330,18 @@ impl DimensionTool { { d.mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter }; } + if d.mode == DimensionMode::Linear { + // The points the dimension measures: a dragged segment's ends, read from the art. + let ends = match &d.source { + Some(DimensionSource::Segment { edge }) => edge.endpoints(cx.doc), + _ => Some((d.a, d.b)), + }; + let again = self.second.is_some_and(|(at, pointer)| at.distance(p).min(pointer.distance(p)) <= cx.tol(ANCHOR_REACH)); + d.orientation = match ends { + Some((a, b)) if !again => orientation_at(a, b, p), + _ => Orientation::Aligned, + }; + } d.place(p); if d.resolve(cx.doc).is_err() { return vec![]; @@ -287,6 +373,7 @@ impl DimensionTool { self.began = false; self.snap.clear(); self.snapped = None; + self.second = None; } /// A plain click: picks a point or a line, or measures a circle's radius. fn click(&mut self, cx: &ToolContext, p: Point, target: Option, mods: Mods) -> Vec { @@ -301,9 +388,10 @@ impl DimensionTool { } self.points.push((at, reference)); if let [(a, ra), (b, rb)] = self.points.as_slice() { - let source = (ra.is_some() || rb.is_some()).then(|| DimensionSource::Points { a: ra.clone(), b: rb.clone(), vertex: None }); + let source = points_source(cx, (*a, ra), (*b, rb)); let mut d = self.recipe(DimensionMode::Linear, *a, *b, Point::ZERO, source); if d.resolve(cx.doc).is_ok() { + self.second = Some((*b, p)); self.pending = Some(d); } self.points.clear(); @@ -603,7 +691,7 @@ mod tests { let d = t.pending.as_ref().expect("both anchors were picked"); assert_eq!((d.a, d.b), (Point::new(100.0, 100.0), Point::new(200.0, 200.0))); let anchor = |anchor| Some(PointRef { node: id, subpath: 0, anchor }); - assert_eq!(d.source, Some(DimensionSource::Points { a: anchor(0), b: anchor(2), vertex: None })); + assert_eq!(d.source, Some(DimensionSource::Points { a: anchor(0), b: anchor(2), vertex: None, free_a: None, free_b: None })); // Dragged past the anchor's reach, the press drags out the dimension of a segment there. let mut t = DimensionTool::default(); t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); @@ -613,6 +701,66 @@ mod tests { assert!(matches!(t.pointer(&c, &ev(PointerKind::Up, 100.0, 60.0)).last(), Some(Action::Commit))); } + /// A point picked on a segment, not on an anchor, keeps its place along the segment. A point + /// off the art is held against the anchors of the other point's path. Both then follow the + /// path, as the anchor at the other end does. + #[test] + fn points_off_anchors_are_held_against_the_path() { + use vectorcraft_doc::dimension::FreePoint; + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let click = |t: &mut DimensionTool, x: f64, y: f64| { + t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y)); + }; + let mut t = DimensionTool::default(); + click(&mut t, 100.0, 100.0); + click(&mut t, 200.0, 150.0); + let pending = t.pending.as_ref().expect("both points were picked"); + let anchor = Some(PointRef { node: id, subpath: 0, anchor: 0 }); + let Some(DimensionSource::Points { a, b: None, vertex: None, free_a: None, free_b: Some(FreePoint::OnSegment { edge, t }) }) = + &pending.source + else { + panic!("{:?}", pending.source) + }; + assert_eq!((a, edge), (&anchor, &SegmentRef { node: id, subpath: 0, segment: 1 })); + assert!((t - 0.5).abs() < 1e-9, "{t}"); + let mut t = DimensionTool::default(); + click(&mut t, 400.0, 400.0); + click(&mut t, 200.0, 200.0); + let pending = t.pending.as_ref().expect("both points were picked"); + let Some(DimensionSource::Points { free_a: Some(free), b: Some(b), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + let FreePoint::Anchors { node, anchors, across } = free else { panic!("{free:?}") }; + assert_eq!((*node, anchors.len(), *across, b.node, b.anchor), (id, 3, 0.0, id, 2)); + let at = free.position(&d).expect("the anchors that hold it exist"); + assert!(at.distance(pending.a) < 1e-9, "{at:?} {:?}", pending.a); + } + + /// A point that Smart Guides put in line with the path's center is held, where the guide put + /// it, against the anchors of the path at the other end. + #[test] + fn a_point_smart_guides_place_is_held_against_the_path() { + use vectorcraft_doc::dimension::FreePoint; + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + assert!(c.smart_guides); + let mut t = DimensionTool::default(); + for (x, y) in [(200.0, 200.0), (151.5, 330.0)] { + t.pointer(&c, &PointerEvent::new(PointerKind::Move, x, y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y)); + } + let pending = t.pending.as_ref().expect("both points were picked"); + assert!((pending.b.x - 150.0).abs() < 1e-9, "in line with the center: {:?}", pending.b); + let Some(DimensionSource::Points { a: Some(a), free_b: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{free:?}"); + assert_eq!(a.node, id); + let at = free.position(&d).expect("the anchors that hold it exist"); + assert!(at.distance(pending.b) < 1e-9, "{at:?} {:?}", pending.b); + } + /// The anchors of a live rectangle are picked the same way. #[test] fn a_press_on_a_live_shapes_anchor_picks_it() { @@ -655,6 +803,47 @@ mod tests { assert_eq!(t.points, vec![corner]); } + /// Beside the two points the dimension is aligned; past either point it is horizontal when + /// the pointer's quarter holds the straight up or down direction and vertical when it holds + /// the straight left or right direction. Points on one horizontal or vertical line, a pointer + /// on the line through the points, and two equal points give aligned. + #[test] + fn the_pointer_chooses_aligned_horizontal_or_vertical() { + use Orientation::{Aligned, Horizontal, Vertical}; + let at = |a: (f64, f64), b: (f64, f64), p: (f64, f64)| orientation_at(Point::new(a.0, a.1), Point::new(b.0, b.1), Point::new(p.0, p.1)); + // A line rising to the right (y grows downwards), and the same points in the other order. + for (a, b) in [((100.0, 300.0), (200.0, 200.0)), ((200.0, 200.0), (100.0, 300.0))] { + for (p, want) in [ + ((120.0, 160.0), Aligned), + ((200.0, 300.0), Aligned), + ((150.0, 250.0), Aligned), + ((200.0, 200.0), Aligned), + ((100.0, 300.0), Aligned), + ((210.0, 120.0), Horizontal), + ((240.0, 150.0), Horizontal), + ((280.0, 220.0), Vertical), + ((240.0, 170.0), Vertical), + ((40.0, 310.0), Vertical), + ((90.0, 380.0), Horizontal), + ((250.0, 150.0), Aligned), + ] { + assert_eq!(at(a, b, p), want, "{a:?} to {b:?}, pointer at {p:?}"); + } + } + // A line falling to the right. + let (a, b) = ((100.0, 100.0), (300.0, 200.0)); + for (p, want) in + [((200.0, 50.0), Aligned), ((320.0, 300.0), Horizontal), ((400.0, 210.0), Vertical), ((60.0, 20.0), Horizontal), ((20.0, 90.0), Vertical)] + { + assert_eq!(at(a, b, p), want, "pointer at {p:?}"); + } + for (a, b) in [((100.0, 100.0), (300.0, 100.0)), ((100.0, 100.0), (100.0, 300.0)), ((100.0, 100.0), (100.0, 100.0))] { + for p in [(50.0, 50.0), (350.0, 50.0), (350.0, 350.0), (50.0, 350.0), (200.0, 60.0), (60.0, 200.0), (400.0, 100.0), (100.0, 400.0)] { + assert_eq!(at(a, b, p), Aligned, "{a:?} to {b:?}, pointer at {p:?}"); + } + } + } + #[test] fn placement_press_previews_without_a_prior_move() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 495e932a4b..e4811418c7 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -782,8 +782,10 @@ impl Tool for GestureTool { }; let color = if self.id == "eraser" { [0x80, 0x80, 0x80] } else { FEEDBACK }; // A tip that is not round shows the outline of the area it covers, each step of the drag - // as wide as the pen pressed there with Size set to Pressure. - if matches!(self.id, "eraser" | "blobBrush") && self.roundness < 100.0 && !self.smoothing { + // as wide as the pen pressed there with Size set to Pressure. So does a round Blob Brush + // tip: a line as wide as the brush would end square, where the stroke it adds is round at + // both ends (#4343). + if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || self.id == "blobBrush") && !self.smoothing { let area = |pts: &[Point], size| { if self.id == "blobBrush" { blob_area(pts, size, self.angle, self.roundness) diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index c0ef91d240..a0fe487289 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -382,6 +382,36 @@ fn blob_brush_drag_shows_scrub_length_measurement_labels() { assert!(!quiet.overlays(&off).iter().any(|o| matches!(o, Overlay::Measure { .. }))); } +/// #4343: while it is dragged, a round Blob Brush shows the outline of the area `path.blob` adds, +/// which reaches half the brush beyond the ends of the stroke (round tips), not a line as wide as +/// the brush that ends square at them. +#[test] +fn blob_brush_preview_is_the_outline_of_the_area_with_round_tips() { + use vectorcraft_geom::kurbo::Shape; + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = GestureTool::new("blobBrush"); + t.size = 20.0; + assert_eq!(t.roundness, 100.0, "a round tip by default"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 300.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 300.0)); + let outlines: Vec<_> = + t.overlays(&cx).into_iter().filter_map(|o| if let Overlay::Path { path, width, .. } = o { Some((path, width)) } else { None }).collect(); + assert!(outlines.iter().all(|(_, width)| f64::from(*width) < t.size / 2.0), "no line as wide as the brush: {outlines:?}"); + // The stroke's outline is the widest one (the tip at the pointer is another). + let Some((path, _)) = outlines.iter().max_by(|a, b| a.0.bounding_box().width().total_cmp(&b.0.bounding_box().width())) else { + panic!("no outline") + }; + let b = path.bounding_box(); + assert!((b.x0 - 40.0).abs() < 0.5 && (b.x1 - 160.0).abs() < 0.5, "round tips reach half the size past the ends: {b:?}"); + assert!((b.y0 - 290.0).abs() < 0.5 && (b.y1 - 310.0).abs() < 0.5, "{b:?}"); + // Round, not square: the corner of the box a square-ended line would fill is outside the area. + assert!(!path.contains(vectorcraft_geom::Point::new(41.0, 291.0))); + assert!(path.contains(vectorcraft_geom::Point::new(45.0, 300.0))); +} + /// The Blob Brush has Keep selected and Merge only with selection, both off by default, and its /// stroke sends both. #[test] diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index 123c4b1efc..4f8e867a54 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -3,9 +3,10 @@ //! Flare: drag sets the center and its size and turns the rays as the pointer moves up or down //! (Shift holds their turn; click without dragging opens the Flare Tool Options), then a click //! sets the end point of the rings; Space held during either drag moves the flare. The rest comes -//! from the tool's options (the Flare Tool Options, which last). Reshape: drag a point of a -//! selected path; the engine's `path.reshape` adds an anchor there if needed and moves the -//! neighbourhood smoothly. +//! from the tool's options (the Flare Tool Options, which last). Reshape: a click on a selected +//! path sets a focal point (adding an anchor on a segment), Shift-click adds or removes more, and +//! a drag from a focal point moves them all; the engine's `path.reshape` stretches the selected +//! anchors between them and the anchors that stay. use serde_json::{Value, json}; use vectorcraft_geom::{Point, Vec2}; @@ -268,27 +269,142 @@ impl Tool for FlareTool { } } -/// Reshape Tool: drag a point on a selected path. +/// Where a Reshape press landed on a selected path. +#[derive(Clone, Copy, Debug, PartialEq)] +enum ReshapeHit { + /// On an anchor: (subpath, anchor). + Anchor(usize, usize), + /// On a segment, away from its anchors: (subpath, the index of the anchor `path.reshape` adds + /// there). + Segment(usize, usize), +} + +impl ReshapeHit { + /// The anchor the press grabs, as `(subpath, anchor)` once any anchor has been added. + fn anchor(self) -> (usize, usize) { + match self { + Self::Anchor(si, ai) | Self::Segment(si, ai) => (si, ai), + } + } + + /// Where the anchor `r` is once the press has added its anchor: one further on after an + /// anchor added before it on its subpath. + fn renumber(self, r: (usize, usize)) -> (usize, usize) { + match self { + Self::Segment(si, added) if r.0 == si && r.1 >= added => (r.0, r.1.saturating_add(1)), + _ => r, + } + } +} + +/// A Reshape press: the path, the point on it, what it landed on and whether Shift was held. +#[derive(Clone, Debug)] +struct ReshapePress { + id: vectorcraft_doc::NodeId, + at: Point, + hit: ReshapeHit, + shift: bool, + /// The drag so far. + d: Vec2, + /// The other focal points the drag moves, found when it starts, before the preview moves them. + others: Vec<((usize, usize), Point)>, +} + +/// How near a focal point's stored position an anchor must be to be that focal point. An anchor +/// added on a segment lies where the curve's point was found, to within rounding. +const FOCAL_MATCH: f64 = 1e-6; + +/// A focal point: its `(subpath, anchor)` and where that anchor lies. +type FocalPoint = ((usize, usize), Point); + +/// Reshape Tool: a click on a selected path makes the anchor or the point on a segment there the +/// focal point (on a segment it adds an anchor), Shift-click adds or removes more, and a drag +/// moves the focal points with the drag and stretches the selected anchors around them. #[derive(Default)] pub struct ReshapeTool { - /// (path, grab point) while dragging. - grab: Option<(vectorcraft_doc::NodeId, Point)>, + /// The press, until the button is released. + press: Option, began: bool, /// Pointer and offset readout while a reshape drag is in progress. measure: Option<(Point, String)>, + /// The focal points the tool highlighted: their path, and each one's `(subpath, anchor)` and + /// where that anchor lies. An anchor the tool adds before one renumbers it. A focal point + /// whose anchor no longer lies there (another edit moved or removed it) shows nothing and + /// moves nothing. + focal: Option<(vectorcraft_doc::NodeId, Vec)>, } impl ReshapeTool { - /// The selected path under `p` (Reshape works on selected paths only, like Illustrator). - fn hit(cx: &ToolContext, p: Point) -> Option<(vectorcraft_doc::NodeId, Point)> { + /// The selected path under `p` (Reshape works on selected paths only), the point on it and + /// what the point is. + fn hit(cx: &ToolContext, p: Point) -> Option<(vectorcraft_doc::NodeId, Point, ReshapeHit)> { let tol = cx.tol(4.0); - let editable = cx.doc.editable(); - cx.selection.objects.iter().copied().filter(|id| editable(*id)).find_map(|id| { + Self::paths(cx).into_iter().find_map(|id| { let pd = cx.doc.node(id)?.path_data()?; - let (_, _, _, q, d) = pd.nearest(p)?; - (d <= tol).then_some((id, q)) + let (si, seg, _, q, d) = pd.nearest(p)?; + if d > tol { + return None; + } + // `path.reshape` takes the anchor within `tol` of the point on the path. + let anchor = pd + .subpaths + .get(si)? + .anchors + .iter() + .enumerate() + .map(|(i, a)| (i, a.p.distance(q))) + .filter(|&(_, dist)| dist <= tol) + .min_by(|a, b| a.1.total_cmp(&b.1)); + Some(match anchor { + Some((ai, _)) => (id, pd.subpaths.get(si)?.anchors.get(ai)?.p, ReshapeHit::Anchor(si, ai)), + // `SubPath::insert_anchor` puts the new anchor after the segment's first anchor. + None => (id, q, ReshapeHit::Segment(si, seg.saturating_add(1))), + }) }) } + + /// The paths Reshape works on: the selected paths that can be edited, in selection order. + fn paths(cx: &ToolContext) -> Vec { + let editable = cx.doc.editable(); + cx.selection.objects.iter().copied().filter(|&id| editable(id) && cx.doc.node(id).is_some_and(|n| n.path_data().is_some())).collect() + } + + /// The highlighted focal points of path `id` as `(subpath, anchor)`, with their positions: the + /// anchors of the path that lie where the tool stored them. None while Reshape does not work + /// on the path. + fn focal_points(&self, cx: &ToolContext, id: vectorcraft_doc::NodeId) -> Vec<((usize, usize), Point)> { + let Some((fid, points)) = &self.focal else { return vec![] }; + if *fid != id || !Self::paths(cx).contains(&id) { + return vec![]; + } + let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { return vec![] }; + let mut out: Vec<((usize, usize), Point)> = vec![]; + for &((si, ai), p) in points { + let here = pd.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p); + if let Some(q) = here.filter(|q| q.distance(p) <= FOCAL_MATCH) + && !out.iter().any(|(o, _)| *o == (si, ai)) + { + out.push(((si, ai), q)); + } + } + out + } + + /// The focal points other than the pressed point that a drag from `press` moves: all the + /// highlighted ones when the press is on one of them, else none (Shift only keeps the drag's + /// angle). + fn dragged_focal(&self, cx: &ToolContext, press: &ReshapePress) -> Vec<((usize, usize), Point)> { + let focal = self.focal_points(cx, press.id); + let pressed = |r: &(usize, usize)| matches!(press.hit, ReshapeHit::Anchor(si, ai) if (si, ai) == *r); + if focal.iter().any(|(r, _)| pressed(r)) { focal.into_iter().filter(|(r, _)| !pressed(r)).collect() } else { vec![] } + } + + /// `path.reshape`'s params for `press` dragged by `d`. + fn params(cx: &ToolContext, press: &ReshapePress, d: Vec2) -> Value { + let others: Vec<[usize; 2]> = press.others.iter().map(|&((si, ai), _)| [si, ai]).collect(); + // `focal` is sent when empty too: without it, `path.reshape` follows the earlier rule. + json!({ "id": press.id.0, "x": press.at.x, "y": press.at.y, "dx": d.x, "dy": d.y, "tol": cx.tol(4.0), "focal": others }) + } } impl Tool for ReshapeTool { @@ -296,18 +412,19 @@ impl Tool for ReshapeTool { "reshape" } fn busy(&self) -> bool { - self.grab.is_some() + self.press.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { match ev.kind { PointerKind::Down => { - self.grab = Self::hit(cx, ev.pos); + self.press = + Self::hit(cx, ev.pos).map(|(id, at, hit)| ReshapePress { id, at, hit, shift: ev.mods.shift, d: Vec2::ZERO, others: vec![] }); self.began = false; self.measure = None; vec![] } PointerKind::Drag => { - let Some((id, at)) = self.grab else { return vec![] }; + let Some(at) = self.press.as_ref().map(|p| p.at) else { return vec![] }; let mut d: Vec2 = ev.pos - at; if ev.mods.shift { d = vectorcraft_geom::constrain_angle_from(d, 45.0, cx.constrain_angle); @@ -318,25 +435,58 @@ impl Tool for ReshapeTool { return out; } self.began = true; + let others = self.press.as_ref().map(|p| self.dragged_focal(cx, p)).unwrap_or_default(); + if let Some(p) = self.press.as_mut() { + p.others = others; + } out.push(Action::Begin("Reshape".into())); } + let Some(press) = self.press.as_mut() else { return out }; + press.d = d; self.measure = cx.measurement_labels.then(|| (ev.pos + Vec2::new(cx.tol(12.0), cx.tol(12.0)), cx.offset_label(d.x, d.y))); - out.push(Action::Preview( - "path.reshape".into(), - json!({ "id": id.0, "x": at.x, "y": at.y, "dx": d.x, "dy": d.y, "tol": cx.tol(4.0) }), - )); + out.push(Action::Preview("path.reshape".into(), Self::params(cx, press, d))); out } PointerKind::Up => { - self.grab = None; self.measure = None; - if std::mem::take(&mut self.began) { vec![Action::Commit] } else { vec![] } + let Some(press) = self.press.take() else { return vec![] }; + if std::mem::take(&mut self.began) { + // The focal points move with the whole drag, the grabbed point too, and are + // renumbered after an anchor added on a segment. + let mut points: Vec<((usize, usize), Point)> = press.others.iter().map(|&(r, p)| (press.hit.renumber(r), p + press.d)).collect(); + points.push((press.hit.anchor(), press.at + press.d)); + self.focal = Some((press.id, points)); + return vec![Action::Commit]; + } + // A click: the point becomes the focal point, or with Shift is added to them or, + // when it is one already, removed. + let mut points: Vec<((usize, usize), Point)> = if press.shift { self.focal_points(cx, press.id) } else { vec![] }; + let mut out = vec![]; + match press.hit { + ReshapeHit::Anchor(si, ai) => { + let before = points.len(); + points.retain(|&(r, _)| r != (si, ai)); + if points.len() == before { + points.push(((si, ai), press.at)); + } + } + ReshapeHit::Segment(..) => { + // A reshape by no distance adds the anchor and keeps the selection as it is. + out.push(Action::Exec("path.reshape".into(), Self::params(cx, &press, Vec2::ZERO))); + for (r, _) in &mut points { + *r = press.hit.renumber(*r); + } + points.push((press.hit.anchor(), press.at)); + } + } + self.focal = (!points.is_empty()).then_some((press.id, points)); + out } _ => vec![], } } fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { - if key == ToolKey::Escape && self.grab.take().is_some() { + if key == ToolKey::Escape && self.press.take().is_some() { self.measure = None; if std::mem::take(&mut self.began) { return vec![Action::Cancel]; @@ -344,17 +494,30 @@ impl Tool for ReshapeTool { } vec![] } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.focal = None; + self.measure = None; + if self.press.take().is_some() && std::mem::take(&mut self.began) { vec![Action::Cancel] } else { vec![] } + } fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = vec![]; + // Each focal point: a filled anchor square inside a larger hollow one. + if let Some((id, _)) = &self.focal { + let color = cx.doc.layer_color(*id); + for (_, p) in self.focal_points(cx, *id) { + out.push(Overlay::Anchor { p, color, filled: false, size: 10.0 }); + out.push(Overlay::Anchor { p, color, filled: true, size: 5.0 }); + } + } if cx.measurement_labels && let Some((p, t)) = &self.measure { - vec![Overlay::Measure { p: *p, text: t.clone() }] - } else { - vec![] + out.push(Overlay::Measure { p: *p, text: t.clone() }); } + out } fn cursor(&self, cx: &ToolContext, p: Point, _mods: Mods) -> Cursor { - if self.grab.is_some() || Self::hit(cx, p).is_some() { Cursor::Move } else { Cursor::Arrow } + if self.press.is_some() || Self::hit(cx, p).is_some() { Cursor::Move } else { Cursor::Arrow } } } diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index e4039e6d9c..c50889d030 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -1194,6 +1194,47 @@ impl Targets { (d, ov, held.contains(&true)) } + /// [`Self::snap_moved_to_rulers`] for a selection a move Shift keeps to its line (through the + /// grabbed point `p`, along `dir`), its bounds now `r`: the edge or centre of `r` that a ruler + /// guide runs past within `tol` goes onto it by sliding along the line, the way needing the + /// shortest slide winning and at most twice `tol` (a line nearly parallel to a guide would + /// carry the selection far to meet it). Returns the shift along the line and the guides. + pub(crate) fn snap_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64) -> (Vec2, Vec) { + let len = dir.hypot(); + if !len.is_finite() || len <= 1e-9 { + return (Vec2::ZERO, vec![]); + } + let u = dir / len; + // The way along the line, where the guide is and where it starts, and whether it is upright. + let mut best: Option<(f64, f64, Point, bool)> = None; + for (vertical, c) in [(true, u.x), (false, u.y)] { + if c.abs() <= 1e-9 { + continue; + } + let vs = if vertical { [r.x0, r.center().x, r.x1] } else { [r.y0, r.center().y, r.y1] }; + let (mid, half) = + if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) }; + for (t, from, _) in self.rulers.iter().filter(|g| g.vertical == vertical).filter_map(|g| g.line_at(mid, tol + half)) { + for v in vs { + let s = (t - v) / c; + if (t - v).abs() <= tol && s.abs() <= 2.0 * tol && best.is_none_or(|b| s.abs() < b.0.abs()) { + best = Some((s, t, from, vertical)); + } + } + } + } + let Some((s, t, from, vertical)) = best else { return (Vec2::ZERO, vec![]) }; + let moved = r + u * s; + let line = if vertical { + self.line(Point::new(t, from.y.min(moved.y0)), Point::new(t, from.y.max(moved.y1))) + } else { + self.line(Point::new(from.x.min(moved.x0), t), Point::new(from.x.max(moved.x1), t)) + }; + let mut ov: Vec = line.into_iter().collect(); + ov.extend(self.label(p + u * s, "align")); + (u * s, ov) + } + /// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for /// dragging `handle` of the box `bx` (about the centre when `from_center`), in the box's own /// frame, and so is the result. The handle lands on an anchor or centre within `tol` on the page diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 4994104656..c34f9ab7de 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -22,6 +22,25 @@ fn snaps_to_anchor_and_alignment() { assert_eq!(p.y, 200.0); } +/// #4312: a Shift move slides the selection along its line onto a ruler guide, but not far to +/// meet one a nearly parallel line only reaches a long way off. +#[test] +fn a_slide_along_a_line_lands_the_bounds_on_a_ruler_guide_within_reach() { + let t = Targets { rulers: vec![Ruler { vertical: true, pos: 300.0, span: None }], ..Targets::default() }; + let r = Rect::new(248.0, 10.0, 298.0, 40.0); + let p = Point::new(270.0, 25.0); + // Level: the right edge is 2 short of the guide, which is the way along the line. + assert_eq!(t.snap_moved_along_to_rulers(p, r, Vec2::new(1.0, 0.0), 4.0).0, Vec2::new(2.0, 0.0)); + // On the diagonal it is 2.8 along. + let (d, ov) = t.snap_moved_along_to_rulers(p, r, Vec2::new(1.0, 1.0), 4.0); + assert!((d - Vec2::new(2.0, 2.0)).hypot() < 1e-9 && !ov.is_empty(), "{d:?}"); + // Nearly upright, it would take about 118 along the line to meet the guide. + assert_eq!(t.snap_moved_along_to_rulers(p, r, Vec2::new(0.017, 1.0), 4.0).0, Vec2::ZERO); + // A guide of an artboard needs the selection to run past it. + let bounded = Targets { rulers: vec![Ruler { vertical: true, pos: 300.0, span: Some((100.0, 200.0)) }], ..Targets::default() }; + assert_eq!(bounded.snap_moved_along_to_rulers(p, r, Vec2::new(1.0, 0.0), 4.0).0, Vec2::ZERO); +} + #[test] fn rect_snap_aligns_edges() { let (d, id) = doc_with_rect(); diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index bc564fced3..b70a160d8a 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -243,8 +243,8 @@ impl Tool for PenTool { self.drag.is_some() || self.handle.is_some() || self.convert.is_some() } /// A path being drawn: Escape ends it. - fn ends_on_escape(&self, _cx: &ToolContext) -> bool { - self.path.is_some() + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.active(cx).is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let tol = cx.tol(5.0).max(cx.point_tol()); diff --git a/crates/tools/src/rulerguide.rs b/crates/tools/src/rulerguide.rs index 87822f070a..3297769382 100644 --- a/crates/tools/src/rulerguide.rs +++ b/crates/tools/src/rulerguide.rs @@ -167,6 +167,8 @@ pub struct NewGuide { vertical: bool, /// The artboard (index) it belongs to: an artboard guide. artboard: Option, + /// Made only within its artboard ([`Self::within`]). + within: bool, snap: GuideSnap, /// The preview's orientation and position (none off the canvas), and the pointer. at: Option<(bool, f64)>, @@ -177,7 +179,24 @@ impl NewGuide { /// A vertical guide out of the left ruler, else a horizontal one out of the top ruler; an /// artboard guide of `artboard`, if any. pub fn new(cx: &ToolContext, vertical: bool, artboard: Option) -> Self { - Self { vertical, artboard, snap: GuideSnap::new(cx), at: None, pointer: Point::ZERO } + Self { vertical, artboard, within: false, snap: GuideSnap::new(cx), at: None, pointer: Point::ZERO } + } + + /// An artboard guide of `artboard` that shows, and is made, only where it lies within that + /// artboard: a vertical guide between its left and right edges, a horizontal one between its + /// top and bottom. With no such artboard, it never shows and nothing is made. + pub fn within(cx: &ToolContext, vertical: bool, artboard: usize) -> Self { + Self { within: true, ..Self::new(cx, vertical, Some(artboard)) } + } + + /// May the guide go at `at` (the x of a vertical guide, the y of a horizontal one)? + fn fits(&self, cx: &ToolContext, vertical: bool, at: f64) -> bool { + if !self.within { + return true; + } + let Some(r) = self.artboard.and_then(|i| cx.doc.artboards.get(i)).map(|a| a.rect) else { return false }; + let (lo, hi) = if vertical { (r.min_x(), r.max_x()) } else { (r.min_y(), r.max_y()) }; + lo <= at && at <= hi } /// The pointer at `ev`, over the canvas or not (`on_canvas`): the actions that show the guide @@ -185,9 +204,13 @@ impl NewGuide { pub fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent, on_canvas: bool) -> Vec { let mut out = vec![]; self.pointer = ev.pos; - if on_canvas { - let vertical = self.vertical != ev.mods.alt; - let at = self.snap.snap(cx, vertical, if vertical { ev.pos.x } else { ev.pos.y }, ev.mods.shift); + let place = on_canvas + .then(|| { + let vertical = self.vertical != ev.mods.alt; + (vertical, self.snap.snap(cx, vertical, if vertical { ev.pos.x } else { ev.pos.y }, ev.mods.shift)) + }) + .filter(|(vertical, at)| self.fits(cx, *vertical, *at)); + if let Some((vertical, at)) = place { if self.at.is_none() { out.push(Action::Begin("New Guide".into())); } diff --git a/crates/tools/src/rulerguide/tests.rs b/crates/tools/src/rulerguide/tests.rs index 7fa192d9ec..4b4f1be72c 100644 --- a/crates/tools/src/rulerguide/tests.rs +++ b/crates/tools/src/rulerguide/tests.rs @@ -148,6 +148,36 @@ fn a_new_guide_is_made_on_release_over_the_canvas_only() { assert_eq!(g.pointer(&c, &ev(PointerKind::Up, -5.0, 40.0, m), false), vec![Action::Cancel]); } +/// A guide made only within its artboard ([`NewGuide::within`]) shows and is made where its +/// position, on the axis Alt gives it, lies within the artboard (edges included). Outside it, or +/// with an artboard the document doesn't have, it goes as it does off the canvas. +#[test] +fn a_guide_within_its_artboard_is_made_only_inside_it() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let m = Mods::default(); + let alt = Mods { alt: true, ..m }; + let preview = |vertical: bool, pos: f64| Action::Preview("guide.add".into(), json!({"vertical": vertical, "pos": pos, "artboard": 0})); + let mut g = NewGuide::within(&c, true, 0); + // Right of the 500 pt artboard: nothing, then its right edge. + assert_eq!(g.pointer(&c, &ev(PointerKind::Drag, 520.0, 40.0, m), true), vec![]); + assert_eq!(g.pointer(&c, &ev(PointerKind::Drag, 500.0, 40.0, m), true), vec![Action::Begin("New Guide".into()), preview(true, 500.0)]); + // Alt makes it horizontal: y 40 is inside, y 600 is not. + assert_eq!(g.pointer(&c, &ev(PointerKind::Drag, 700.0, 40.0, alt), true), vec![preview(false, 40.0)]); + assert_eq!(g.pointer(&c, &ev(PointerKind::Drag, 300.0, 600.0, alt), true), vec![Action::Cancel]); + assert!(g.overlays(&c).is_empty()); + assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 300.0, 600.0, alt), true), vec![]); + // Released inside: made. + let mut g = NewGuide::within(&c, false, 0); + assert_eq!(g.pointer(&c, &ev(PointerKind::Drag, 900.0, 0.0, m), true), vec![Action::Begin("New Guide".into()), preview(false, 0.0)]); + assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 900.0, 0.0, m), true), vec![Action::Commit]); + // No artboard 3: never shown. + let mut g = NewGuide::within(&c, true, 3); + assert_eq!(g.pointer(&c, &ev(PointerKind::Drag, 100.0, 40.0, m), true), vec![]); + assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 100.0, 40.0, m), true), vec![]); +} + #[test] fn new_ruler_guide_alt_switches_axis_and_uses_the_release_position() { let (d, _) = doc_with_rect(); @@ -259,6 +289,7 @@ fn an_artboard_guide_is_picked_and_snapped_to_across_its_artboard_only() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); d.guides = vec![Guide { artboard: Some(id), ..Guide::new(false, 150.0) }]; let (s, p) = (Selection::default(), paint()); @@ -574,6 +605,7 @@ fn ruler_guide_readouts_count_from_the_active_artboard_with_artboard_rulers() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); doc.ruler_origin = Point::new(5.0, 5.0); let (paint, selection) = (paint(), Selection::default()); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index fe666bd671..8dbdb461ea 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -368,6 +368,14 @@ impl MoveSnap { if q != start + d { d = q - start; guides = ov; + } else if guides.is_empty() + && let Some(b) = self.bounds + { + // Nothing else lined up: the bounds slide along the line onto a ruler guide, as + // they do without Shift (#4312). + let (adj, ov) = t.snap_moved_along_to_rulers(start + d, b + d, u, cx.tol(cx.snap_tolerance)); + d += adj; + guides = ov; } } if cx.snap_to_pixel diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 2b1151742a..67f5c91b5d 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -770,6 +770,30 @@ fn a_move_snaps_the_grabbed_point_to_a_ruler_guide_with_smart_guides_on() { assert_eq!(dx(&ToolContext { snap_to_point: false, ..cx(&d, &s, &p) }, 172.0), 22.0); } +/// #4312: a Shift move keeps to its line while its edges and centre land on a ruler guide, as a +/// move without Shift does (#5746). +#[test] +fn a_shift_move_lands_the_edges_on_a_ruler_guide() { + let (mut d, id) = doc_with_rect(); + d.guides = vec![vectorcraft_doc::Guide::new(true, 333.0)]; + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = cx(&d, &s, &p); + // Level; the left edge (100) would end 2 short of the guide, the pointer far from it. + let (m, _) = shift_moved(&c, (150.0 + 231.0, 150.0)); + assert!(moved_by(m, (233.0, 0.0)), "{m:?}"); + // The right edge, 1 past the guide. + let (m, _) = shift_moved(&c, (150.0 + 134.0, 150.0)); + assert!(moved_by(m, (133.0, 0.0)), "{m:?}"); + // Out of reach, or with Snap to Point off, the move stays as dragged. + let (m, _) = shift_moved(&c, (150.0 + 221.0, 150.0)); + assert!(moved_by(m, (221.0, 0.0)), "{m:?}"); + let off = ToolContext { snap_to_point: false, ..cx(&d, &s, &p) }; + let (m, _) = shift_moved(&off, (150.0 + 231.0, 150.0)); + assert!(moved_by(m, (231.0, 0.0)), "{m:?}"); +} + /// Alt pressed during a move makes a copy, which snaps to the original it leaves behind (as /// gathered before the previews moved it); released, the move doesn't. #[test] @@ -2426,3 +2450,30 @@ fn a_ruler_guide_under_the_centre_point_keeps_the_pointer() { let drag = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 150.0)); assert!(drag.iter().any(|a| matches!(a, Action::Preview(cmd, _) if cmd == "guide.move")), "the guide drags: {down:?} {drag:?}"); } + +/// #6437: in Outline view, where an image is drawn as its frame, a click inside it on the edge of +/// a path behind selects that path, with the image selected or not. In Preview the image takes +/// the click. +#[test] +fn outline_view_click_through_an_image_selects_the_path_behind() { + use vectorcraft_doc::{Appearance, Document, ImageObject, Node, NodeKind}; + let mut d = Document::new(500.0, 500.0); + let layer = d.layers[0].id; + let (back, image) = (d.alloc_id(), d.alloc_id()); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)); + d.insert(Some(layer), 0, Node::path(back, square, Appearance::default_art())).unwrap(); + let xf = vectorcraft_geom::Affine::translate((150.0, 150.0)); + let im = ImageObject { key: "k".into(), width: 100, height: 100, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(layer), 1, Node::new(image, NodeKind::Image(Box::new(im)))).unwrap(); + let selects = |a: &[Action], id: NodeId| a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([id.0]))); + let p = paint(); + for picked in [vec![], vec![image]] { + let mut s = Selection::default(); + s.set(picked.clone()); + let outline = ToolContext { outline: true, ..cx(&d, &s, &p) }; + let a = SelectionTool::default().pointer(&outline, &ev(PointerKind::Down, 200.0, 180.0)); + assert!(selects(&a, back), "outline, {picked:?} selected: {a:?}"); + let a = SelectionTool::default().pointer(&cx(&d, &s, &p), &ev(PointerKind::Down, 200.0, 180.0)); + assert!(!selects(&a, back), "preview, {picked:?} selected: {a:?}"); + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0f5152d2bb..7b69fbfb8d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -88,6 +88,7 @@ impl VectorcraftApp { selection_box: None, selection_bounds: None, content_bounds: None, + plugin_keys: Default::default(), cursors: Default::default(), view_moved: None, hover_cursor: None, @@ -340,8 +341,13 @@ impl VectorcraftApp { screen_color::poll(self, ctx); self.poll_finished_work(); crate::script_runs::poll(self); - if self.session.script_running() && !self.session.script_waiting() { - ctx.request_repaint(); + crate::scripts_menu::poll(self, ctx); + if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() { + // A script in `$.sleep` goes on when its time is up; until then the app can idle. + match self.session.script_sleep_left() { + Some(left) => ctx.request_repaint_after(left), + None => ctx.request_repaint(), + } } #[cfg(not(target_arch = "wasm32"))] self.tick_link_updates(ctx, now); @@ -369,9 +375,7 @@ impl VectorcraftApp { unsaved::finish_pending(self); if self.session.script_running() { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - if self.ui.dialog.is_none() { - self.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, serde_json::json!({}))); - } + dialogs::script_run::ask_to_close(self); } else if self.file_sheet_open() { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); self.status(picks::busy()); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 9e698b1bff..d97d111812 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -73,6 +73,7 @@ fn substitute_warnings_follow_current_font_inventory() { impl VectorcraftApp { /// Run a UI or engine command by id. The single entry point for every frontend path. pub fn run(&mut self, id: &str, params: Value) -> Result { + let touch_workspace = self.session.prefs.touch_workspace; // A file dialog it shows off the UI thread runs it again with the path picked. let result = if self.picks.is_entry_free() { let entry = picks::Entry::Command(id.to_string(), params.clone()); @@ -80,6 +81,9 @@ impl VectorcraftApp { } else { self.run_now(id, params) }; + if id == "prefs.import" && result.is_ok() { + crate::prefs_dialog::imported(self, touch_workspace); + } placing::settle_swatch_paste(self); result } diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 6aa3eab765..f88367cb60 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -117,6 +117,7 @@ impl VectorcraftApp { smart_guides: self.ui.view.smart_guides, guides: self.ui.view.guides, snap_to_grid: self.ui.view.snap_to_grid, + pixel_preview: self.ui.view.pixel_preview, snap_to_pixel: self.ui.view.snap_to_pixel, // View › Hide Edges: the canvas draws neither the bounding box (with the type widget) // nor the Live Corners widgets, and the tools do not answer the pointer on them. diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 1e69fc57d5..38b790ecc4 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -58,6 +58,9 @@ pub struct CanvasCache { pub selection_bounds: Option<((u64, u64), Option)>, /// [`VectorcraftApp::content_bounds`] for (document uid, revision). pub content_bounds: Option<((u64, u64), Option)>, + /// [`CacheKey::plugins`] by document uid, with the plug-in revision + /// ([`vectorcraft_render::effects::plugin_revision`]) it was last checked at. + pub plugin_keys: std::collections::HashMap, /// The tools' cursors as OS cursor bitmaps. pub cursors: cursors::Images, /// The view the canvas last drew and when it last changed (egui's input time): while it moves, @@ -119,6 +122,11 @@ pub struct CacheKey { pub highlight_substituted_fonts: bool, /// [`vectorcraft_render::placed_document::generation`]: placed documents' bitmaps made since. pub placed: u64, + /// The plug-in revision ([`vectorcraft_render::effects::plugin_revision`]) of the last plug-in + /// install or removal, or of the last time deferred plug-in effect stages gave results, after + /// which the document drew a plug-in effect ([`vectorcraft_render::draws_plugin_effects`]): a + /// frame drawn before it draws those effects as the plug-ins installed then did. 0 until then. + pub plugins: u64, /// View › Pixel Preview: the document pixels rendered (x0, y0, x1, y1), one per point, shown /// with hard edges. None: the art is rendered for the screen. pub pixel: Option<[i64; 4]>, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 6fc9baab5c..56f121ad6d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -293,6 +293,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let painter = ui.painter_at(rect); let Some(st) = app.session.active() else { return }; let doc = st.doc.clone(); + let effects = st.plugin_effects.clone(); let mask_view = st.shown_mask(); paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view())); @@ -316,7 +317,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview: off, images show // their pixels as they rasterize, hard-edged. let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps; - let key = cache_key(app, ui, st, &t, &v, (w, h, ppp), (pixel, smooth_images)); + let plugins = plugin_key(&mut app.canvas.plugin_keys, &app.session, st); + let key = cache_key(app, ui, st, &t, &v, (w, h, ppp), (pixel, smooth_images, plugins)); // Placed documents' bitmaps are being made: draw again when they are ready. if vectorcraft_render::placed_document::busy() { ui.ctx().request_repaint_after(std::time::Duration::from_millis(30)); @@ -348,8 +350,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if wait.is_none() && (!same_frame || app.canvas.texture.is_none() || settle) { let (w, h, view) = frame_view(pixel, (w, h), &v, ppp); let opts = frame_options(app, &key, mask_view, smooth_images); - draw_frame(app, ui, Frame { key: &key, doc: &doc, size: (w, h), view, opts, pixel }); + draw_frame(app, ui, Frame { key: &key, doc: &doc, effects: &effects, size: (w, h), view, opts, pixel }); } + report_deferred(app, &effects); // The status bar reports each image that a renderer (this thread's or the worker's) could not // decode, once per image in the process. let undecoded = vectorcraft_render::newly_undecodable(doc.images.values()); @@ -565,7 +568,7 @@ fn cache_key( t: &Tokens, v: &View, (w, h, ppp): (u32, u32, f32), - (pixel, smooth_images): (Option<[i64; 4]>, bool), + (pixel, smooth_images, plugins): (Option<[i64; 4]>, bool, u64), ) -> CacheKey { // Paths made into guides are drawn as the ruler guides are (Preferences › Guides & Grid). let guide_look = LineLook::guides(&app.session.prefs, t); @@ -590,6 +593,7 @@ fn cache_key( highlight_alternate_glyphs: app.session.prefs.highlight_alternate_glyphs, highlight_substituted_fonts: app.session.prefs.highlight_substituted_fonts, placed: vectorcraft_render::placed_document::generation(), + plugins, pixel, smooth_images, isolated: st.isolation.map(|id| id.0), @@ -602,6 +606,39 @@ fn cache_key( } } +/// [`CacheKey::plugins`] of document `st`, one of the documents open in `session`. `keys` holds each +/// document's value and the plug-in revision it was checked at, so a document is looked through only +/// once after each change of the plug-in revision. +fn plugin_key( + keys: &mut std::collections::HashMap, + session: &vectorcraft_engine::Session, + st: &vectorcraft_engine::DocState, +) -> u64 { + let revision = vectorcraft_render::effects::plugin_revision(); + match keys.get(&st.uid) { + Some(&(checked, key)) if checked == revision => key, + seen => { + let key = if vectorcraft_render::draws_plugin_effects(&st.doc) { revision } else { seen.map_or(0, |&(_, key)| key) }; + keys.retain(|uid, _| session.documents().iter().any(|d| d.uid == *uid)); + keys.insert(st.uid, (revision, key)); + key + } + } +} + +/// Once the first view of a document has been drawn, the status bar says how many plug-in effect +/// stages it left deferred, if any. +fn report_deferred(app: &mut VectorcraftApp, effects: &vectorcraft_plugins::deferred::Deferrals) { + if let Some(n) = effects.take_report().filter(|n| *n > 0) { + app.status(crate::i18n::msg_n( + n as u64, + "Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.", + "Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them.", + &[], + )); + } +} + /// Start the render worker, and upload the frame it finished. fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) { if !app.canvas.worker_started { @@ -625,6 +662,9 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate: return; } upload(app, ctx, done.img, done.key.pixel.is_some()); + if let Some(d) = app.session.documents().iter().find(|d| d.uid as usize == done.key.doc) { + d.plugin_effects.first_view_done(); + } app.canvas.key = Some(done.key); app.canvas.shown = Some((done.doc, done.opts)); app.perf.render_ms = done.ms; @@ -707,6 +747,8 @@ fn frame_options( struct Frame<'a> { key: &'a CacheKey, doc: &'a std::sync::Arc, + /// The document's deferred plug-in effect stages: the frame renders inside their view. + effects: &'a vectorcraft_plugins::deferred::Deferrals, size: (u32, u32), view: Affine, opts: vectorcraft_render::RenderOptions, @@ -718,7 +760,7 @@ struct Frame<'a> { pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::from_millis(16); fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { - let Frame { key, doc, size: (w, h), view, opts, pixel } = frame; + let Frame { key, doc, effects, size: (w, h), view, opts, pixel } = frame; // Frames that would be slow on this thread (the last one took over 8 ms) go // to the worker. An interaction's frames stay on the worker once it drew the frame shown: // its renderer keeps the rasters of the art's effects that make those frames fast, and this @@ -746,7 +788,8 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.canvas.renderer.let_go_of_measured(); } if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { - let part = app.canvas.renderer.render(doc, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view, &opts); + let renderer = &mut app.canvas.renderer; + let part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view, &opts)); let color = color_image(&part); let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; tex.set_partial([x0 as usize, y0 as usize], color, options); @@ -768,6 +811,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { view, opts, scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + effects: effects.clone(), may_copy, may_keep: true, }); @@ -779,7 +823,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { } _ => { let t0 = now_ms(); - let img = app.canvas.renderer.render(doc, w, h, view, &opts); + let renderer = &mut app.canvas.renderer; + let img = effects.view(|| renderer.render(doc, w, h, view, &opts)); + effects.first_view_done(); upload(app, ui.ctx(), img, pixel.is_some()); app.canvas.key = Some(key.clone()); app.canvas.shown = Some((doc.clone(), opts.clone())); @@ -1065,11 +1111,14 @@ fn guide_lines(app: &VectorcraftApp, painter: &egui::Painter, xf: &Xf, rect: egu } } -/// The ruler guides of document `st`, its selected guides in the selection colour. +/// The ruler guides of document `st`, its selected guides in the selection colour. An artboard +/// guide of an artboard with a guide label ([`vectorcraft_doc::Artboard::guide_label`]) is drawn in +/// the label's color, in the guide preference's style; the others in the guide preference's color. fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, xf, t): (&egui::Painter, &Xf, &Tokens), rect: egui::Rect) { let doc = &st.doc; let look = LineLook::guides(&app.session.prefs, t); let picked = LineLook { color: t.selection, ..look }; + let labels = guide_labels(doc); let selected: &[usize] = &st.selection.guides; let key = st.selection.key_guide; let view = view_bounds(xf); @@ -1086,7 +1135,8 @@ fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, ends } }; - if selected.contains(&i) { picked } else { look }.guide(painter, a, b); + let own = g.artboard.and_then(|id| labels.get(&id)).map_or(look, |&color| LineLook { color, ..look }); + if selected.contains(&i) { picked } else { own }.guide(painter, a, b); // The key guide (Align to Key Object, #2143): thicker, as a key object's outline is. if key == Some(i) { painter.line_segment([a, b], Stroke::new(KEY_OUTLINE, picked.color)); @@ -1094,6 +1144,17 @@ fn guides_of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, (painter, } } +/// The guide label colors of `doc`'s artboards that have one, by artboard id. +pub(super) fn guide_labels(doc: &vectorcraft_doc::Document) -> std::collections::HashMap { + doc.artboards + .iter() + .filter_map(|a| { + let [r, g, b] = a.guide_label?.rgb(); + Some((a.id, Color32::from_rgb(r, g, b))) + }) + .collect() +} + /// The selection's visuals and the tools' overlays, to be drawn. fn selection_visuals( app: &mut VectorcraftApp, diff --git a/crates/ui-egui/src/canvas/fill.rs b/crates/ui-egui/src/canvas/fill.rs index 60d8b00754..8eda1db219 100644 --- a/crates/ui-egui/src/canvas/fill.rs +++ b/crates/ui-egui/src/canvas/fill.rs @@ -95,6 +95,7 @@ pub(super) fn fill_uncovered( let (_, _, view) = fill_view(&done.key); app.canvas.fill = Some(Fill { key: done.key, view, size: (fw, fh), tex }); } + let effects = app.session.documents().iter().find(|d| d.uid as usize == key.doc).map(|d| d.plugin_effects.clone()).unwrap_or_default(); let Some(worker) = app.canvas.fill_worker.as_mut().filter(|_| !gaps.is_empty()) else { return }; if !app.canvas.fill.as_ref().is_some_and(|f| covers(&f.key)) && !worker.pending.as_ref().is_some_and(covers) { let (w, h, view) = fill_view(key); @@ -106,6 +107,7 @@ pub(super) fn fill_uncovered( view, opts, scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + effects, may_copy: false, may_keep: false, }); diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 09749fc12c..7f000ee787 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -178,7 +178,11 @@ pub(super) fn ruler_rects(full: egui::Rect) -> [egui::Rect; 3] { /// A drag from a ruler onto the canvas makes a guide where the button is released (the engine's /// `Session::ruler_guide`): a horizontal one from the top ruler, a vertical one from the left /// ruler, snapped as a moved guide is (with Shift to the ruler's ticks). Released anywhere else, -/// it makes none. The corner drags the rulers' origin or resets it on a double-click. +/// it makes none. A double-click on a ruler (both clicks on that ruler) makes a guide at the +/// pointer, across the ruler's axis (a vertical one on the top ruler, a horizontal one on the +/// left; swapped in a view turned 90°, where the rulers read the other document axis, and the +/// nearer axis in between), unsnapped, as one `guide.add` and so one undo step. The corner drags the rulers' origin or resets it on a +/// double-click. pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, canvas: egui::Rect, xf: &Xf) -> Option { let [top, left, corner] = ruler_rects(full); // Right-click on a ruler or the origin box: the document units, to swap between them as @@ -189,6 +193,40 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c // (right). Not focusable (`click_and_drag` is): no key acts on a ruler, so Tab skips it. let resp = ui.interact(r, egui::Id::unique(id), Sense::CLICK | Sense::DRAG); resp.context_menu(|ui| crate::menus::ruler_menu_body(app, ui, &mut unit_clicked)); + // egui counts a double-click by position and time alone, so a click on the canvas right + // at the ruler and one on the ruler would pass for one: the pair counts only when the + // ruler's own click before it came within the double-click delay. + let last_click = egui::Id::unique(if vertical { "ruler-left-last-click" } else { "ruler-top-last-click" }); + let now = ui.input(|i| i.time); + let first_here = + ui.data(|d| d.get_temp::(last_click)).is_some_and(|t| now - t <= ui.ctx().options(|o| o.input_options.max_double_click_delay)); + if resp.clicked_by(egui::PointerButton::Primary) { + ui.data_mut(|d| d.insert_temp(last_click, now)); + } + if resp.double_clicked_by(egui::PointerButton::Primary) + && first_here + && let Some(p) = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())) + { + // The same document point the drag path reads. A ruler reads the canvas's coordinates + // turned with the view, so the guide is the one whose line crosses the ruler's axis: + // the vertical one when that axis (the screen's x for the top ruler, y for the left, + // in document directions) is nearer the document's x, else the horizontal one. At 0° + // that is a vertical guide from the top ruler; at 90° a horizontal one; between, the + // nearer axis, whose line still runs through the point and never along the ruler. + let at = xf.to_doc(p); + let (sn, cs) = xf.rot.sin_cos(); + let axis = if vertical { (sn, cs) } else { (cs, -sn) }; + let across = axis.0.abs() >= axis.1.abs(); + let mut params = json!({"vertical": across, "pos": if across { at.x } else { at.y }}); + if let Some(ab) = app.session.ruler_guide_artboard() { + params["artboard"] = json!(ab); + } + // The new guide shows even if guides were hidden. + app.ui.view.guides = true; + if let Err(e) = app.run("guide.add", params) { + app.status(e.to_string()); + } + } let kind = if resp.drag_stopped() { PointerKind::Up } else if resp.dragged() { diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 13b56e6f1e..c8dc007538 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -12,8 +12,8 @@ use super::outline::{c32, node_outline, stroke_path, too_many_anchors}; use super::view::fit_zoom; use super::{ Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, cache_key, - dim_on_canvas, frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, pos2, rulers, shows_artboards, textured_quad, vec2, - view_rects, + dim_on_canvas, frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, plugin_key, pos2, rulers, shows_artboards, + textured_quad, vec2, view_rects, }; use crate::doc_windows::Win; use crate::thumb_worker::ThumbWorker; @@ -303,7 +303,8 @@ pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) // View › Pixel Preview, as the canvas draws it. let pixel = (app.ui.view.pixel_preview && v.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten(); let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps; - let mut key = cache_key(app, ui, st, &t, &v, (pw, ph, ppp), (pixel, smooth_images)); + let plugins = plugin_key(&mut app.canvas.plugin_keys, &app.session, st); + let mut key = cache_key(app, ui, st, &t, &v, (pw, ph, ppp), (pixel, smooth_images, plugins)); // The current document's drag and Image Trace hold are not this document's, and this view has // its own Outline or Preview. (key.dragging, key.trace_source, key.outline) = (false, None, v.outline); diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index b5f8dac668..0ccba73dee 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -233,6 +233,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { for (label, icon, cmd, params) in &items { let galley = ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(13.0), t.text_strong); let (r, resp) = ui.allocate_exact_size(vec2(galley.size().x + 38.0, 30.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, *label)); if resp.hovered() { ui.painter().rect_filled(r, CornerRadius::same(3), t.hover); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a891179a6b..81008bb0be 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1208,6 +1208,73 @@ fn a_drag_from_a_ruler_onto_the_canvas_makes_a_guide() { assert_eq!(app.session.active().unwrap().doc.art_bounds(), None, "the tool drew nothing"); } +/// An artboard's guide label colors its own guides only: a canvas guide, a guide of an artboard +/// without a label and a guide of a deleted artboard keep the guide color preference, and a +/// selected labeled guide takes the selection color. Hide Guides hides labeled guides too. +#[test] +fn artboard_guide_label_colors_only_its_own_guides() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("artboard.new", &json!({})).unwrap(); + app.session.execute("artboard.new", &json!({})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Red"})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 2, "guideLabel": "#00ff00"})).unwrap(); + // Vertical guides at x 100 (artboard 1, Red), 520 (artboard 2, no label) and 940 (artboard + // 3, whose artboard is then deleted), and a horizontal canvas guide at y 150. + for (pos, artboard) in [(100, json!(0)), (520, json!(1)), (940, json!(2))] { + app.session.execute("guide.add", &json!({"vertical": true, "pos": pos, "artboard": artboard})).unwrap(); + } + app.session.execute("guide.add", &json!({"vertical": false, "pos": 150})).unwrap(); + // Deleting artboard 3 deletes its guide; a guide still naming its id (as a file might) is an + // orphan, drawn across the canvas. + let gone = app.session.active().unwrap().doc.artboards[2].id; + app.session.execute("artboard.setProps", &json!({"index": 2, "guideLabel": null})).unwrap(); + app.session.execute("artboard.delete", &json!({"index": 2})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); + { + let st = app.session.active_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + let last = doc.guides.len() - 1; + doc.guides[last].artboard = Some(gone); + } + app.ui.view.guides = true; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let t = Tokens::get(&ctx); + let pref = LineLook::guides(&app.session.prefs, &t).color; + let colors = |app: &mut VectorcraftApp, at: f64, vertical: bool| -> Vec { + shapes(app, &ctx) + .iter() + .filter_map(|s| match s { + Shape::LineSegment { points, stroke } => { + let (a, b) = (xf.to_doc(points[0]), xf.to_doc(points[1])); + let (u, v) = if vertical { (a.x, b.x) } else { (a.y, b.y) }; + ((u - at).abs() < 0.01 && (v - at).abs() < 0.01).then_some(stroke.color) + } + _ => None, + }) + .collect() + }; + let red = Color32::from_rgb(0xff, 0x4f, 0x4f); + assert_eq!(colors(&mut app, 100.0, true), [red], "the labeled artboard's guide"); + assert_eq!(colors(&mut app, 520.0, true), [pref], "an artboard without a label"); + assert_eq!(colors(&mut app, 150.0, false), [pref], "a canvas guide"); + assert!(colors(&mut app, 940.0, true).is_empty(), "deleted with its artboard"); + assert_eq!(colors(&mut app, 300.0, true), [pref], "a guide whose artboard is gone"); + assert_ne!(red, pref); + // Selected, it is drawn in the selection color; deselected, in the label's again. + app.session.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + assert_eq!(colors(&mut app, 100.0, true), [t.selection], "selected"); + app.session.execute("guide.select", &json!({"indexes": []})).unwrap(); + assert_eq!(colors(&mut app, 100.0, true), [red], "deselected"); + // A new label shows on the next frame. + app.session.execute("artboard.setProps", &json!({"index": 0, "guideLabel": "Black"})).unwrap(); + assert_eq!(colors(&mut app, 100.0, true), [Color32::BLACK]); + app.ui.view.guides = false; + assert!(colors(&mut app, 100.0, true).is_empty(), "Hide Guides hides it"); +} + /// #4646: a guide dragged out of a ruler shows as a line across the canvas while it is dragged, /// also with Preferences › Performance › Real-time Drawing and Editing off (only its position /// label showed then). @@ -1412,6 +1479,52 @@ fn new_ruler_guide_alt_cancel_keeps_document_and_redo() { } } +/// With Preferences › Guides & Grid › Artboard Guides with Cmd/Ctrl + Ruler Drag on, Cmd/Ctrl held +/// when a drag leaves either ruler makes a guide of the active artboard, even when the key is let +/// go before the release; a guide outside the artboard is not made. With the preference off, the +/// same drag makes a canvas guide. +#[test] +fn cmd_ruler_drags_make_artboard_guides_with_the_preference_on() { + use egui::{Event, Modifiers}; + for source_vertical in [false, true] { + for on in [false, true] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "cmdRulerDragArtboardGuides", "value": on})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.select_tool("rectangle"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let from = + if source_vertical { pos2(rect.left() - RULER / 2.0, rect.center().y) } else { pos2(rect.center().x, rect.top() - RULER / 2.0) }; + let drag = |app: &mut VectorcraftApp, to: Point| { + let at = xf.to_screen(to); + assert!(rect.contains(at)); + let button = |pos, pressed, modifiers| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + frame(app, &ctx, vec![Event::ModifiersChanged(Modifiers::COMMAND), Event::PointerMoved(from)]); + frame(app, &ctx, vec![button(from, true, Modifiers::COMMAND)]); + frame(app, &ctx, vec![Event::PointerMoved(at)]); + frame(app, &ctx, vec![Event::ModifiersChanged(Modifiers::NONE), Event::PointerMoved(at), button(at, false, Modifiers::NONE)]); + }; + let board = app.session.active().unwrap().doc.artboards[0].id; + drag(&mut app, Point::new(80.0, 120.0)); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.guides.len(), 1, "vertical {source_vertical}, on {on}"); + assert_eq!(st.doc.guides[0].vertical, source_vertical); + assert_eq!(st.doc.guides[0].artboard, on.then_some(board), "vertical {source_vertical}, on {on}"); + // Beyond the artboard's right or bottom edge. + let beyond = xf.to_doc(rect.right_bottom() - egui::vec2(2.0, 2.0)); + assert!(beyond.x > 400.0 && beyond.y > 300.0, "{beyond:?}"); + drag(&mut app, beyond); + assert_eq!(app.session.active().unwrap().doc.guides.len(), if on { 1 } else { 2 }, "vertical {source_vertical}, on {on}"); + } + } +} + /// #451: a guide dragged out of a ruler lands on the art's side midpoints (halving an /// artboard-sized rectangle) and on the artboard's edges; an artboard guide is drawn across /// its artboard only. @@ -2282,6 +2395,52 @@ fn undecodable_images_are_marked_and_reported_once() { assert_eq!(app.ui.status, "", "said once"); } +/// The plug-in effects a document's first view leaves out past its budget are reported in the +/// status bar once, in the singular or the plural, and Effect › Refresh Deferred Effects is +/// enabled until it has run them. +#[test] +fn the_first_view_reports_the_plug_in_effects_it_deferred() { + use std::sync::atomic::{AtomicU64, Ordering}; + use vectorcraft_plugins::wat as tpl; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.canvas.worker_started = true; // render on this thread + let module = tpl::module(&tpl::manifest("test.ui.deferred", "effect", "{}"), tpl::ECHO, "", 1); + app.session.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(module).unwrap())})).unwrap(); + // Each reading of the clock is 3 s later: the first run's result comes back after the budget, + // and no later run starts. + let step = std::sync::Arc::new(AtomicU64::new(3_000)); + let ctx = egui::Context::default(); + for (count, said) in [ + (2, "Opened with 2 plug-in effects deferred. Effect › Refresh Deferred Effects runs them."), + (1, "Opened with 1 plug-in effect deferred. Effect › Refresh Deferred Effects runs it."), + ] { + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // Art the plug-in has not been given before: a result it gave is kept and drawn at once. + for i in 0..count { + let x = 31.0 + 97.0 * f64::from(i) + 13.0 * f64::from(count); + let id = app.session.execute("shape.rectangle", &json!({"x": x, "y": 47, "width": 23, "height": 29})).unwrap()["id"].clone(); + app.session.execute("effect.apply", &json!({"ids": [id], "effect": "plugin.test.ui.deferred"})).unwrap(); + } + app.session.execute("select.none", &json!({})).unwrap(); + let (now, by) = (std::sync::Arc::new(AtomicU64::new(0)), step.clone()); + let clock: vectorcraft_plugins::deferred::Clock = + std::sync::Arc::new(move || Some(now.fetch_add(by.load(Ordering::Relaxed), Ordering::Relaxed))); + app.session.doc_mut().unwrap().plugin_effects = vectorcraft_plugins::deferred::Deferrals::with_clock(clock); + step.store(3_000, Ordering::Relaxed); + app.status(""); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.ui.status, said); + assert!(crate::menus::enabled(&app, "effect.refreshDeferred")); + app.status(""); + app.session.doc_mut().unwrap().revision += 1; + frame(&mut app, &ctx, vec![]); + assert_eq!(app.ui.status, "", "said once"); + step.store(0, Ordering::Relaxed); + app.session.execute("effect.refreshDeferred", &json!({})).unwrap(); + assert!(!crate::menus::enabled(&app, "effect.refreshDeferred"), "nothing is left deferred"); + } +} + /// A drag of an object with raster effects (#1257): the drag's frames render while /// interacting and draw the object's drop shadow and filtered content from the rasters of the /// frame before; the frame after the drag renders without `interacting`, on the render worker, @@ -3723,6 +3882,34 @@ fn snap_to_grid_and_pixel_preview_hide_the_hover_outline() { assert!(outlines(&mut app) > 0, "Pixel Preview off again"); } +/// View › Pixel Preview turns Smart Guides off in the tools: a square moved to 3 pt below another +/// square's top lines up with it only while Pixel Preview is off. +#[test] +fn pixel_preview_stops_smart_guides_snapping_a_move() { + for pixel in [false, true] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 400, "y": 300, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + if pixel { + app.run("view.pixelPreview", json!({})).unwrap(); + } + assert!(app.ui.view.smart_guides); + assert_eq!(app.ui.view.pixel_preview, pixel); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool("selection"); + let view = app.view_info(); + let mut at = |kind: PointerKind, y: f64| crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, 425.0, y), view); + at(PointerKind::Down, 325.0); + for y in [300.0, 250.0, 200.0, 150.0, 128.0] { + at(PointerKind::Drag, y); + } + at(PointerKind::Up, 128.0); + let top = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap().y0; + assert_eq!(top, if pixel { 103.0 } else { 100.0 }, "Pixel Preview {pixel}"); + } +} + /// #2452: while the view scrolls under a resting pointer, the art under it isn't hit-tested: /// no hover outline, and the tool's last cursor stays. Once the view has been still for /// [`HOVER_STILL_SECS`], the outline comes back without the pointer moving. @@ -9057,6 +9244,20 @@ fn the_task_bar_offers_the_artboard_tools_actions() { assert_eq!(names(&mut app), ["Resize", "Duplicate", "Export"]); } +/// Screen readers name the Contextual Task Bar's text buttons by their labels. +#[test] +fn screen_readers_name_the_task_bars_text_buttons() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 180, "y": 130, "width": 40, "height": 40})).unwrap(); + app.select_tool("selection"); + let tree = tree(|ui| show(&mut app, ui)); + for label in ["Edit Path", "Offset Path", "Simplify", "Duplicate"] { + assert_eq!(named(&tree, label).role(), egui::accesskit::Role::Button, "{label}"); + } +} + /// A selected group's Contextual Task Bar offers Ungroup and Isolate. While an opacity mask is /// edited, when Enter Isolation Mode is off, a group in the mask art gets Ungroup without Isolate. #[test] @@ -10546,6 +10747,7 @@ fn pan_job(doc: &std::sync::Arc, key: &CacheKey, (dx, view: Affine::translate((dx, dy)), opts: vectorcraft_render::RenderOptions::default(), scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + effects: Default::default(), may_copy: true, may_keep: true, } @@ -10590,6 +10792,48 @@ fn a_whole_pixel_pan_copies_the_pixels_that_stay_on_screen() { } } +/// Installing, replacing or removing a plug-in draws a document with a plug-in effect again, and a +/// pan from the frame drawn before the change renders whole instead of copying its pixels. The key +/// of a document without a plug-in effect does not follow the plug-ins. The other tests share the +/// plug-in registry, and the plug-in is removed after. +#[test] +fn a_plug_in_change_draws_the_document_s_plug_in_effects_again() { + use vectorcraft_plugins::wat as tpl; + let id = "test.canvas.redraw"; + let module = vectorcraft_format::base64_encode(&wat::parse_str(tpl::module(&tpl::manifest(id, "effect", "{}"), tpl::ECHO, "", 1)).unwrap()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("plugin.install", json!({"dataBase64": module})).unwrap(); + app.session.execute("file.new", &json!({"width": 256, "height": 128})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 16, "y": 16, "width": 64, "height": 96})).unwrap()["id"].clone(); + app.canvas.worker_started = true; // render on this thread + let ctx = egui::Context::default(); + shapes(&mut app, &ctx); + // Other keys' fields (placed documents' bitmaps) follow what other tests do; this one's don't. + let plugins = |app: &VectorcraftApp| app.canvas.key.as_ref().expect("a frame was rendered").plugins; + let plain = plugins(&app); + app.run("plugin.install", json!({"dataBase64": module})).unwrap(); + shapes(&mut app, &ctx); + assert_eq!(plugins(&app), plain, "no plug-in effect, so nothing to draw again"); + app.run("effect.apply", json!({"effect": vectorcraft_plugins::effect::effect_id(id), "ids": [rect]})).unwrap(); + shapes(&mut app, &ctx); + let before = app.canvas.key.clone().expect("a frame was rendered"); + app.run("plugin.install", json!({"dataBase64": module})).unwrap(); + shapes(&mut app, &ctx); + let after = plugins(&app); + assert_ne!(after, before.plugins, "drawn again once the plug-in was replaced"); + // The worker's frame from before the change gives no pixels to the next pan. + let doc = app.session.active().unwrap().doc.clone(); + let at_100 = CacheKey { zoom: 1.0, rot: 0.0, ppp: 1.0, pixel: None, ..before }; + let mut r = vectorcraft_render::Renderer::new(); + let mut kept = None; + render_job(&mut r, &mut kept, &pan_job(&doc, &at_100, (0.0, 0.0))); + let pan = pan_job(&doc, &CacheKey { plugins: after, ..at_100.clone() }, (10.0, 0.0)); + assert!(!render_job(&mut r, &mut kept, &pan).reused, "copied from the frame before the change"); + app.run("plugin.remove", json!({"id": id})).unwrap(); + shapes(&mut app, &ctx); + assert_ne!(plugins(&app), after, "drawn again once the plug-in was removed"); +} + /// A frame does not copy from the last one when the view moves by part of a pixel or over half the /// frame, when copying is not allowed, or when a listed key field, render option, zoom, rotation, /// canvas size or device scale differs. Each such frame has the job's size. The session test @@ -10643,6 +10887,7 @@ fn a_frame_renders_whole_when_anything_but_a_whole_pixel_pan_changed() { ("outline key", other_key(&|k| k.outline = true)), ("Pixel Preview", other_key(&|k| k.pixel = Some([0, 0, 256, 128]))), ("placed bitmaps", other_key(&|k| k.placed += 1)), + ("plug-ins", other_key(&|k| k.plugins += 1)), ("outline", other_opts(&|o| o.outline = true)), ("proof", other_opts(&|o| o.proof = Some(Default::default()))), ("overprint preview", other_opts(&|o| o.overprint_preview = true)), @@ -11120,6 +11365,151 @@ fn direct_selection_shows_the_bounding_box_while_cmd_is_held() { assert!(app.ui.view.bounding_box, "View › Show Bounding Box is unchanged"); } +/// #5239: a double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler +/// at its x, a horizontal one on the left ruler at its y, as one undo step, shown even when +/// guides were hidden. The first click of the pair adds nothing. +#[test] +fn double_clicking_a_ruler_adds_a_guide_at_that_position() { + // The ruler to click, the guide's orientation and its position, the pointer at that position. + for (top, vertical, pos) in [(true, true, 120.0), (false, false, 80.0)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.guides = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let view = app.view_mut().unwrap(); + view.zoom = 2.0; + view.rotation = 0.0; + view.center = Point::new(200.0, 150.0); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let at = if top { + pos2(xf.to_screen(Point::new(pos, 0.0)).x, rect.top() - RULER / 2.0) + } else { + pos2(rect.left() - RULER / 2.0, xf.to_screen(Point::new(0.0, pos)).y) + }; + let guides = |app: &mut VectorcraftApp| { + let list = app.session.execute("guide.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().map(|g| (g["vertical"].as_bool().unwrap(), g["pos"].as_f64().unwrap())).collect::>() + }; + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = steps(&app); + let click = |app: &mut VectorcraftApp| { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(app, &ctx, vec![button(true)]); + frame(app, &ctx, vec![button(false)]); + }; + click(&mut app); + assert_eq!(guides(&mut app), vec![], "a single click adds none"); + click(&mut app); + let got = guides(&mut app); + assert_eq!(got.len(), 1, "top ruler: {top}, {got:?}"); + assert!(got[0].0 == vertical && (got[0].1 - pos).abs() < 0.01, "top ruler: {top}, want vertical {vertical} at {pos}: {got:?}"); + assert!(app.ui.view.guides, "the new guide is shown"); + assert_eq!(steps(&app), before + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(guides(&mut app), vec![]); + } +} + +/// A fresh app with a 400 x 300 document, rulers on, the view at zoom 2 turned `rotation` degrees, +/// and its first frame drawn. +fn ruler_guide_app(rotation: f64) -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.guides = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let view = app.view_mut().unwrap(); + view.zoom = 2.0; + view.rotation = rotation; + view.center = Point::new(200.0, 150.0); + frame(&mut app, &ctx, vec![]); + (app, ctx) +} + +/// One primary click at `at`, as three frames (move, press, release). +fn click_at(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2) { + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![egui::Event::PointerMoved(at)]); + frame(app, ctx, vec![button(true)]); + frame(app, ctx, vec![button(false)]); +} + +/// The ruler guides as (vertical, position). +fn guide_list(app: &mut VectorcraftApp) -> Vec<(bool, f64)> { + let list = app.session.execute("guide.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().map(|g| (g["vertical"].as_bool().unwrap(), g["pos"].as_f64().unwrap())).collect() +} + +/// #5239 review: egui counts a double-click by position and time, not by widget, so a click on +/// the canvas right at a ruler followed at once by a click on the ruler is not a double-click on +/// the ruler. No guide; two clicks on the ruler still make one. +#[test] +fn a_canvas_click_then_a_ruler_click_adds_no_guide() { + for (top, canvas_first) in [(true, true), (false, true), (true, false), (false, false)] { + let (mut app, ctx) = ruler_guide_app(0.0); + let rect = app.canvas_rect.unwrap(); + // Two points less than 6 pt apart, either side of the ruler's inner edge. + let (on_canvas, on_ruler) = if top { + (pos2(rect.center().x, rect.top() + 1.0), pos2(rect.center().x, rect.top() - 1.0)) + } else { + (pos2(rect.left() + 1.0, rect.center().y), pos2(rect.left() - 1.0, rect.center().y)) + }; + click_at(&mut app, &ctx, if canvas_first { on_canvas } else { on_ruler }); + click_at(&mut app, &ctx, on_ruler); + let want = usize::from(!canvas_first); + assert_eq!(guide_list(&mut app).len(), want, "top ruler: {top}, first click on the canvas: {canvas_first}"); + } +} + +/// #5239 review: the rulers read the canvas's coordinates turned with the view, so a guide made +/// by a double-click runs across the ruler's axis in any view: it passes through the clicked +/// point and crosses the ruler's edge at it, never along it. At 90° the top ruler reads the +/// document's y, so its guide is horizontal; the left ruler reads x, so its guide is vertical. +/// A view turned part of the way takes the document axis nearer to the ruler's. +#[test] +fn a_ruler_double_click_follows_a_rotated_view() { + // Rotation (degrees), top ruler's guide is vertical, left ruler's guide is vertical. + for (rotation, top_vertical, left_vertical) in [ + (0.0, true, false), + (90.0, false, true), + (-90.0, false, true), + (180.0, true, false), + (270.0, false, true), + (30.0, true, false), + (60.0, false, true), + ] { + for top in [true, false] { + let (mut app, ctx) = ruler_guide_app(rotation); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let at = + if top { pos2(rect.center().x + 37.0, rect.top() - RULER / 2.0) } else { pos2(rect.left() - RULER / 2.0, rect.center().y + 23.0) }; + click_at(&mut app, &ctx, at); + click_at(&mut app, &ctx, at); + let got = guide_list(&mut app); + let label = format!("rotation {rotation}, top ruler: {top}: {got:?}"); + assert_eq!(got.len(), 1, "{label}"); + let (vertical, pos) = got[0]; + assert_eq!(vertical, if top { top_vertical } else { left_vertical }, "{label}"); + // Through the clicked point. + let doc = xf.to_doc(at); + assert!((pos - if vertical { doc.x } else { doc.y }).abs() < 0.01, "{label}: through {doc:?}"); + // Its direction on screen is not along the ruler: the line crosses the ruler's edge. + let along = if vertical { Point::new(doc.x, doc.y + 1.0) } else { Point::new(doc.x + 1.0, doc.y) }; + let dir = (xf.to_screen(along) - xf.to_screen(doc)).normalized(); + let across = if top { dir.y.abs() } else { dir.x.abs() }; + assert!(across > 0.5, "{label}: the guide runs along the ruler ({dir:?})"); + } + } +} + /// An edit to a 3D effect renders the part it changed on this thread, measured by the renderer /// that drew the frame shown ([`vectorcraft_render::Renderer::changed`]): it draws the part with /// the 3D art it made to measure it. diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 7d85a07be1..062059e6d7 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -6,6 +6,8 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> { "dimension" => &[ ("Drag", true), (" out from a highlighted edge to place its dimension | ", false), + ("Click", true), + (" two points, then move and click to place an aligned, horizontal or vertical dimension | ", false), ("Esc", true), (" cancels | Double-click the tool for options", false), ], diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 4d5f75821b..506b149fee 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -136,7 +136,7 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) /// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] /// above or below the strip floats its view in a window under the pointer; one dragged along the /// strip moves its document among the others (`document.move`, #5663), a line marking where it -/// will go. +/// will go. A middle-click on a tab closes it, as its × does (#6506). pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { /// The width of the » button. const MORE: f32 = 30.0; @@ -200,7 +200,9 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { icons::paint(ui, "x", xr, if xresp.hovered() { t.text_strong } else { t.text }); ui.painter().galley(egui::pos2(title_left, r.center().y - galley.size().y / 2.0), galley.clone(), t.text); hovering_art |= crate::document_drag::hover_tab(app, &resp, win, xr.expand(3.0)); - if xresp.clicked() { + // A middle-click anywhere on the tab closes it as the × does (#6506), so closing a + // modified document's last view still asks to save first. + if xresp.clicked() || resp.middle_clicked() || xresp.middle_clicked() { close = Some(win); } else if resp.clicked() { activate = Some(win); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 15c856cd85..452fec1cc0 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -505,6 +505,65 @@ fn a_tabs_close_box_sits_where_the_platform_puts_it() { assert!(super::CLOSE_BEFORE_TITLE == cfg!(target_os = "macos")); } +/// A middle-click on a document tab closes it as the × does (#6506): a saved document closes, and +/// a modified one asks to save first instead of losing its changes. +#[test] +fn a_middle_click_on_a_tab_closes_it_as_the_close_box_does() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + for _ in 0..3 { + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + } + // The second document has unsaved changes; the third stays the current one. + app.session.set_active(1); + app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.session.set_active(2); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 200.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::doc_tabs(app, ui)); + out.textures_delta.clear(); + let mut titles = vec![]; + for c in &out.shapes { + if let egui::Shape::Text(t) = &c.shape + && t.visual_bounding_rect().width() > 30.0 + { + titles.push(t.visual_bounding_rect()); + } + } + titles.sort_by(|a, b| a.left().total_cmp(&b.left())); + titles + }; + let middle_click = |app: &mut crate::VectorcraftApp, at: egui::Pos2| { + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at), press(true)]); + frame(app, vec![press(false)]) + }; + let titles = frame(&mut app, vec![]); + assert_eq!(titles.len(), 3, "{titles:?}"); + // The modified document's tab: the save prompt comes up and the document stays open. + let titles = middle_click(&mut app, titles[1].center()); + assert_eq!(app.session.documents().len(), 3, "a modified document is not closed without asking"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::unsaved::KIND), "a modified document asks first"); + app.ui.dialog = None; + // The first, saved document's tab: it closes, and the others stay open. + let uid = |app: &crate::VectorcraftApp, i: usize| app.session.documents()[i].uid; + let (second, third) = (uid(&app, 1), uid(&app, 2)); + middle_click(&mut app, titles[0].center()); + assert_eq!(app.session.documents().len(), 2, "the middle-click closed the first document"); + assert_eq!((uid(&app, 0), uid(&app, 1)), (second, third)); + assert!(app.ui.dialog.is_none(), "a saved document closes without asking"); + // A middle-click on the × itself closes too: the third, saved document's. + let titles = frame(&mut app, vec![]); + assert_eq!(titles.len(), 2, "{titles:?}"); + let title = titles[1]; + let x = if super::CLOSE_BEFORE_TITLE { title.left() - 16.0 } else { title.right() + 20.0 }; + middle_click(&mut app, egui::pos2(x, title.center().y)); + assert_eq!(app.session.documents().len(), 1, "the middle-click on the × closed the third document"); + assert_eq!(uid(&app, 0), second); + assert!(app.ui.dialog.is_none(), "a saved document closes without asking"); +} + /// One headless frame of the status bar; returns the artboard navigator's buttons, left to /// right: first, previous, next, last. fn navigator(app: &mut crate::VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 38ccc908d8..c13a230a94 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -322,6 +322,7 @@ registry! { BrushDelete: [brush_delete::KIND] => brush_delete::SPEC, Message: [confirm::MESSAGE] => confirm::MESSAGE_SPEC, Replace: [confirm::REPLACE] => confirm::REPLACE_SPEC, + ResetPreferences: [confirm::RESET_PREFS] => confirm::RESET_PREFS_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC, GraphData: [graph_data::KIND] => graph_data::SPEC, @@ -409,6 +410,7 @@ registry! { ScriptRun: [script_run::KIND] => script_run::SPEC, ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, + ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, @@ -504,6 +506,9 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == layer_options::KIND { layer_options::note_set(d, &field, &value); } + if d.kind == "preferences" { + crate::prefs_dialog::note_set(d, &field, &value); + } let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); d.fields.insert(field, value); if let Some(field) = dxf { @@ -584,6 +589,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::GROWTH_KIND { app.session.script_request_stop(); } + if d.kind == script_run::NOTICE_KIND { + script_run::notice_cancel(app, &d); + } // Toolbar-only Flare options start no preview and must not cancel a gesture // that was already active before opening them. The generic parameter dialog has a spec // without a preview, yet previews some commands (Grid Repeat Options) when asked to. diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index 0ce0de9350..1854eba4b9 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -1,7 +1,8 @@ //! Artboard Options (double-click with the Artboard tool, double-click the tool, or the Artboards //! panel's options icon or menu): the artboard's fields, sizes parsed with units, its position //! from a reference point, its background color (`color`: a color as the paint commands take -//! it, or null for none), Show Center Mark and Show Cross Hairs (`showCenterMark`, +//! it, or null for none), its guide label (`guideLabel`: the color its own guides are drawn in, a +//! layer color's name or `#rrggbb`, or null for none), Show Center Mark and Show Cross Hairs (`showCenterMark`, //! `showCrossHairs`), the display marks the canvas draws on the artboard //! (https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/modify-display-settings-of-artboards.html), //! and its video display options, Show Video Safe Areas and Video Ruler Pixel Aspect Ratio @@ -15,7 +16,7 @@ use serde_json::{Value, json}; use vectorcraft_color::Color; -use vectorcraft_doc::Unit; +use vectorcraft_doc::{LAYER_COLORS, LayerColor, Unit}; use vectorcraft_engine::cmd::color_value; use vectorcraft_geom::{Point, Rect}; @@ -32,7 +33,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { confirm, // A new artboard's dialog opens without these; its swatch, checkboxes and Video Ruler Pixel // Aspect Ratio field add them. The Global checkboxes' fields come from the preferences. - inputs: |_| &["color", "showCenterMark", "showCrossHairs", "showVideoSafeAreas", PIXEL_ASPECT, FADE, UPDATE_WHILE_DRAGGING], + inputs: |_| &["color", GUIDE_LABEL, "showCenterMark", "showCrossHairs", "showVideoSafeAreas", PIXEL_ASPECT, FADE, UPDATE_WHILE_DRAGGING], ..DialogSpec::FORM }; @@ -49,7 +50,7 @@ fn placed(d: &Dialog) -> Rect { /// as the Transform panel and the Control bar show an artboard's. A new Width or Height keeps the /// reference point where it was, as their sizes do. /// Then Background Color: the Fill list (None, White, Black; Custom for another color) and a swatch -/// that picks a color of its own, the Show Center Mark, Show Cross Hairs and Show Video Safe Areas +/// that picks a color of its own, the Guide Label row ([`guide_label_row`]), the Show Center Mark, Show Cross Hairs and Show Video Safe Areas /// checkboxes, and the Video Ruler Pixel Aspect Ratio field. Last, under Global, the Fade Region /// Outside Artboard and Update While Dragging checkboxes. fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { @@ -116,6 +117,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if let Some(c) = set { d.fields.insert("color".into(), c.as_ref().map_or(Value::Null, crate::panels::color_json)); } + guide_label_row(ui, d); ui.add_space(8.0); form::check(ui, d, "showCenterMark", tl!("Show Center Mark")); form::check(ui, d, "showCrossHairs", tl!("Show Cross Hairs")); @@ -137,6 +139,64 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// The field of the guide label, as `artboard.setProps` and `artboard.new` take it: a layer +/// color's name, `#rrggbb`, or null for none. +pub(super) const GUIDE_LABEL: &str = "guideLabel"; + +/// The size of the color chip before each name in the Guide Label list. +const CHIP: egui::Vec2 = egui::vec2(16.0, 10.0); + +/// The Guide Label row: a list of None, the layer colors (each after a chip of its color) and +/// Custom, and, while the artboard has a label, a swatch that picks a color of its own. Custom +/// keeps the label's color as a `#rrggbb` value. +fn guide_label_row(ui: &mut egui::Ui, d: &mut Dialog) { + let now = d.fields.get(GUIDE_LABEL).and_then(Value::as_str).and_then(LayerColor::from_label_text); + let shown = match now { + None => "None", + Some(LayerColor::Preset(i)) => LAYER_COLORS.get(usize::from(i)).map_or("Custom", |(n, _)| *n), + Some(LayerColor::Custom(_)) => "Custom", + }; + let mut set = None; + ui.horizontal(|ui| { + let row = form::row_label(ui, tl!("Guide Label:")); + ui.label_inputs_by(row.id, |ui| { + let border = crate::theme::Tokens::get(ui.ctx()).input_border; + let rows = std::iter::once(("None", None)).chain(LAYER_COLORS.iter().map(|(n, c)| (*n, Some(*c)))).chain([("Custom", None)]); + let picked = crate::widgets::combo(ui, "ab-options-guide-label", tl!(shown), 140.0, |ui| { + let mut chosen = None; + for (i, (name, rgb)) in rows.enumerate() { + let chip = egui::IdSalt::new(("ab-guide-label-chip", i)); + let r = egui::Button::selectable(name == shown, (egui::Atom::custom(chip, CHIP), tl!(name))).atom_ui(ui); + if let (Some(rect), Some([cr, cg, cb])) = (r.rect(chip), rgb) { + ui.painter().rect_filled(rect, 1.0, egui::Color32::from_rgb(cr, cg, cb)); + ui.painter().rect_stroke(rect, 1.0, egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); + } + if r.response.clicked() { + chosen = Some(i); + } + } + chosen + }); + match picked { + Some(0) => set = Some(None), + Some(i) if i <= LAYER_COLORS.len() => set = u8::try_from(i - 1).ok().map(|i| Some(LayerColor::Preset(i))), + Some(_) => set = Some(Some(LayerColor::Custom(now.map_or(LAYER_COLORS[0].1, LayerColor::rgb)))), + None => {} + } + if let Some(c) = now { + let mut rgb = c.rgb(); + let swatch_name = format!("{} {}", tl!("Guide Label:"), tl!("Swatches")); + if ui.name_inputs(swatch_name, |ui| ui.color_edit_button_srgb(&mut rgb)).changed() { + set = Some(Some(LayerColor::Custom(rgb))); + } + } + }); + }); + if let Some(c) = set { + d.fields.insert(GUIDE_LABEL.into(), c.map_or(Value::Null, |c| json!(c.label_text()))); + } +} + /// The preference and field of Fade Region Outside Artboard: while the Artboard tool is active, /// the canvas draws everything outside the artboards darker. const FADE: &str = "fadeRegionOutsideArtboard"; @@ -292,8 +352,10 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let a = st.doc.artboards.get(index).ok_or("no artboard")?; let r = a.rect; let color = a.color.as_ref().map(crate::panels::color_json); + let guide_label = a.guide_label.map(LayerColor::label_text); let fields = json!({ "index": index, "name": a.name, "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "color": color, + GUIDE_LABEL: guide_label, "showCenterMark": a.show_center_mark, "showCrossHairs": a.show_cross_hairs, "showVideoSafeAreas": a.show_video_safe_areas, PIXEL_ASPECT: a.video_ruler_pixel_aspect_ratio, }); @@ -374,7 +436,7 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { } /// OK for a new artboard: `artboard.new` with the fields (an empty name gives the default one), -/// the background color picked, the display marks ticked and the Video Ruler Pixel Aspect Ratio +/// the background color and guide label picked, the display marks ticked and the Video Ruler Pixel Aspect Ratio /// typed, and the new artboard becomes the active one. fn confirm_new(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut p = json!({}); @@ -388,6 +450,9 @@ fn confirm_new(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(c) = d.fields.get("color") { p["color"] = c.clone(); } + if let Some(c) = d.fields.get(GUIDE_LABEL).filter(|c| !c.is_null()) { + p[GUIDE_LABEL] = c.clone(); + } for k in ["showCenterMark", "showCrossHairs", "showVideoSafeAreas"] { if d.bool(k) { p[k] = json!(true); diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 86f8fe4531..d1ca76cc58 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -251,7 +251,8 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { "v_scale" => tl!("Vertical Scale"), "baseline_shift" => tl!("Baseline Shift"), "rotation" => tl!("Character Rotation"), - "fill_tint" | "stroke_tint" => tl!("Tint"), + "fill_tint" => tl!("Fill Tint"), + "stroke_tint" => tl!("Stroke Tint"), "stroke_width" => tl!("Weight"), _ => return Err("unknown character style number field".into()), }; @@ -661,18 +662,22 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { ("kerning", tl!("Kerning")), ("tracking", tl!("Tracking")), ] { - ui.label(caption); + let row = ui.label(caption); if d.fields.get(key).is_some_and(Value::is_null) { d.fields.insert(key.into(), json!("")); } - form::text(ui, d, key, 190.0); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, key, 190.0)); ui.end_row(); } - ui.label(tl!("Case")); - choice(ui, d, "case", &[("normal", tl!("Normal")), ("allCaps", tl!("All Caps")), ("smallCaps", tl!("Small Caps"))]); + let row = ui.label(tl!("Case")); + ui.label_inputs_by(row.id, |ui| { + choice(ui, d, "case", &[("normal", tl!("Normal")), ("allCaps", tl!("All Caps")), ("smallCaps", tl!("Small Caps"))]); + }); ui.end_row(); - ui.label(tl!("Position")); - choice(ui, d, "position", &[("normal", tl!("Normal")), ("superscript", tl!("Superscript")), ("subscript", tl!("Subscript"))]); + let row = ui.label(tl!("Position")); + ui.label_inputs_by(row.id, |ui| { + choice(ui, d, "position", &[("normal", tl!("Normal")), ("superscript", tl!("Superscript")), ("subscript", tl!("Subscript"))]); + }); ui.end_row(); for (key, caption) in [ ("underline", tl!("Underline")), @@ -693,20 +698,22 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { } ui.end_row(); } - ui.label(tl!("Character Alignment")); - choice( - ui, - d, - "charAlign", - &[ - ("romanBaseline", tl!("Roman Baseline")), - ("emBoxTop", tl!("Em Box Top/Right")), - ("emBoxCenter", tl!("Em Box Center")), - ("emBoxBottom", tl!("Em Box Bottom/Left")), - ("icfTop", tl!("ICF Top/Right")), - ("icfBottom", tl!("ICF Bottom/Left")), - ], - ); + let row = ui.label(tl!("Character Alignment")); + ui.label_inputs_by(row.id, |ui| { + choice( + ui, + d, + "charAlign", + &[ + ("romanBaseline", tl!("Roman Baseline")), + ("emBoxTop", tl!("Em Box Top/Right")), + ("emBoxCenter", tl!("Em Box Center")), + ("emBoxBottom", tl!("Em Box Bottom/Left")), + ("icfTop", tl!("ICF Top/Right")), + ("icfBottom", tl!("ICF Bottom/Left")), + ], + ); + }); ui.end_row(); }); } @@ -721,20 +728,20 @@ pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) { ("baseline_shift", tl!("Baseline Shift"), "pt"), ("rotation", tl!("Character Rotation"), "°"), ] { - ui.label(caption); + let row = ui.label(caption); if d.fields.get(key).is_some_and(Value::is_null) { d.fields.insert(key.into(), json!("")); } ui.horizontal(|ui| { - form::text(ui, d, key, 160.0); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, key, 160.0)); ui.label(unit); }); ui.end_row(); } - ui.label(tl!("Language:")); + let row = ui.label(tl!("Language:")); let names: Vec<&str> = std::iter::once(" ").chain(vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, _, _)| *name)).collect(); let current = d.fields.get("language").and_then(Value::as_str).unwrap_or("").to_string(); - if let Some(i) = crate::widgets::dropdown(ui, (KIND, "language"), ¤t, &names, 190.0) { + if let Some(i) = ui.label_inputs_by(row.id, |ui| crate::widgets::dropdown(ui, (KIND, "language"), ¤t, &names, 190.0)) { d.fields.insert("language".into(), if i == 0 { Value::Null } else { names.get(i).map_or(Value::Null, |name| json!(name)) }); } ui.end_row(); @@ -798,9 +805,9 @@ fn paint_choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str) { /// the stroke Weight and Overprint Fill and Overprint Stroke, each unset or set. pub(crate) fn color_body(ui: &mut egui::Ui, d: &mut Dialog) { egui::Grid::new("character-style-color").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { - for (key, caption) in [("fill", tl!("Fill")), ("stroke", tl!("Stroke"))] { - ui.label(caption); - paint_choice(ui, d, key); + for (key, caption, tint_name) in [("fill", tl!("Fill"), tl!("Fill Tint")), ("stroke", tl!("Stroke"), tl!("Stroke Tint"))] { + let row = ui.label(caption); + ui.label_inputs_by(row.id, |ui| paint_choice(ui, d, key)); ui.end_row(); let tint_key = format!("{key}_tint"); ui.label(tl!("Tint")); @@ -810,20 +817,20 @@ pub(crate) fn color_body(ui: &mut egui::Ui, d: &mut Dialog) { let linked = d.fields.get(key).and_then(|p| p.get("swatch")).is_some_and(Value::is_string); ui.add_enabled_ui(linked, |ui| { ui.horizontal(|ui| { - form::text(ui, d, &tint_key, 160.0); + form::text_named(ui, d, &tint_key, tint_name, 160.0); ui.label("%"); }); }); ui.end_row(); } - ui.label(tl!("Weight")); + let row = ui.label(tl!("Weight")); if d.fields.get("stroke_width").is_none_or(Value::is_null) { d.fields.insert("stroke_width".into(), json!("")); } let stroked = d.fields.get("stroke").and_then(|p| p.get("type")).and_then(Value::as_str) != Some("none"); ui.add_enabled_ui(stroked, |ui| { ui.horizontal(|ui| { - form::text(ui, d, "stroke_width", 160.0); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, "stroke_width", 160.0)); ui.label("pt"); }); }); @@ -839,11 +846,11 @@ pub(crate) fn opentype_body(ui: &mut egui::Ui, d: &mut Dialog) { let figures: Vec<(&str, &str)> = FIGURE_VALUES.into_iter().zip(crate::panels::opentype::FIGURES).collect(); let positions: Vec<(&str, &str)> = POSITION_VALUES.into_iter().zip(crate::panels::opentype::POSITIONS).collect(); egui::Grid::new("character-style-opentype").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { - ui.label(tl!("Figure:")); - choice(ui, d, "ot_figure", &figures); + let row = ui.label(tl!("Figure:")); + ui.label_inputs_by(row.id, |ui| choice(ui, d, "ot_figure", &figures)); ui.end_row(); - ui.label(tl!("Position:")); - choice(ui, d, "ot_position", &positions); + let row = ui.label(tl!("Position:")); + ui.label_inputs_by(row.id, |ui| choice(ui, d, "ot_position", &positions)); ui.end_row(); for (key, caption) in [ ("ot_liga", tl!("Standard Ligatures")), @@ -929,8 +936,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { opentype_body(ui, d); } else { ui.horizontal(|ui| { - ui.label(tl!("Style Name:")); - form::text(ui, d, "name", 190.0); + let row = ui.label(tl!("Style Name:")); + ui.label_inputs_by(row.id, |ui| form::text(ui, d, "name", 190.0)); }); ui.separator(); if let Ok(attrs) = edited_attrs(d) { @@ -1643,8 +1650,8 @@ mod tests { fn color_tint_and_weight_outside_their_limits_are_errors() { let linked = json!({"type": "solid", "color": {"model": "gray", "k": 0.5}, "swatch": "Ink"}); for (key, value, message) in [ - ("fill_tint", "150", "Tint must be a number from 0 to 100"), - ("stroke_tint", "-1", "Tint must be a number from 0 to 100"), + ("fill_tint", "150", "Fill Tint must be a number from 0 to 100"), + ("stroke_tint", "-1", "Stroke Tint must be a number from 0 to 100"), ("stroke_width", "-1", "Weight must be a number from 0 to 4000000"), ("stroke_width", "thick", "Weight must be a number"), ] { @@ -1837,7 +1844,7 @@ mod tests { }; let shown = crate::i18n::message(crate::i18n::current(), &why); let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).with_accessibility_check(false).build_ui_state( + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( move |ui, app: &mut VectorcraftApp| { if !std::mem::replace(&mut fonts, true) { crate::theme::install_fonts(ui.ctx()); @@ -1857,6 +1864,76 @@ mod tests { } } + #[test] + fn every_section_names_its_inputs_in_both_dialogs() { + for new_style in [false, true] { + for section in ["general", "basic", "advanced", "color", "opentype"] { + let mut app = app(); + if new_style { + app.run("ui.newCharStyle", json!({})).unwrap(); + } else { + app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + open(&mut app, "Body").unwrap(); + } + app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section)); + let mut fonts = false; + // The harness fails a frame that leaves an input without an accessible name. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + assert!(h.unnamed_widgets().is_empty(), "new {new_style}, {section}: {:?}", h.unnamed_widgets()); + } + } + } + + #[test] + fn fill_and_stroke_tint_fields_have_distinct_names() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + for new_style in [false, true] { + let mut app = app(); + app.run("swatch.new", json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap(); + if new_style { + app.run("ui.newCharStyle", json!({})).unwrap(); + } else { + app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + open(&mut app, "Body").unwrap(); + } + let brand = json!(app.session.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap()); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("color")); + d.fields.insert("fill".into(), brand.clone()); + d.fields.insert("stroke".into(), brand); + } + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + for name in ["Fill Tint", "Stroke Tint"] { + let field = h.get_by_role_and_label(Role::TextInput, name); + assert!(!field.accesskit_node().is_disabled(), "new {new_style}: {name} is enabled for a linked swatch"); + } + assert!(h.query_by_role_and_label(Role::TextInput, "Tint").is_none(), "new {new_style}: a field is named only Tint"); + } + } + #[test] fn invalid_number_keeps_last_valid_preview() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index ab79ccf5d6..06e96e45fe 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -63,6 +63,31 @@ pub(crate) fn ask_replace(app: &mut VectorcraftApp, path: &str, typed: &str) { app.ui.dialog = Some(Dialog::new(REPLACE, fields)); } +/// The dialog kind of the question Reset Preferences asks over the Preferences dialog +/// ([`ask_reset_prefs`]). Fields: `message`, `detail`. +pub const RESET_PREFS: &str = "resetPreferences"; + +pub(super) const RESET_PREFS_SPEC: DialogSpec = DialogSpec { confirm: reset_prefs, ..SPEC }; + +/// Ask whether to reset the preferences, over the Preferences dialog open now. Cancel and Escape +/// show Preferences again as it was; OK shows it again with every preference at its default value +/// ([`crate::prefs_dialog::reset_fields`]). Nothing is applied until OK in Preferences. +pub(crate) fn ask_reset_prefs(app: &mut VectorcraftApp) { + let under = app.ui.dialog.take().and_then(|d| serde_json::to_value(d).ok()); + let message = tl!("Reset all preferences to their defaults?"); + let detail = tl!("The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences."); + let fields = json!({"message": message, "detail": detail, super::PARENT: under}); + app.ui.dialog = Some(Dialog::new(RESET_PREFS, fields)); +} + +/// OK on [`ask_reset_prefs`]: Preferences again, its fields at their defaults. +fn reset_prefs(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut prefs = super::parent(d).filter(|p| p.kind == "preferences").ok_or("the dialog it was opened over is no longer open")?; + crate::prefs_dialog::reset_fields(&mut prefs); + app.ui.dialog = Some(prefs); + Ok(Value::Null) +} + /// Most messages kept for later while a dialog is open ([`tell`]). const MAX_WAITING: usize = 16; diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index c87cfb7e63..bbddd222f5 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -120,7 +120,7 @@ fn suffix(kind: &str, key: &str) -> Option<&'static str> { /// The fields of the form dialogs ([`grid`]) that the dialog's own body draws, by dialog kind. fn own_rows(kind: &str) -> &'static [&'static str] { match kind { - "artboardOptions" => &["color", super::artboard_options::PIXEL_ASPECT], + "artboardOptions" => &["color", super::artboard_options::GUIDE_LABEL, super::artboard_options::PIXEL_ASPECT], // The grids' Reference Point is their 9-point locator. "rectangularGrid" | "polarGrid" => &["reference"], _ => &[], diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 2ef43cb8fe..8f5e3b1093 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -1,16 +1,25 @@ //! File › Scripts › Other Script…: choosing a JavaScript file and the warning before it runs -//! (`script.run` runs it), the question a run that keeps adding art asks, and the question quitting -//! asks while a script runs. +//! (`script.run` runs it), the question a run that keeps adding art asks, the question quitting +//! asks while a script runs, and the dialogs a script opens with `alert`, `confirm` and `prompt`. //! //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it //! asks for a `.js` or `.jsx` file (the web opens the browser's file picker). With Preferences › //! General › Show External Script Warning off, the chosen script runs at once. Warning fields: //! `name`, `script` (`script.run`'s params) and `dontShow` (true: turn the warning off). +//! +//! A script's dialog (kind `scriptDialog`) has the fields `kind` (alert, confirm or prompt), +//! `message`, `title` (null: Script Alert), `errorIcon`, `noAsDefault` and `value` (the prompt's +//! text), and takes `answer`: `ok` (alert, prompt), `yes` or `no` (confirm), `cancel` (prompt) or +//! `stop`. OK, Enter or `ui.dialog.confirm` without an `answer` gives the default button's answer. +//! Escape or `ui.dialog.cancel` gives Cancel for a prompt, No for a confirm and Stop for an alert. +//! Stop ends the run and puts back everything it did. use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; +use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; +use vectorcraft_engine::script::{DialogAnswer, ScriptDialog}; -use super::DialogSpec; +use super::{DialogAction, DialogSpec}; use crate::state::Dialog; use crate::theme::{self, Tokens}; use crate::{FilePick, VectorcraftApp, widgets}; @@ -21,6 +30,19 @@ pub const KIND: &str = "scriptRun"; pub const GROWTH_KIND: &str = "scriptGrowth"; /// The dialog kind of the question quitting asks while a script runs. pub const CLOSE_KIND: &str = "scriptClose"; +/// The dialog kind of a script's `alert`, `confirm` and `prompt`. +pub const NOTICE_KIND: &str = "scriptDialog"; + +pub(super) const NOTICE_SPEC: DialogSpec = DialogSpec { + heading: notice_heading, + body_with_actions: Some(notice_body), + confirm: notice_confirm, + ok: None, + inputs: |_| &["answer"], + min_width: 360.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Run Script").into(), @@ -145,3 +167,170 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result } Ok(Value::Null) } + +/// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which +/// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. +pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND); + if app.ui.dialog.is_some() { + return; + } + let mut fields = json!({}); + if let Some(notice) = notice { + fields[super::PARENT] = serde_json::to_value(notice).unwrap_or_default(); + } + app.ui.dialog = Some(Dialog::new(CLOSE_KIND, fields)); +} + +/// Closes the question quitting asks once the run it asks about has ended, and forgets the +/// script's dialog it was asked over once the run no longer waits at that dialog, so Cancel does +/// not show it again. +pub(crate) fn settle_close(app: &mut VectorcraftApp) { + if !app.ui.dialog.as_ref().is_some_and(|d| d.kind == CLOSE_KIND) { + return; + } + if !app.session.script_running() { + app.ui.dialog = None; + } else if app.session.script_dialog().is_none() + && let Some(d) = app.ui.dialog.as_mut() + { + d.fields.remove(super::PARENT); + } +} + +/// Shows the dialog the running script waits at. +pub(crate) fn open_notice(app: &mut VectorcraftApp, d: &ScriptDialog) { + let fields = json!({ + "kind": d.kind.id(), + "message": d.message, + "title": d.title, + "errorIcon": d.error_icon, + "noAsDefault": d.no_as_default, + "value": d.preset, + }); + app.ui.dialog = Some(Dialog::new(NOTICE_KIND, fields)); +} + +/// The dialog's heading: the script's title on one line, or Script Alert. +pub(crate) fn notice_heading(d: &Dialog) -> String { + match d.fields.get("title").and_then(Value::as_str) { + Some(title) => shown_text(title, false), + None => tl!("Script Alert").into(), + } +} + +/// The answer of the default button: OK, or for a confirm Yes, or No with `noAsDefault`. +fn default_answer(d: &Dialog) -> &'static str { + match (d.str("kind").as_str(), d.bool("noAsDefault")) { + ("confirm", true) => "no", + ("confirm", false) => "yes", + _ => "ok", + } +} + +/// A button that is the primary one when it is the default. +fn answer_button(ui: &mut egui::Ui, label: &str, default: bool) -> bool { + if default { widgets::primary_button_enabled(ui, label, true).clicked() } else { widgets::secondary_button(ui, label).clicked() } +} + +fn notice_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let t = Tokens::get(ui.ctx()); + let kind = d.str("kind"); + let message = shown_text(&d.str("message"), true); + ui.horizontal_top(|ui| { + if d.bool("errorIcon") { + ui.label(egui::RichText::new("!").font(theme::semibold(22.0)).color(t.error)); + ui.add_space(8.0); + } + egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| ui.label(&message)); + }); + if kind == "prompt" { + ui.add_space(8.0); + let name = cut_to(&shown_text(&message, false), 200).to_string(); + super::form::text_edit_named(ui, d, "value", &name, ui.available_width()); + let value = d.str("value"); + if value.len() > MAX_PROMPT_BYTES { + d.fields.insert("value".into(), json!(cut_to(&value, MAX_PROMPT_BYTES))); + } + } + ui.add_space(16.0); + let default = default_answer(d); + let mut answer = None; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + let buttons: &[(&str, &str)] = match kind.as_str() { + "confirm" => &[("yes", "Yes"), ("no", "No")], + "prompt" => &[("ok", "OK"), ("cancel", "Cancel")], + _ => &[("ok", "OK")], + }; + for (id, label) in buttons { + if answer_button(ui, tl!(label), *id == default) { + answer = Some(*id); + } + ui.add_space(8.0); + } + // The row runs right to left: Stop goes at its left end. + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if widgets::secondary_button(ui, tl!("Stop")).clicked() { + answer = Some("stop"); + } + }); + }); + if answer.is_none() && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + answer = Some(default); + } + let Some(answer) = answer else { return DialogAction::None }; + d.fields.insert("answer".into(), json!(answer)); + DialogAction::Confirm +} + +/// Gives the running script the dialog's `answer`, or the default button's. +fn notice_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let answer = d.fields.get("answer").and_then(Value::as_str).unwrap_or(default_answer(d)); + give(app, d, answer) +} + +/// Escape or Cancel: Cancel for a prompt, No for a confirm and Stop for an alert. +pub(super) fn notice_cancel(app: &mut VectorcraftApp, d: &Dialog) { + let answer = match d.str("kind").as_str() { + "prompt" => "cancel", + "confirm" => "no", + _ => "stop", + }; + let _ = give(app, d, answer); +} + +fn give(app: &mut VectorcraftApp, d: &Dialog, answer: &str) -> Result { + let given = match (d.str("kind").as_str(), answer) { + (_, "stop") => None, + ("alert", "ok") => Some(DialogAnswer::Ok), + ("confirm", "yes") => Some(DialogAnswer::Confirm(true)), + ("confirm", "no") => Some(DialogAnswer::Confirm(false)), + ("prompt", "ok") => Some(DialogAnswer::Prompt(Some(d.str("value")))), + ("prompt", "cancel") => Some(DialogAnswer::Prompt(None)), + (kind, _) => return Err(format!("`answer` for this {kind} dialog must be one of: {}", answers_for(kind))), + }; + match given { + None => { + app.session.script_request_stop(); + } + Some(a) => { + // Refused while the dialog still waits: the text is too long, and the dialog stays open. + if !app.session.script_answer(a) && app.session.script_dialog().is_some() { + return Err(format!("the prompt's text is longer than {MAX_PROMPT_BYTES} bytes")); + } + } + } + if app.ui.dialog.as_ref().is_some_and(|open| open.kind == NOTICE_KIND) { + app.ui.dialog = None; + } + Ok(Value::Null) +} + +fn answers_for(kind: &str) -> &'static str { + match kind { + "confirm" => "yes, no, stop", + "prompt" => "ok, cancel, stop", + _ => "ok, stop", + } +} diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index c5bdfea5c8..2ad8bdf213 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1755,6 +1755,64 @@ fn new_artboard_options_give_the_new_artboard_its_background_color() { } } +/// Artboard Options shows the artboard's guide label on its Guide Label: row (None, a layer color's +/// name, or Custom). OK sets a label picked there in one undo step, keeps it while another field +/// changes, and a null `guideLabel` clears it; Cancel leaves it. OK with nothing changed adds no +/// undo step, and a new artboard's Artboard Options gives it the label picked. +#[test] +fn artboard_options_shows_sets_and_clears_the_guide_label() { + let mut app = app(); + let label = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards[0].guide_label.map(vectorcraft_doc::LayerColor::label_text); + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let lines = |app: &mut VectorcraftApp| { + let text = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx())); + text.lines().map(str::trim).map(str::to_string).collect::>() + }; + crate::dialogs::artboard_options::open(&mut app).unwrap(); + let shown = lines(&mut app); + assert!(shown.iter().any(|l| l == "Guide Label:"), "{shown:?}"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["guideLabel"], json!(null)); + let u = undo(&app); + super::confirm(&mut app).unwrap(); + assert_eq!((label(&app), undo(&app)), (None, u), "OK with nothing changed"); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("Orange")); + super::confirm(&mut app).unwrap(); + assert_eq!((label(&app).as_deref(), undo(&app)), (Some("Orange"), u + 1)); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["guideLabel"], json!("Orange")); + assert!(lines(&mut app).iter().any(|l| l == "Orange")); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("#123456")); + cancel(&mut app); + assert_eq!(label(&app).as_deref(), Some("Orange"), "Cancel leaves it"); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + assert!(lines(&mut app).iter().any(|l| l == "Orange")); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("#123456")); + super::confirm(&mut app).unwrap(); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + assert!(lines(&mut app).iter().any(|l| l == "Custom")); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Card")); + super::confirm(&mut app).unwrap(); + assert_eq!(label(&app).as_deref(), Some("#123456"), "kept while another field changes"); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!("purple")); + assert!(super::confirm(&mut app).is_err(), "a name in other letter case is refused"); + assert_eq!(label(&app).as_deref(), Some("#123456")); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), json!(null)); + super::confirm(&mut app).unwrap(); + assert_eq!(label(&app), None); + for (picked, want) in [(Some(json!("Teal")), Some("Teal")), (None, None)] { + app.run("ui.newArtboard", json!({})).unwrap(); + if let Some(c) = picked { + app.ui.dialog.as_mut().unwrap().fields.insert("guideLabel".into(), c); + } + super::confirm(&mut app).unwrap(); + let ab = app.session.doc().unwrap().doc.artboards.last().cloned().unwrap(); + assert_eq!(ab.guide_label.map(vectorcraft_doc::LayerColor::label_text).as_deref(), want); + } +} + /// Artboard Options shows Show Center Mark and Show Cross Hairs, ticked as the artboard has them /// whether it opens from the Artboards panel or from a double-click with the Artboard tool. OK /// sets them in one undo step, and a new artboard's Artboard Options gives it the ones ticked. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 354d811a34..e69dc7b97c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -276,6 +276,7 @@ font-technology Variable Променливи Average… Усредняване… Axis: Ос: Background Color: Цвят на фона: + Guide Label: Етикет на водачите: Show Center Mark Показване на централен знак Show Cross Hairs Показване на кръстосани линии Show Video Safe Areas Показване на безопасните видеозони @@ -1826,6 +1827,7 @@ font-technology Variable Променливи Lock Grid Заключване на мрежата Lock Guides Заключване на водачите Lock Guides by Default Заключване на водачите по подразбиране + Artboard Guides with Cmd/Ctrl + Ruler Drag Водачи за работната област с Cmd/Ctrl + плъзгане от линийка Lock Others Заключване на другите Lock Slices Заключване на фрагментите Lock Station Point Заключване на базовата точка @@ -2277,6 +2279,8 @@ font-technology Variable Променливи Other Layers Други слоеве Other Libraries Други библиотеки Other Library… Друга библиотека… + Some scripts were not listed Някои скриптове не са изброени + The Scripts folder cannot be read Папката Scripts не може да бъде прочетена Other Script… Друг скрипт… Out of Gamut Warning Предупреждение за излизане извън цветовата гама Out of Web Color Warning Предупреждение за цвят извън уеб палитрата @@ -2744,6 +2748,12 @@ digits Malayalam Малаялам Reset OpenType Features Нулиране на OpenType характеристиките Reset Panel Нулиране на панела Reset Preferences Нулиране на настройките + Export Preferences… Експортиране на настройките… + Import Preferences… Импортиране на настройките… + Save the applied preferences to a JSON file Запазване на приложените настройки във файл JSON + Apply the preferences in a file Export Preferences saved Прилагане на настройките от файл, запазен с „Експортиране на настройките“ + Export Preferences Експортиране на настройките + Import Preferences Импортиране на настройките Search Preferences Търсене в настройките No settings found Няма намерени настройки Reset Profiles Нулиране на профилите @@ -2766,6 +2776,8 @@ digits Malayalam Малаялам Responsive Адаптивен Restore Възстановяване Restore every preference to its default (applied on OK) Възстановяване на всички настройки по подразбиране (прилага се при ОПК) + Reset all preferences to their defaults? Да се нулират ли всички настройки до стойностите по подразбиране? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Стойностите по подразбиране се прилагат, когато щракнете върху ОК в Настройки. Отказ там запазва текущите ви настройки. Restore Recovered Documents Възстановяване на възстановените документи Restored documents open unsaved: save them to keep them. Възстановените документи се отварят незаписани: запазете ги, за да ги съхраните. Restrict printing, editing and other tasks Ограничаване на печата, редактирането и други задачи @@ -3059,6 +3071,13 @@ digits Malayalam Малаялам Quest Outline Квест Coin Shine Монета Boss Alert Бос + Status Effects Статус ефекти + Poison Tint Отрова + Freeze Edge Замразяване + Burn Aura Изгаряне + Stun Pulse Зашеметяване + Stealth Fade Скритост + Shield Buff Щит Shape Фигура Shape Builder Създател на фигури Shape Builder Regions Области на създателя на фигури @@ -3476,6 +3495,8 @@ digits Malayalam Малаялам Tiles are numbered across, then down; leave the range empty for every tile. Плочките се номерират напречно, след това надолу; оставете диапазона празен за всяка плочка. Copies per Sheet (as many as fit, in a grid) Копия на лист (колкото се побират, в мрежа) Tint Оттенък + Fill Tint Оттенък на запълване + Stroke Tint Оттенък на щриха Tip extends past the end point Връхът продължава след крайната точка Tip on the end point Връх върху крайната точка Title Case Заглавни букви @@ -3966,6 +3987,7 @@ axis Both И двете Stop Script Спри скрипта Show External Script Warning Показвай предупреждение за външни скриптове A Script Is Running Изпълнява се скрипт + Script Alert Известие от скрипт A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. Do not show this warning again Не показвай повече това предупреждение Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново. @@ -4506,6 +4528,20 @@ axis Both И двете @msg unknown overprints `{o}` (preserve, simulate or discard) непознати надписи `{o}` (запазване, симулиране или отхвърляне) @msg unknown panel `{raw}` непознат панел `{raw}` @msg unknown preference `{key}` непозната настройка `{key}` +@msg Preferences imported. Настройките са импортирани. +@msg not a preferences file: {e} не е файл с настройки: {e} +@msg not a preferences file: no JSON object не е файл с настройки: няма обект JSON +@msg not a preferences file (format `{format}`) не е файл с настройки (формат `{format}`) +@msg not a preferences file: no `format` не е файл с настройки: няма `format` +@msg not a preferences file: no `version` не е файл с настройки: няма `version` +@msg not a preferences file: no `prefs` не е файл с настройки: няма `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) файлът е запазен от по-нова версия на VectorCraft (версия {v}) +@msg the file holds no preferences файлът не съдържа настройки +@msg `{key}` names a folder, which preferences files leave out `{key}` указва папка, а файловете с настройки не съдържат папки +@msg the file is larger than 1 MB файлът е по-голям от 1 MB +@msg give `path` or `data` посочете `path` или `data` +@msg `{key}` must be an object `{key}` трябва да бъде обект +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` се изпълнява самостоятелно, а не като стъпка от пакет @msg unknown preset (one of {_1}) непозната предварителна настройка (една от {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) непозната предварителна настройка `{name}` (висока, средна, ниска или запазена: вижте flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) непозната предварителна настройка `{name}` (вижте flattener.presets.list) @@ -5421,6 +5457,7 @@ file-filter Flattener presets Предварителни настройки за file-filter PDF presets Предварителни настройки за PDF file-filter PDF-compatible .ai Съвместими с PDF .ai файлове file-filter Print presets Предварителни настройки за печат +file-filter Preferences Настройки file-filter Export presets Набори за експортиране file-filter SVG Compressed Компресиран SVG file-filter Swatch libraries Библиотеки с образци @@ -5502,6 +5539,7 @@ theme Appearance Външен вид Preview (1 inch on the page) Преглед (1 инч на страницата) Set as Default Задаване по подразбиране out from a highlighted edge to place its dimension | навън от осветен ръб, за да поставите размера му | + two points, then move and click to place an aligned, horizontal or vertical dimension | върху две точки, после преместете и щракнете, за да поставите подравнен, хоризонтален или вертикален размер | cancels | Double-click the tool for options отказва | Двойно щракване върху инструмента за опции Angular Ъглов Away from the Line Встрани от линията @@ -5531,14 +5569,17 @@ theme Appearance Външен вид @msg Invalid drawing scale Невалиден мащаб на чертежа @msg Invalid real scale Невалиден реален мащаб @msg Measured anchor no longer exists Измерената опорна точка вече не съществува +@msg Invalid measured point Невалидна измерена точка @msg Measured segment no longer exists Измереният сегмент вече не съществува @msg Non-finite dimension Размерът не е крайно число +@msg Only linear dimensions are horizontal or vertical Само линейните размери са хоризонтални или вертикални @msg Scale Text Attributes: selected type has no scale to bake Мащабиране на текстови атрибути: избраният текст няма мащаб за прилагане @msg Scale must be drawing:real, for example 1:10 Мащабът трябва да е чертеж:реалност, например 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Съотношението на мащаба трябва да е между 1:1000000 и 1000000:1 @msg Second measured segment no longer exists Вторият измерен сегмент вече не съществува @msg Unknown dimension mode Непознат режим на размера @msg Unknown dimension option {k} Непозната опция за размер {k} +@msg Unknown dimension orientation Непозната ориентация на размера @msg Unknown dimension style Непознат стил на размера @msg Unknown unit Непозната единица Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Затваря кръговите краища на отворени профили. При частично завъртане срязаните страни остават отворени. @@ -5858,6 +5899,12 @@ axis Y Axis Y ос Flag Флаг Crosshair Мерник Checkpoint Контролна точка + Inventory Icons Икони на инвентара + Sword Меч + Shield Щит + Potion Отвара + Key Ключ + Gem Скъпоценен камък Open Symbol Library Отваряне на библиотека със символи Save Symbol Library Запазване на библиотека със символи Save Symbol Library… Запази библиотека със символи… @@ -6461,3 +6508,28 @@ breakText Glyphs Глифи @msg side is left or right, not `{s}` side е left или right, а не `{s}` Edit Custom Dictionary Редактиране на потребителски речник Entry: Запис: +# Script Console + Script Console Конзола за скриптове + Clear Script Console Изчистване на конзолата за скриптове + Copy Script Console Копиране на конзолата за скриптове + Copy All Копиране на всичко + Copy Selected Копиране на избраното + Finished Завършен + Ended with an error Прекратен с грешка + Out of fuel Достигнат лимит на инструкциите + Ended at a host limit Прекратен при лимит на хоста + Ended at a limit Прекратен при лимит + Stopped Спрян + Ended by an internal fault Прекратен поради вътрешна грешка + time unavailable времето не е налично + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} най-бавни: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} извикване към хоста|{n} извиквания към хоста +@plural {n} earlier line dropped|{n} earlier lines dropped {n} по-ранен ред премахнат|{n} по-ранни реда премахнати +@plural {n} line cut|{n} lines cut {n} ред съкратен|{n} реда съкратени + +# Deferred plug-in effects + Refresh Deferred Effects Обновяване на отложените ефекти + Deferred Effects Отложени ефекти diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d1fc0ea540..fc4610e0d0 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -62,6 +62,8 @@ Scripts Skripte Check Script… Provjeri skriptu… Check Script Provjeri skriptu + Some scripts were not listed Neke skripte nisu navedene + The Scripts folder cannot be read Folder Scripts se ne može pročitati Other Script… Druga skripta… Document Setup… Postavke dokumenta… Switch Units Promijeni jedinice @@ -601,6 +603,7 @@ Show Guides Prikaži vodilice Lock Guides Zaključaj vodilice Lock Guides by Default Zaključaj vodilice po zadanom + Artboard Guides with Cmd/Ctrl + Ruler Drag Vodilice radne ploče uz Cmd/Ctrl + povlačenje s ravnala Unlock Guides Otključaj vodilice Make Guides Napravi vodilice Release Guides Oslobodi vodilice @@ -773,6 +776,13 @@ Quest Outline Zadatak Coin Shine Novčić Boss Alert Bos + Status Effects Statusni efekti + Poison Tint Otrov + Freeze Edge Zamrzavanje + Burn Aura Izgaranje + Stun Pulse Omamljenost + Stealth Fade Nevidljivost + Shield Buff Štit Outlines and Rules Obrisi i linije Hand-Drawn Ručno crtano Gradient Finishes Gradijentne završnice @@ -2255,6 +2265,8 @@ digits Malayalam Malajalam Green Zelena Shifts the tints of global and spot colors; other colors stay. Pomjera nijanse globalnih i spot boja; ostale boje ostaju. Tint Preliv + Fill Tint Preliv ispune + Stroke Tint Preliv poteza Color Guide Options Opcije vodiča za boje Less Manje Steps: Koraci: @@ -2622,6 +2634,7 @@ digits Malayalam Malajalam File Dimensions Dimenzije datoteke Transforms Transformacije Background Color: Boja pozadine: + Guide Label: Oznaka vodilica: Show Center Mark Prikaži oznaku centra Show Cross Hairs Prikaži končanicu Show Video Safe Areas Prikaži sigurne oblasti za video @@ -3712,6 +3725,12 @@ theme Appearance Izgled Real-time Drawing and Editing Crtanje i uređivanje u stvarnom vremenu Render Threads (-1 = Automatic) Niti iscrtavanja (-1 = automatski) Reset Preferences Vrati postavke na početne + Export Preferences… Izvezi postavke… + Import Preferences… Uvezi postavke… + Save the applied preferences to a JSON file Sačuvaj primijenjene postavke u JSON datoteku + Apply the preferences in a file Export Preferences saved Primijeni postavke iz datoteke sačuvane naredbom Izvezi postavke + Export Preferences Izvezi postavke + Import Preferences Uvezi postavke Search Preferences Pretraga postavki No settings found Nema pronađenih postavki Scale Corners Skaliraj uglove @@ -4091,6 +4110,8 @@ font-technology Variable Varijabilni Preferences Postavke Previous Prethodno Restore every preference to its default (applied on OK) Vrati svaku postavku na zadanu vrijednost (primjenjuje se na U redu) + Reset all preferences to their defaults? Vratiti sve postavke na zadane vrijednosti? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Zadane vrijednosti primjenjuju se kada kliknete U redu u Postavkama. Otkaži tamo zadržava vaše trenutne postavke. Smaller ↔ Larger Manje ↔ veće Smart Guides (View → Smart Guides) Pametne vodilice (Prikaz → Pametne vodilice) Couldn't save recovery data: {e} Nije moguće sačuvati podatke za oporavak: {e} @@ -4331,6 +4352,7 @@ imageTrace Outline Obris Stop Script Zaustavi skriptu Show External Script Warning Prikaži upozorenje za vanjske skripte A Script Is Running Skripta se izvršava + Script Alert Upozorenje skripte A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. Do not show this warning again Ne prikazuj više ovo upozorenje Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite. @@ -4905,6 +4927,20 @@ imageTrace Outline Obris @msg unknown overprints `{o}` (preserve, simulate or discard) nepoznati pretisci `{o}` (preserve, simulate ili discard) @msg unknown panel `{raw}` nepoznat panel `{raw}` @msg unknown preference `{key}` nepoznata postavka `{key}` +@msg Preferences imported. Postavke su uvezene. +@msg not a preferences file: {e} nije datoteka postavki: {e} +@msg not a preferences file: no JSON object nije datoteka postavki: nema JSON objekta +@msg not a preferences file (format `{format}`) nije datoteka postavki (format `{format}`) +@msg not a preferences file: no `format` nije datoteka postavki: nema `format` +@msg not a preferences file: no `version` nije datoteka postavki: nema `version` +@msg not a preferences file: no `prefs` nije datoteka postavki: nema `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) datoteku je sačuvala novija verzija programa VectorCraft (verzija {v}) +@msg the file holds no preferences datoteka ne sadrži postavke +@msg `{key}` names a folder, which preferences files leave out `{key}` navodi folder, a datoteke postavki ne sadrže foldere +@msg the file is larger than 1 MB datoteka je veća od 1 MB +@msg give `path` or `data` navedite `path` ili `data` +@msg `{key}` must be an object `{key}` mora biti objekat +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` se pokreće samostalno, ne kao korak paketa @msg unknown preset (one of {_1}) nepoznat predložak (jedan od {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) nepoznat predložak `{name}` (high, medium, low ili sačuvani: vidi flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) nepoznat predložak `{name}` (vidi flattener.presets.list) @@ -5445,6 +5481,7 @@ file-filter Swatch libraries Biblioteke uzoraka boja file-filter Flattener presets Predlošci spljoštavanja file-filter PDF presets PDF predlošci file-filter Print presets Predlošci štampanja +file-filter Preferences Postavke file-filter Export presets Predlošci izvoza file-filter SVG Compressed Komprimirani SVG file-filter PDF-compatible .ai .ai kompatibilan s PDF-om @@ -5551,6 +5588,7 @@ mark-style Japanese Japanski Preview (1 inch on the page) Pregled (1 inč na stranici) Set as Default Postavi kao zadano out from a highlighted edge to place its dimension | od istaknute ivice da postavite njenu kotu | + two points, then move and click to place an aligned, horizontal or vertical dimension | na dvije tačke, zatim pomjerite i kliknite da postavite poravnatu, horizontalnu ili vertikalnu kotu | cancels | Double-click the tool for options otkazuje | Dvostruki klik na alat za opcije Angular Ugaono Away from the Line Dalje od linije @@ -5579,14 +5617,17 @@ mark-style Japanese Japanski @msg Invalid drawing scale Nevažeća skala crteža @msg Invalid real scale Nevažeća stvarna skala @msg Measured anchor no longer exists Izmjereno sidro više ne postoji +@msg Invalid measured point Neispravna izmjerena tačka @msg Measured segment no longer exists Izmjereni segment više ne postoji @msg Non-finite dimension Nekonačna kota +@msg Only linear dimensions are horizontal or vertical Samo linearne kote su horizontalne ili vertikalne @msg Scale Text Attributes: selected type has no scale to bake Skaliraj atribute teksta: odabrani tekst nema skalu za primjenu @msg Scale must be drawing:real, for example 1:10 Skala mora biti crtež:stvarno, npr. 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Omjer skale mora biti između 1:1000000 i 1000000:1 @msg Second measured segment no longer exists Drugi izmjereni segment više ne postoji @msg Unknown dimension mode Nepoznat način kote @msg Unknown dimension option {k} Nepoznata opcija kote {k} +@msg Unknown dimension orientation Nepoznata orijentacija kote @msg Unknown dimension style Nepoznat stil kote @msg Unknown unit Nepoznata jedinica Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Zatvori kružne krajeve otvorenih profila. Djelimična izvlačenja zadržavaju otvorene rezane strane. @@ -5902,6 +5943,12 @@ axis Y Axis Y osa Flag Zastava Crosshair Nišan Checkpoint Kontrolna tačka + Inventory Icons Ikone inventara + Sword Mač + Shield Štit + Potion Napitak + Key Ključ + Gem Dragulj Open Symbol Library Otvori biblioteku simbola Save Symbol Library Sačuvaj biblioteku simbola Save Symbol Library… Sačuvaj biblioteku simbola… @@ -6512,3 +6559,28 @@ shape Open Otvoren @msg side is left or right, not `{s}` side je left ili right, a ne `{s}` Edit Custom Dictionary Uredi prilagođeni rječnik Entry: Unos: +# Script Console + Script Console Konzola skripti + Clear Script Console Očisti konzolu skripti + Copy Script Console Kopiraj konzolu skripti + Copy All Kopiraj sve + Copy Selected Kopiraj odabrano + Finished Završeno + Ended with an error Završeno s greškom + Out of fuel Dostignuto ograničenje instrukcija + Ended at a host limit Završeno na ograničenju hosta + Ended at a limit Završeno na ograničenju + Stopped Zaustavljeno + Ended by an internal fault Završeno zbog interne greške + time unavailable vrijeme nije dostupno + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} najsporije: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} poziv hosta|{n} poziva hosta|{n} poziva hosta +@plural {n} earlier line dropped|{n} earlier lines dropped {n} raniji red uklonjen|{n} ranija reda uklonjena|{n} ranijih redova uklonjeno +@plural {n} line cut|{n} lines cut {n} red skraćen|{n} reda skraćena|{n} redova skraćeno + +# Deferred plug-in effects + Refresh Deferred Effects Osvježi odgođene efekte + Deferred Effects Odgođeni efekti diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9e77ecb32f..44562ac0f1 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -35,6 +35,7 @@ on the canvas to create one al llenç per crear-ne un on the canvas to create one ( al llenç per crear-ne un ( out from a highlighted edge to place its dimension | des d’una vora ressaltada cap enfora per col·locar-ne la dimensió | + two points, then move and click to place an aligned, horizontal or vertical dimension | dos punts, després moveu i feu clic per col·locar una dimensió alineada, horitzontal o vertical | over paths to roughen their outlines | sobre traçats per fer aspres els contorns | over paths, and hold still to keep going | sobre traçats i mantén el punter quiet per continuar | right or left to zoom in or out | a la dreta o a l’esquerra per ampliar o reduir | @@ -427,6 +428,7 @@ antiAlias Sharp Nítid B5 B5 Back Enrere Background Color: Color de fons: + Guide Label: Etiqueta de les guies: Background Contents Contingut del fons Background Level Nivell de fons Background: Fons: @@ -453,6 +455,12 @@ antiAlias Sharp Nítid Flag Bandera Crosshair Punt de mira Checkpoint Punt de control + Inventory Icons Icones d’inventari + Sword Espasa + Shield Escut + Potion Poció + Key Clau + Gem Gemm Batch Lot Batch… Lot… Bearing Orientació @@ -2349,6 +2357,7 @@ digits Malayalam Malaiàlam Lock Grid Bloca la quadrícula Lock Guides Bloca les guies Lock Guides by Default Bloca les guies per defecte + Artboard Guides with Cmd/Ctrl + Ruler Drag Guies del tauler amb Cmd/Ctrl + arrossegament des de la regla Lock Others Bloca la resta Lock Selected Bloca la selecció Lock Slices Bloca els talls @@ -3474,6 +3483,12 @@ digits Malayalam Malaiàlam Reset Painting Restableix Pintura Reset Panel Restableix el panell Reset Preferences Restableix les preferències + Export Preferences… Exporta les preferències… + Import Preferences… Importa les preferències… + Save the applied preferences to a JSON file Desa les preferències aplicades en un fitxer JSON + Apply the preferences in a file Export Preferences saved Aplica les preferències d’un fitxer desat amb Exporta les preferències + Export Preferences Exporta les preferències + Import Preferences Importa les preferències Search Preferences Cerca a les preferències No settings found No s'ha trobat cap paràmetre Reset Printing and Proofing Restableix impressió i prova @@ -3511,6 +3526,8 @@ digits Malayalam Malaiàlam Responsive Adaptatiu Restore Restaura Restore every preference to its default (applied on OK) Restaura cada preferència al seu valor predeterminat (s’aplica en prémer D’acord) + Reset all preferences to their defaults? Voleu restablir totes les preferències als valors predeterminats? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Els valors predeterminats s’apliquen quan feu clic a D’acord a Preferències. Cancel·la allà conserva les preferències actuals. Restore Recovered Documents Restaura els documents recuperats Restored documents open unsaved: save them to keep them. Els documents restaurats s’obren sense desar: desa’ls per conservar-los. Restrict printing, editing and other tasks Restringeix la impressió, l’edició i altres tasques @@ -3938,6 +3955,13 @@ digits Malayalam Malaiàlam Quest Outline Missió Coin Shine Moneda Boss Alert Cap + Status Effects Efectes d’estat + Poison Tint Verí + Freeze Edge Congelació + Burn Aura Cremada + Stun Pulse Atordiment + Stealth Fade Sigil + Shield Buff Escut Shape Forma Shape Builder Constructor de formes Shape Builder Delete Suprimeix del constructor de formes @@ -4467,6 +4491,8 @@ digits Malayalam Malaiàlam Tilt Inclinació Time (hhmmss) Hora (hhmmss) Tint To + Fill Tint To de farciment + Stroke Tint To del traç Tint Reduction Reducció de to Tints Tons Tints and Shades Tons i ombres @@ -5119,6 +5145,7 @@ digits Malayalam Malaiàlam @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis ha de ser "vertical", "horizontal" o un angle en graus, no `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" fons {other}: transparent, blanc, negre o un color com "#ff8800" @msg bad color {v} color incorrecte {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` és null, el nom d’un color de capa o #rrggbb @msg bad colour `{hex}` (#rrggbb) color incorrecte `{hex}` (#rrggbb) @msg bad page tree arbre de pàgines incorrecte @msg bad shortcut drecera incorrecta @@ -5176,6 +5203,7 @@ digits Malayalam Malaiàlam Stop Script Atura l'script Show External Script Warning Mostra l'avís dels scripts externs A Script Is Running S'està executant un script + Script Alert Avís de l'script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. Do not show this warning again No tornis a mostrar aquest avís Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir. @@ -5189,6 +5217,9 @@ digits Malayalam Malaiàlam @msg the script is too large to run l'script és massa gran per executar-lo @msg a drag or an undo group is open; finish it before running a script hi ha un arrossegament o un grup de desfer obert; acabeu-lo abans d'executar un script @msg the script left a document that cannot be kept l'script ha deixat un document que no es pot conservar +@msg the script is no longer in the Scripts folder l'script ja no és a la carpeta Scripts + Some scripts were not listed Alguns scripts no s'han llistat + The Scripts folder cannot be read No es pot llegir la carpeta Scripts @msg the script's run is no longer available l'execució de l'script ja no està disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped una ordre fallida ha canviat passos de desfer que no s'han pogut restaurar, així que l'script s'ha aturat @msg a recovery copy could not be written, so the script was not run no s'ha pogut escriure una còpia de recuperació, per tant l'script no s'ha executat @@ -5356,6 +5387,7 @@ digits Malayalam Malaiàlam @msg Make Guides: select paths Crea guies: seleccioneu traçats @msg mask art ends outside a mask dictionary l’art de la màscara acaba fora d’un diccionari de màscara @msg Measured anchor no longer exists El punt d’ancoratge mesurat ja no existeix +@msg Invalid measured point El punt mesurat no és vàlid @msg Measured segment no longer exists El segment mesurat ja no existeix @msg missing `folder` falta `folder` @msg missing `id` (see plugin.list) falta `id` (vegeu plugin.list) @@ -5515,6 +5547,7 @@ digits Malayalam Malaiàlam @msg node {_1} is not text el node {_1} no és text @msg node {_1} is on a locked artboard el node {_1} és en un tauler bloquejat @msg Non-finite dimension Cota no finita +@msg Only linear dimensions are horizontal or vertical Només les dimensions lineals són horitzontals o verticals @msg not a blend no és una fusió @msg not a DXF drawing no és un dibuix DXF @msg not a file no és un fitxer @@ -5885,6 +5918,7 @@ digits Malayalam Malaiàlam @msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode control desconegut `{name}`: fillStroke, coloring, drawMode o screenMode @msg Unknown dimension mode Mode de dimensió desconegut @msg Unknown dimension option {k} Opció de dimensió desconeguda {k} +@msg Unknown dimension orientation Orientació de dimensió desconeguda @msg Unknown dimension style Estil de dimensió desconegut @msg unknown effect `{id}` efecte desconegut `{id}` @msg unknown format format desconegut @@ -5904,6 +5938,20 @@ digits Malayalam Malaiàlam @msg missing `{path}` falta `{path}` @msg `{path}` must be {expected}, not {got} `{path}` ha de ser {expected}, no {got} @msg unknown preference `{key}` preferència desconeguda `{key}` +@msg Preferences imported. S’han importat les preferències. +@msg not a preferences file: {e} no és un fitxer de preferències: {e} +@msg not a preferences file: no JSON object no és un fitxer de preferències: no hi ha cap objecte JSON +@msg not a preferences file (format `{format}`) no és un fitxer de preferències (format `{format}`) +@msg not a preferences file: no `format` no és un fitxer de preferències: no hi ha `format` +@msg not a preferences file: no `version` no és un fitxer de preferències: no hi ha `version` +@msg not a preferences file: no `prefs` no és un fitxer de preferències: no hi ha `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) el fitxer s’ha desat amb una versió més nova del VectorCraft (versió {v}) +@msg the file holds no preferences el fitxer no conté cap preferència +@msg `{key}` names a folder, which preferences files leave out `{key}` indica una carpeta, i els fitxers de preferències no inclouen carpetes +@msg the file is larger than 1 MB el fitxer ocupa més d’1 MB +@msg give `path` or `data` indiqueu `path` o `data` +@msg `{key}` must be an object `{key}` ha de ser un objecte +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` s’executa sol, no com a pas d’un lot @msg unknown preset (one of {_1}) preajust desconegut (un de {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) preajust desconegut `{name}` (high, medium, low o un de desat: consulta flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) preajust desconegut `{name}` (consulta flattener.presets.list) @@ -6066,6 +6114,7 @@ file-filter Flattener presets Preajustos de l’aplanador file-filter PDF presets Preajustos de PDF file-filter PDF-compatible .ai .ai compatible amb PDF file-filter Print presets Preajustos d’impressió +file-filter Preferences Preferències file-filter Export presets Preajustos d’exportació file-filter SVG Compressed SVG comprimit file-filter Swatch libraries Biblioteques de mostres @@ -6714,3 +6763,31 @@ breakText Glyphs Glifs No Suggestions No hi ha suggeriments Edit Custom Dictionary Edita el diccionari personalitzat Entry: Entrada: +# Script Console + Script Console Consola d’scripts + Clear Script Console Esborra la consola d’scripts + Copy Script Console Copia la consola d’scripts + Copy All Copia-ho tot + Copy Selected Copia la selecció + Finished Acabat + Ended with an error Acabat amb un error + Out of fuel Límit d’instruccions esgotat + Ended at a host limit Acabat en un límit de l’amfitrió + Ended at a limit Acabat en un límit + Stopped Aturat + Ended by an internal fault Acabat per un error intern + time unavailable temps no disponible + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} més lentes: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} crida a l’amfitrió|{n} crides a l’amfitrió +@plural {n} earlier line dropped|{n} earlier lines dropped {n} línia anterior descartada|{n} línies anteriors descartades +@plural {n} line cut|{n} lines cut {n} línia tallada|{n} línies tallades +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` han de ser números de línies que la consola conserva, `first` abans de `last` + +# Deferred plug-in effects + Refresh Deferred Effects Actualitza els efectes ajornats + Deferred Effects Efectes ajornats +@msg no plug-in effect is deferred no hi ha cap efecte de complement ajornat +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. S’ha obert amb {n} efecte de complement ajornat. Efecte › Actualitza els efectes ajornats l’executa.|S’ha obert amb {n} efectes de complement ajornats. Efecte › Actualitza els efectes ajornats els executa. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index de1723b906..e42f9bd215 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -610,6 +610,7 @@ Show Guides Zobrazit vodítka Lock Guides Zamknout vodítka Lock Guides by Default Ve výchozím stavu zamknout vodítka + Artboard Guides with Cmd/Ctrl + Ruler Drag Vodítka pracovní plochy tažením z pravítka s Cmd/Ctrl Unlock Guides Odemknout vodítka Make Guides Vytvořit vodítka Release Guides Uvolnit vodítka @@ -782,6 +783,13 @@ Quest Outline Úkol Coin Shine Mince Boss Alert Boss + Status Effects Stavové efekty + Poison Tint Jed + Freeze Edge Zmrazení + Burn Aura Spálení + Stun Pulse Omráčení + Stealth Fade Plížení + Shield Buff Štít Outlines and Rules Obrysy a linky Hand-Drawn Ručně kreslené Gradient Finishes Přechodové povrchy @@ -2284,6 +2292,8 @@ digits Malayalam Malajálamské Green Zelená Shifts the tints of global and spot colors; other colors stay. Posune tóny globálních a přímých barev; ostatní barvy zůstanou. Tint Tón + Fill Tint Tón výplně + Stroke Tint Tón tahu Color Guide Options Možnosti průvodce barvami Less Méně Steps: Kroky: @@ -2653,6 +2663,7 @@ digits Malayalam Malajálamské File Dimensions Rozměry souboru Transforms Transformace Background Color: Barva pozadí: + Guide Label: Štítek vodítek: Show Center Mark Zobrazit středovou značku Show Cross Hairs Zobrazit nitkový kříž Show Video Safe Areas Zobrazit bezpečné oblasti videa @@ -3764,6 +3775,12 @@ theme Appearance Motiv Real-time Drawing and Editing Kreslení a úpravy v reálném čase Render Threads (-1 = Automatic) Vlákna vykreslování (-1 = automaticky) Reset Preferences Obnovit předvolby + Export Preferences… Exportovat předvolby… + Import Preferences… Importovat předvolby… + Save the applied preferences to a JSON file Uložit použité předvolby do souboru JSON + Apply the preferences in a file Export Preferences saved Použít předvolby ze souboru uloženého příkazem Exportovat předvolby + Export Preferences Exportovat předvolby + Import Preferences Importovat předvolby Search Preferences Hledat v předvolbách No settings found Nenalezena žádná nastavení Scale Corners Měnit velikost rohů @@ -4143,6 +4160,8 @@ font-technology Variable Variabilní Preferences Předvolby Previous Předchozí Restore every preference to its default (applied on OK) Obnovit všechny předvolby na výchozí hodnoty (použije se po OK) + Reset all preferences to their defaults? Obnovit všechny předvolby na výchozí hodnoty? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Výchozí hodnoty se použijí po klepnutí na OK v Předvolbách. Zrušit tam zachová vaše současné předvolby. Smaller ↔ Larger Menší ↔ Větší Smart Guides (View → Smart Guides) Chytrá vodítka (Zobrazení → Chytrá vodítka) Couldn't save recovery data: {e} Data pro obnovení nelze uložit: {e} @@ -4389,6 +4408,7 @@ imageTrace Outline Obrys Stop Script Zastavit skript Show External Script Warning Zobrazit upozornění u externích skriptů A Script Is Running Běží skript + Script Alert Upozornění skriptu A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. Do not show this warning again Toto upozornění již nezobrazovat Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. @@ -4402,6 +4422,9 @@ imageTrace Outline Obrys @msg the script is too large to run skript je příliš velký na spuštění @msg a drag or an undo group is open; finish it before running a script je otevřené tažení nebo skupina kroků zpět; před spuštěním skriptu ji dokončete @msg the script left a document that cannot be kept skript zanechal dokument, který nelze zachovat +@msg the script is no longer in the Scripts folder skript už není ve složce Scripts + Some scripts were not listed Některé skripty nebyly uvedeny + The Scripts folder cannot be read Složku Scripts nelze přečíst @msg the script's run is no longer available běh skriptu již není k dispozici @msg a failed command changed undo steps that could not be put back, so the script was stopped neúspěšný příkaz změnil kroky zpět, které nebylo možné obnovit, proto byl skript zastaven @msg a recovery copy could not be written, so the script was not run záložní kopii se nepodařilo zapsat, proto skript nebyl spuštěn @@ -4585,6 +4608,7 @@ imageTrace Outline Obrys @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis musí být "vertical", "horizontal" nebo úhel ve stupních, ne `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" pozadí {other}: transparent, white, black nebo barva jako "#ff8800" @msg bad color {v} chybná barva {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` je null, název barvy vrstvy nebo #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio musí být číslo od 0,1 do 10 @msg the Color Picker is not open Výběr barvy není otevřený @msg the Simplify slider is not open Posuvník Zjednodušit není otevřený @@ -4989,6 +5013,20 @@ imageTrace Outline Obrys @msg unknown overprints `{o}` (preserve, simulate or discard) neznámé přetisky `{o}` (preserve, simulate nebo discard) @msg unknown panel `{raw}` neznámý panel `{raw}` @msg unknown preference `{key}` neznámá předvolba `{key}` +@msg Preferences imported. Předvolby byly importovány. +@msg not a preferences file: {e} nejde o soubor předvoleb: {e} +@msg not a preferences file: no JSON object nejde o soubor předvoleb: chybí objekt JSON +@msg not a preferences file (format `{format}`) nejde o soubor předvoleb (formát `{format}`) +@msg not a preferences file: no `format` nejde o soubor předvoleb: chybí `format` +@msg not a preferences file: no `version` nejde o soubor předvoleb: chybí `version` +@msg not a preferences file: no `prefs` nejde o soubor předvoleb: chybí `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) soubor byl uložen novější verzí aplikace VectorCraft (verze {v}) +@msg the file holds no preferences soubor neobsahuje žádné předvolby +@msg `{key}` names a folder, which preferences files leave out `{key}` určuje složku a soubory předvoleb složky neobsahují +@msg the file is larger than 1 MB soubor je větší než 1 MB +@msg give `path` or `data` zadejte `path` nebo `data` +@msg `{key}` must be an object `{key}` musí být objekt +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` se spouští samostatně, ne jako krok dávky @msg unknown preset (one of {_1}) neznámé přednastavení (jedno z {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) neznámé přednastavení `{name}` (high, medium, low nebo uložené: viz flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) neznámé přednastavení `{name}` (viz flattener.presets.list) @@ -5560,6 +5598,7 @@ file-filter Swatch libraries Knihovny vzorníků file-filter Flattener presets Přednastavení sloučení průhlednosti file-filter PDF presets Přednastavení PDF file-filter Print presets Přednastavení tisku +file-filter Preferences Předvolby file-filter Export presets Přednastavení exportu file-filter SVG Compressed Komprimované SVG file-filter PDF-compatible .ai .ai kompatibilní s PDF @@ -5682,6 +5721,7 @@ mark-style Japanese Japonské Preview (1 inch on the page) Náhled (1 palec na stránce) Set as Default Nastavit jako výchozí out from a highlighted edge to place its dimension | ze zvýrazněné hrany ven a umístíte její kótu | + two points, then move and click to place an aligned, horizontal or vertical dimension | na dva body, pak posuňte ukazatel a klepnutím umístěte zarovnanou, vodorovnou nebo svislou kótu | cancels | Double-click the tool for options zruší | Dvojitým kliknutím na nástroj otevřete volby Angular Úhlová Away from the Line Dál od čáry @@ -5710,14 +5750,17 @@ mark-style Japanese Japonské @msg Invalid drawing scale Neplatné měřítko výkresu @msg Invalid real scale Neplatné skutečné měřítko @msg Measured anchor no longer exists Měřený kotevní bod už neexistuje +@msg Invalid measured point Neplatný měřený bod @msg Measured segment no longer exists Měřený segment už neexistuje @msg Non-finite dimension Kóta není konečné číslo +@msg Only linear dimensions are horizontal or vertical Vodorovné nebo svislé jsou jen lineární kóty @msg Scale Text Attributes: selected type has no scale to bake Měnit velikost atributů textu: vybraný text nemá žádnou skalaci, kterou lze použít @msg Scale must be drawing:real, for example 1:10 Měřítko musí mít tvar výkres:skutečnost, například 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Poměr měřítka musí být mezi 1:1000000 a 1000000:1 @msg Second measured segment no longer exists Druhý měřený segment už neexistuje @msg Unknown dimension mode Neznámý režim kóty @msg Unknown dimension option {k} Neznámá volba kóty {k} +@msg Unknown dimension orientation Neznámá orientace kóty @msg Unknown dimension style Neznámý styl kóty @msg Unknown unit Neznámá jednotka # Revolve cap description @@ -6084,6 +6127,12 @@ axis Y Axis osa Y Flag Vlajka Crosshair Zaměřovač Checkpoint Kontrolní bod + Inventory Icons Ikony inventáře + Sword Meč + Shield Štít + Potion Lektvar + Key Klíč + Gem Drahokam Open Symbol Library Otevřít knihovnu symbolů Save Symbol Library Uložit knihovnu symbolů Save Symbol Library… Uložit knihovnu symbolů… @@ -6733,3 +6782,31 @@ breakText Glyphs Glyfy No Suggestions Žádné návrhy Edit Custom Dictionary Upravit vlastní slovník Entry: Položka: +# Script Console + Script Console Konzole skriptů + Clear Script Console Vymazat konzoli skriptů + Copy Script Console Kopírovat konzoli skriptů + Copy All Kopírovat vše + Copy Selected Kopírovat vybrané + Finished Dokončeno + Ended with an error Ukončeno s chybou + Out of fuel Vyčerpán limit instrukcí + Ended at a host limit Ukončeno na limitu hostitele + Ended at a limit Ukončeno na limitu + Stopped Zastaveno + Ended by an internal fault Ukončeno vnitřní chybou + time unavailable čas není k dispozici + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} nejpomalejší: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} volání hostitele|{n} volání hostitele|{n} volání hostitele +@plural {n} earlier line dropped|{n} earlier lines dropped {n} starší řádek zahozen|{n} starší řádky zahozeny|{n} starších řádků zahozeno +@plural {n} line cut|{n} lines cut {n} řádek zkrácen|{n} řádky zkráceny|{n} řádků zkráceno +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` a `last` musí být čísla řádků, které konzole uchovává, `first` před `last` + +# Deferred plug-in effects + Refresh Deferred Effects Obnovit odložené efekty + Deferred Effects Odložené efekty +@msg no plug-in effect is deferred žádný efekt zásuvného modulu není odložen +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Otevřeno s {n} odloženým efektem zásuvného modulu. Efekt › Obnovit odložené efekty jej spustí.|Otevřeno s {n} odloženými efekty zásuvných modulů. Efekt › Obnovit odložené efekty je spustí.|Otevřeno s {n} odloženými efekty zásuvných modulů. Efekt › Obnovit odložené efekty je spustí. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 77687493e5..cf7aa67b3f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -55,6 +55,8 @@ Scripts Scripter Check Script… Kontrollér script… Check Script Kontrollér script + Some scripts were not listed Nogle scripter blev ikke vist + The Scripts folder cannot be read Mappen Scripts kan ikke læses Other Script… Andet script… Document Setup… Dokumentopsætning… Switch Units Skift enheder @@ -560,6 +562,7 @@ Show Guides Vis hjælpelinjer Lock Guides Lås hjælpelinjer Lock Guides by Default Lås hjælpelinjer som standard + Artboard Guides with Cmd/Ctrl + Ruler Drag Hjælpelinjer til kunstplade med Cmd/Ctrl + træk fra lineal Unlock Guides Lås hjælpelinjer op Make Guides Opret hjælpelinjer Release Guides Frigør hjælpelinjer @@ -719,6 +722,13 @@ Quest Outline Quest Coin Shine Mønt Boss Alert Boss + Status Effects Statuseffekter + Poison Tint Gift + Freeze Edge Frost + Burn Aura Brænd + Stun Pulse Bedøvelse + Stealth Fade Snige + Shield Buff Skjold Outlines and Rules Konturer og linjer Hand-Drawn Håndtegnet Gradient Finishes Gradientfinish @@ -2088,6 +2098,8 @@ digits Malayalam Malayalam Green Grøn Shifts the tints of global and spot colors; other colors stay. Flytter nuancerne af globale farver og spotfarver; andre farver forbliver uændrede. Tint Nuance + Fill Tint Fyldnuance + Stroke Tint Stregnuance Color Guide Options Indstillinger for farveguide Less Mindre Steps: Trin: @@ -2441,6 +2453,7 @@ digits Malayalam Malayalam File Dimensions Fildimensioner Transforms Transformationer Background Color: Baggrundsfarve: + Guide Label: Hjælpelinjeetiket: Show Center Mark Vis midtermærke Show Cross Hairs Vis trådkors Show Video Safe Areas Vis sikre videoområder @@ -3487,6 +3500,12 @@ theme Appearance Udseende Real-time Drawing and Editing Tegning og redigering i realtid Render Threads (-1 = Automatic) Renderingstråde (-1 = automatisk) Reset Preferences Nulstil indstillinger + Export Preferences… Eksportér præferencer… + Import Preferences… Importér præferencer… + Save the applied preferences to a JSON file Gem de anvendte præferencer i en JSON-fil + Apply the preferences in a file Export Preferences saved Anvend præferencerne i en fil, som Eksportér præferencer har gemt + Export Preferences Eksportér præferencer + Import Preferences Importér præferencer Search Preferences Søg i præferencer No settings found Ingen indstillinger fundet Scale Corners Skalér hjørner @@ -3857,6 +3876,8 @@ font-technology Variable Variable Preferences Præferencer Previous Forrige Restore every preference to its default (applied on OK) Gendan alle præferencer til standard (anvendes ved OK) + Reset all preferences to their defaults? Nulstil alle præferencer til standard? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Standardværdierne anvendes, når du klikker på OK i Præferencer. Annullér der beholder dine nuværende præferencer. Smaller ↔ Larger Mindre ↔ Større Smart Guides (View → Smart Guides) Smarte hjælpelinjer (Vis → Smarte hjælpelinjer) Couldn't save recovery data: {e} Kunne ikke gemme gendannelsesdata: {e} @@ -4085,6 +4106,7 @@ imageTrace Outline Kontur Stop Script Stop script Show External Script Warning Vis advarsel om eksterne scripts A Script Is Running Et script kører + Script Alert Scriptadvarsel A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. Do not show this warning again Vis ikke denne advarsel igen Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen. @@ -4602,6 +4624,20 @@ imageTrace Outline Kontur @msg unknown overprints `{o}` (preserve, simulate or discard) ukendt overprint `{o}` (bevar, simulér eller forkast) @msg unknown panel `{raw}` ukendt panel `{raw}` @msg unknown preference `{key}` ukendt præference `{key}` +@msg Preferences imported. Præferencerne er importeret. +@msg not a preferences file: {e} ikke en præferencefil: {e} +@msg not a preferences file: no JSON object ikke en præferencefil: intet JSON-objekt +@msg not a preferences file (format `{format}`) ikke en præferencefil (format `{format}`) +@msg not a preferences file: no `format` ikke en præferencefil: intet `format` +@msg not a preferences file: no `version` ikke en præferencefil: ingen `version` +@msg not a preferences file: no `prefs` ikke en præferencefil: ingen `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) filen er gemt af en nyere version af VectorCraft (version {v}) +@msg the file holds no preferences filen indeholder ingen præferencer +@msg `{key}` names a folder, which preferences files leave out `{key}` angiver en mappe, og præferencefiler indeholder ikke mapper +@msg the file is larger than 1 MB filen er større end 1 MB +@msg give `path` or `data` angiv `path` eller `data` +@msg `{key}` must be an object `{key}` skal være et objekt +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` køres alene, ikke som et trin i en batch @msg unknown preset (one of {_1}) ukendt forudindstilling (én af {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) ukendt forudindstilling `{name}` (høj, mellem, lav eller en gemt: se flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) ukendt forudindstilling `{name}` (se flattener.presets.list) @@ -5098,6 +5134,7 @@ file-filter Swatch libraries Farveprøvebiblioteker file-filter Flattener presets Flattener-forudindstillinger file-filter PDF presets PDF-forudindstillinger file-filter Print presets Printforudindstillinger +file-filter Preferences Præferencer file-filter Export presets Eksportforudindstillinger file-filter SVG Compressed Komprimeret SVG file-filter PDF-compatible .ai PDF-kompatibel .ai @@ -5272,6 +5309,7 @@ mark-style Japanese Japansk Preview (1 inch on the page) Forhåndsvisning (1 tomme på siden) Set as Default Angiv som standard out from a highlighted edge to place its dimension | ud fra en fremhævet kant for at placere dens mål | + two points, then move and click to place an aligned, horizontal or vertical dimension | på to punkter, flyt derefter, og klik for at placere et justeret, vandret eller lodret mål | cancels | Double-click the tool for options annullerer | Dobbeltklik på værktøjet for indstillinger Angular Vinklet Away from the Line Væk fra linjen @@ -5301,14 +5339,17 @@ mark-style Japanese Japansk @msg Invalid drawing scale Ugyldig tegningsmålestok @msg Invalid real scale Ugyldig virkelig målestok @msg Measured anchor no longer exists Det målte ankerpunkt findes ikke længere +@msg Invalid measured point Ugyldigt målt punkt @msg Measured segment no longer exists Det målte segment findes ikke længere @msg Non-finite dimension Ikke-endeligt mål +@msg Only linear dimensions are horizontal or vertical Kun lineære mål er vandrette eller lodrette @msg Scale Text Attributes: selected type has no scale to bake Skalér tekstattributter: den valgte tekst har ingen skalering at anvende @msg Scale must be drawing:real, for example 1:10 Målestokken skal være tegning:virkelig, for eksempel 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Målestoksforholdet skal være mellem 1:1000000 og 1000000:1 @msg Second measured segment no longer exists Det andet målte segment findes ikke længere @msg Unknown dimension mode Ukendt måltilstand @msg Unknown dimension option {k} Ukendt målindstilling {k} +@msg Unknown dimension orientation Ukendt målretning @msg Unknown dimension style Ukendt målstil @msg Unknown unit Ukendt enhed Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Luk de runde ender af åbne profiler. Delvise omdrejninger beholder deres skårne sider åbne. @@ -5873,6 +5914,12 @@ axis Y Axis Y-akse Flag Flag Crosshair Sigtekorn Checkpoint Kontrolpunkt + Inventory Icons Inventarikoner + Sword Sværd + Shield Skjold + Potion Eliksir + Key Nøgle + Gem Ædelsten Open Symbol Library Åbn symbolbibliotek Save Symbol Library Gem symbolbibliotek Save Symbol Library… Gem symbolbibliotek… @@ -6475,3 +6522,28 @@ breakText Glyphs Glyffer @msg side is left or right, not `{s}` side er left eller right, ikke `{s}` Edit Custom Dictionary Redigér egen ordliste Entry: Opslag: +# Script Console + Script Console Scriptkonsol + Clear Script Console Ryd scriptkonsollen + Copy Script Console Kopiér scriptkonsollen + Copy All Kopiér alt + Copy Selected Kopiér markeret + Finished Færdig + Ended with an error Afsluttet med en fejl + Out of fuel Instruktionsgrænsen er nået + Ended at a host limit Afsluttet ved en værtsgrænse + Ended at a limit Afsluttet ved en grænse + Stopped Stoppet + Ended by an internal fault Afsluttet af en intern fejl + time unavailable tid ikke tilgængelig + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} langsomste: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} værtskald|{n} værtskald +@plural {n} earlier line dropped|{n} earlier lines dropped {n} tidligere linje fjernet|{n} tidligere linjer fjernet +@plural {n} line cut|{n} lines cut {n} linje afkortet|{n} linjer afkortet + +# Deferred plug-in effects + Refresh Deferred Effects Opdatér udskudte effekter + Deferred Effects Udskudte effekter diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7e2619386b..b339033e66 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -264,6 +264,7 @@ font-technology Variable Variabel Average… Durchschnitt berechnen… Axis: Achse: Background Color: Hintergrundfarbe: + Guide Label: Farbmarkierung der Hilfslinien: Show Center Mark Mittelpunktmarke einblenden Show Cross Hairs Fadenkreuz einblenden Show Video Safe Areas Videosichere Bereiche einblenden @@ -1248,6 +1249,7 @@ file-filter Swatch libraries Farbfeldbibliotheken file-filter Flattener presets Reduzierungsvorgaben file-filter PDF presets PDF-Vorgaben file-filter Print presets Druckvorgaben +file-filter Preferences Voreinstellungen file-filter Export presets Exportvorgaben file-filter SVG Compressed SVG komprimiert file-filter PDF-compatible .ai PDF-kompatible .ai @@ -1893,6 +1895,7 @@ file-filter Templates Vorlagen Lock Grid Raster sperren Lock Guides Hilfslinien sperren Lock Guides by Default Hilfslinien standardmäßig sperren + Artboard Guides with Cmd/Ctrl + Ruler Drag Zeichenflächen-Hilfslinien mit Cmd/Ctrl + Ziehen aus dem Lineal Lock Others Andere sperren Lock Slices Slices sperren Lock Station Point Standpunkt sperren @@ -2776,6 +2779,12 @@ digits Malayalam Malayalam Reset OpenType Features OpenType-Funktionen zurücksetzen Reset Panel Bedienfeld zurücksetzen Reset Preferences Voreinstellungen zurücksetzen + Export Preferences… Voreinstellungen exportieren… + Import Preferences… Voreinstellungen importieren… + Save the applied preferences to a JSON file Die angewendeten Voreinstellungen in einer JSON-Datei speichern + Apply the preferences in a file Export Preferences saved Die Voreinstellungen aus einer mit „Voreinstellungen exportieren“ gespeicherten Datei anwenden + Export Preferences Voreinstellungen exportieren + Import Preferences Voreinstellungen importieren Search Preferences Voreinstellungen durchsuchen No settings found Keine Einstellungen gefunden Reset Profiles Profile zurücksetzen @@ -2799,6 +2808,8 @@ digits Malayalam Malayalam Responsive Responsiv Restore Wiederherstellen Restore every preference to its default (applied on OK) Alle Voreinstellungen auf ihre Standardwerte zurücksetzen (wird bei OK angewendet) + Reset all preferences to their defaults? Alle Voreinstellungen auf ihre Standardwerte zurücksetzen? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Die Standardwerte werden angewendet, wenn Sie in den Voreinstellungen auf OK klicken. Abbrechen dort behält Ihre aktuellen Voreinstellungen. Restore Recovered Documents Wiederhergestellte Dokumente öffnen Restored documents open unsaved: save them to keep them. Wiederhergestellte Dokumente werden ungespeichert geöffnet: Speichern Sie sie, um sie zu behalten. Restrict printing, editing and other tasks Drucken, Bearbeiten und andere Aufgaben einschränken @@ -3106,6 +3117,13 @@ digits Malayalam Malayalam Quest Outline Quest Coin Shine Münze Boss Alert Boss + Status Effects Statuseffekte + Poison Tint Gift + Freeze Edge Frost + Burn Aura Brand + Stun Pulse Betäubung + Stealth Fade Schleichen + Shield Buff Schild Shape Form Shape Builder Formerstellung Shape Builder Regions Formerstellungsbereiche @@ -3509,6 +3527,8 @@ effect Points Punkte Copies per Sheet (as many as fit, in a grid) Kopien pro Blatt (so viele wie passen, im Raster) Gutter: Zwischenraum: Tint Tonwert + Fill Tint Flächentonwert + Stroke Tint Konturtonwert Tip extends past the end point Spitze ragt über den Endpunkt hinaus Tip on the end point Spitze auf dem Endpunkt Title Case Wortanfänge groß @@ -3994,6 +4014,7 @@ theme Appearance Erscheinungsbild Stop Script Skript stoppen Show External Script Warning Warnung bei externen Skripten anzeigen A Script Is Running Ein Skript wird ausgeführt + Script Alert Skriptmeldung A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. Do not show this warning again Diese Warnung nicht mehr anzeigen Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. @@ -4007,6 +4028,9 @@ theme Appearance Erscheinungsbild @msg the script is too large to run das Skript ist zu groß zum Ausführen @msg a drag or an undo group is open; finish it before running a script ein Ziehvorgang oder eine Rückgängig-Gruppe ist offen; schließen Sie sie ab, bevor Sie ein Skript ausführen @msg the script left a document that cannot be kept das Skript hat ein Dokument hinterlassen, das nicht behalten werden kann +@msg the script is no longer in the Scripts folder das Skript befindet sich nicht mehr im Ordner „Scripts“ + Some scripts were not listed Einige Skripte wurden nicht aufgeführt + The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden @msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar @msg a failed command changed undo steps that could not be put back, so the script was stopped ein fehlgeschlagener Befehl hat Rückgängig-Schritte geändert, die nicht wiederhergestellt werden konnten, daher wurde das Skript angehalten @msg a recovery copy could not be written, so the script was not run eine Wiederherstellungskopie konnte nicht geschrieben werden, daher wurde das Skript nicht ausgeführt @@ -4191,6 +4215,7 @@ theme Appearance Erscheinungsbild @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis muss "vertical", "horizontal" oder ein Winkel in Grad sein, nicht `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black oder eine Farbe wie "#ff8800" @msg bad color {v} ungültige Farbe {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` ist null, der Name einer Ebenenfarbe oder #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio muss eine Zahl von 0,1 bis 10 sein @msg the Color Picker is not open der Farbwähler ist nicht geöffnet @msg the Simplify slider is not open der Regler „Vereinfachen“ ist nicht geöffnet @@ -4597,6 +4622,20 @@ theme Appearance Erscheinungsbild @msg unknown overprints `{o}` (preserve, simulate or discard) unbekannter Wert für overprints `{o}` (preserve, simulate oder discard) @msg unknown panel `{raw}` unbekanntes Bedienfeld `{raw}` @msg unknown preference `{key}` unbekannte Voreinstellung `{key}` +@msg Preferences imported. Voreinstellungen importiert. +@msg not a preferences file: {e} keine Voreinstellungsdatei: {e} +@msg not a preferences file: no JSON object keine Voreinstellungsdatei: kein JSON-Objekt +@msg not a preferences file (format `{format}`) keine Voreinstellungsdatei (Format `{format}`) +@msg not a preferences file: no `format` keine Voreinstellungsdatei: kein `format` +@msg not a preferences file: no `version` keine Voreinstellungsdatei: keine `version` +@msg not a preferences file: no `prefs` keine Voreinstellungsdatei: keine `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) die Datei wurde mit einer neueren Version von VectorCraft gespeichert (Version {v}) +@msg the file holds no preferences die Datei enthält keine Voreinstellungen +@msg `{key}` names a folder, which preferences files leave out `{key}` nennt einen Ordner, und Voreinstellungsdateien enthalten keine Ordner +@msg the file is larger than 1 MB die Datei ist größer als 1 MB +@msg give `path` or `data` geben Sie `path` oder `data` an +@msg `{key}` must be an object `{key}` muss ein Objekt sein +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` läuft für sich allein, nicht als Stapelschritt @msg unknown preset (one of {_1}) unbekannte Vorgabe (eine von {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) unbekannte Vorgabe `{name}` (high, medium, low oder eine gespeicherte: siehe flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) unbekannte Vorgabe `{name}` (siehe flattener.presets.list) @@ -5255,6 +5294,7 @@ effect Soft Weich Preview (1 inch on the page) Vorschau (1 Zoll auf der Seite) Set as Default Als Standard festlegen out from a highlighted edge to place its dimension | von einer hervorgehobenen Kante nach außen, um ihre Bemaßung zu platzieren | + two points, then move and click to place an aligned, horizontal or vertical dimension | auf zwei Punkte, dann bewegen und klicken, um eine ausgerichtete, horizontale oder vertikale Bemaßung zu platzieren | cancels | Double-click the tool for options bricht ab | Doppelklick auf das Werkzeug für Optionen Linear Linear Angular Winkel @@ -5287,14 +5327,17 @@ effect Soft Weich @msg Invalid drawing scale Ungültiger Zeichnungsmaßstab @msg Invalid real scale Ungültiger realer Maßstab @msg Measured anchor no longer exists Der gemessene Ankerpunkt existiert nicht mehr +@msg Invalid measured point Ungültiger gemessener Punkt @msg Measured segment no longer exists Das gemessene Segment existiert nicht mehr @msg Non-finite dimension Die Bemaßung ist keine endliche Zahl +@msg Only linear dimensions are horizontal or vertical Nur lineare Bemaßungen sind horizontal oder vertikal @msg Scale Text Attributes: selected type has no scale to bake Textattribute skalieren: Der ausgewählte Text weist keine zu übernehmende Skalierung auf @msg Scale must be drawing:real, for example 1:10 Der Maßstab muss Zeichnung:Realität sein, zum Beispiel 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Das Maßstabsverhältnis muss zwischen 1:1000000 und 1000000:1 liegen @msg Second measured segment no longer exists Das zweite gemessene Segment existiert nicht mehr @msg Unknown dimension mode Unbekannter Bemaßungsmodus @msg Unknown dimension option {k} Unbekannte Bemaßungsoption {k} +@msg Unknown dimension orientation Unbekannte Bemaßungsausrichtung @msg Unknown dimension style Unbekannter Bemaßungsstil @msg Unknown unit Unbekannte Einheit # Revolve cap description @@ -5667,6 +5710,12 @@ axis Y Axis Y-Achse Flag Flagge Crosshair Fadenkreuz Checkpoint Kontrollpunkt + Inventory Icons Inventar-Symbole + Sword Schwert + Shield Schild + Potion Trank + Key Schlüssel + Gem Edelstein Open Symbol Library Symbol-Bibliothek öffnen Save Symbol Library Symbol-Bibliothek speichern Save Symbol Library… Symbol-Bibliothek speichern… @@ -6320,3 +6369,31 @@ breakText Glyphs Glyphen No Suggestions Keine Vorschläge Edit Custom Dictionary Benutzerwörterbuch bearbeiten Entry: Eintrag: +# Script Console + Script Console Skriptkonsole + Clear Script Console Skriptkonsole leeren + Copy Script Console Skriptkonsole kopieren + Copy All Alles kopieren + Copy Selected Auswahl kopieren + Finished Beendet + Ended with an error Mit einem Fehler beendet + Out of fuel Anweisungslimit erreicht + Ended at a host limit An einem Host-Limit beendet + Ended at a limit An einem Limit beendet + Stopped Gestoppt + Ended by an internal fault Durch einen internen Fehler beendet + time unavailable Zeit nicht verfügbar + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} langsamste: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} Host-Aufruf|{n} Host-Aufrufe +@plural {n} earlier line dropped|{n} earlier lines dropped {n} ältere Zeile verworfen|{n} ältere Zeilen verworfen +@plural {n} line cut|{n} lines cut {n} Zeile gekürzt|{n} Zeilen gekürzt +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` und `last` müssen Nummern von Zeilen sein, die die Konsole enthält, `first` vor `last` + +# Deferred plug-in effects + Refresh Deferred Effects Zurückgestellte Effekte aktualisieren + Deferred Effects Zurückgestellte Effekte +@msg no plug-in effect is deferred kein Plug-in-Effekt ist zurückgestellt +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Mit {n} zurückgestelltem Plug-in-Effekt geöffnet. Effekt › Zurückgestellte Effekte aktualisieren führt ihn aus.|Mit {n} zurückgestellten Plug-in-Effekten geöffnet. Effekt › Zurückgestellte Effekte aktualisieren führt sie aus. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a95d84be33..114ed5a524 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -267,6 +267,7 @@ font-technology Variable Μεταβλητές Average… Μέσος όρος… Axis: Άξονας: Background Color: Χρώμα φόντου: + Guide Label: Ετικέτα οδηγών: Show Center Mark Εμφάνιση σημαδιού κέντρου Show Cross Hairs Εμφάνιση σταυρονήματος Show Video Safe Areas Εμφάνιση ασφαλών περιοχών βίντεο @@ -1725,6 +1726,7 @@ font-technology Variable Μεταβλητές Lock Κλείδωμα Lock Guides Κλείδωμα οδηγών Lock Guides by Default Κλείδωμα οδηγών από προεπιλογή + Artboard Guides with Cmd/Ctrl + Ruler Drag Οδηγοί πίνακα σχεδίασης με Cmd/Ctrl + σύρσιμο από χάρακα Lock Slices Κλείδωμα τομών Low Χαμηλή Luminosity Φωτεινότητα @@ -1919,6 +1921,12 @@ font-technology Variable Μεταβλητές Reselect Επαναφορά προηγούμενης επιλογής Reset Επαναφορά Reset Preferences Επαναφορά προτιμήσεων + Export Preferences… Εξαγωγή προτιμήσεων… + Import Preferences… Εισαγωγή προτιμήσεων… + Save the applied preferences to a JSON file Αποθήκευση των εφαρμοσμένων προτιμήσεων σε αρχείο JSON + Apply the preferences in a file Export Preferences saved Εφαρμογή των προτιμήσεων από αρχείο που αποθήκευσε η Εξαγωγή προτιμήσεων + Export Preferences Εξαγωγή προτιμήσεων + Import Preferences Εισαγωγή προτιμήσεων Search Preferences Αναζήτηση στις προτιμήσεις No settings found Δεν βρέθηκαν ρυθμίσεις Reset to Default Επαναφορά προεπιλογής @@ -2077,6 +2085,8 @@ font-technology Variable Μεταβλητές Threshold Κατώφλι Tile Παράθεση Tint Χρωματική απόχρωση + Fill Tint Χρωματική απόχρωση γεμίσματος + Stroke Tint Χρωματική απόχρωση περιγράμματος Tolerance Ανοχή Tolerance: Ανοχή: Tool Options… Επιλογές εργαλείου… @@ -2237,6 +2247,7 @@ axis Both Και τα δύο Stop Script Διακοπή σεναρίου Show External Script Warning Εμφάνιση προειδοποίησης για εξωτερικά σενάρια A Script Is Running Εκτελείται ένα σενάριο + Script Alert Ειδοποίηση σεναρίου A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. @@ -2250,6 +2261,9 @@ axis Both Και τα δύο @msg the script is too large to run το σενάριο είναι πολύ μεγάλο για εκτέλεση @msg a drag or an undo group is open; finish it before running a script είναι ανοιχτή μια μεταφορά ή ομάδα αναίρεσης· ολοκληρώστε την πριν εκτελέσετε σενάριο @msg the script left a document that cannot be kept το σενάριο άφησε ένα έγγραφο που δεν μπορεί να διατηρηθεί +@msg the script is no longer in the Scripts folder το σενάριο δεν βρίσκεται πλέον στον φάκελο Scripts + Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα + The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts @msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη @msg a failed command changed undo steps that could not be put back, so the script was stopped μια εντολή που απέτυχε άλλαξε βήματα αναίρεσης που δεν ήταν δυνατό να επαναφερθούν, οπότε το σενάριο σταμάτησε @msg a recovery copy could not be written, so the script was not run δεν ήταν δυνατή η εγγραφή αντιγράφου ανάκτησης, οπότε το σενάριο δεν εκτελέστηκε @@ -2616,6 +2630,7 @@ file-filter Flattener presets Προεπιλογές ισοπέδωσης file-filter PDF presets Προεπιλογές PDF file-filter PDF-compatible .ai .ai συμβατό με PDF file-filter Print presets Προεπιλογές εκτύπωσης +file-filter Preferences Προτιμήσεις file-filter Export presets Προκαθορισμένα εξαγωγής file-filter SVG Compressed Συμπιεσμένο SVG file-filter Swatch libraries Βιβλιοθήκες δειγμάτων χρωμάτων @@ -3421,6 +3436,8 @@ digits Malayalam Μαλαγιάλαμ Reshape Type Area Αναδιαμόρφωση περιοχής κειμένου Responsive Αποκρινόμενο Restore every preference to its default (applied on OK) Επαναφορά όλων των προτιμήσεων στις προεπιλογές τους (εφαρμογή με το Εντάξει) + Reset all preferences to their defaults? Επαναφορά όλων των προτιμήσεων στις προεπιλογές τους; + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Οι προεπιλογές εφαρμόζονται όταν κάνετε κλικ στο Εντάξει στις Προτιμήσεις. Το Ακύρωση εκεί διατηρεί τις τρέχουσες προτιμήσεις σας. Restore Recovered Documents Επαναφορά ανακτημένων εγγράφων Restored documents open unsaved: save them to keep them. Τα ανακτημένα έγγραφα ανοίγουν χωρίς να είναι αποθηκευμένα: αποθηκεύστε τα για να τα διατηρήσετε. Restrict printing, editing and other tasks Περιορισμός εκτύπωσης, επεξεργασίας και άλλων ενεργειών @@ -3608,6 +3625,13 @@ digits Malayalam Μαλαγιάλαμ Quest Outline Αποστολή Coin Shine Νόμισμα Boss Alert Αρχηγός + Status Effects Εφέ κατάστασης + Poison Tint Δηλητήριο + Freeze Edge Πάγωμα + Burn Aura Κάψιμο + Stun Pulse Ζάλη + Stealth Fade Αορασία + Shield Buff Ασπίδα Shape Builder Regions Περιοχές δημιουργίας σχημάτων Shape Effects Εφέ σχημάτων Shape Mode Λειτουργία σχήματος @@ -4235,6 +4259,7 @@ digits Malayalam Μαλαγιάλαμ @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` το axis πρέπει να είναι "vertical", "horizontal" ή γωνία σε μοίρες, όχι `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" φόντο {other}: transparent, white, black ή χρώμα όπως "#ff8800" @msg bad color {v} μη έγκυρο χρώμα {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb το `guideLabel` είναι null, όνομα χρώματος επιπέδου ή #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 Το videoRulerPixelAspectRatio πρέπει να είναι αριθμός από 0,1 έως 10 @msg bad colour `{hex}` (#rrggbb) μη έγκυρο χρώμα `{hex}` (#rrggbb) @msg bad page tree μη έγκυρο δέντρο σελίδων @@ -4629,6 +4654,20 @@ digits Malayalam Μαλαγιάλαμ @msg unknown overprints `{o}` (preserve, simulate or discard) άγνωστη επιλογή υπερεκτύπωσης `{o}` (preserve, simulate ή discard) @msg unknown panel `{raw}` άγνωστος πίνακας `{raw}` @msg unknown preference `{key}` άγνωστη προτίμηση `{key}` +@msg Preferences imported. Οι προτιμήσεις εισήχθησαν. +@msg not a preferences file: {e} δεν είναι αρχείο προτιμήσεων: {e} +@msg not a preferences file: no JSON object δεν είναι αρχείο προτιμήσεων: δεν υπάρχει αντικείμενο JSON +@msg not a preferences file (format `{format}`) δεν είναι αρχείο προτιμήσεων (μορφή `{format}`) +@msg not a preferences file: no `format` δεν είναι αρχείο προτιμήσεων: δεν υπάρχει `format` +@msg not a preferences file: no `version` δεν είναι αρχείο προτιμήσεων: δεν υπάρχει `version` +@msg not a preferences file: no `prefs` δεν είναι αρχείο προτιμήσεων: δεν υπάρχει `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) το αρχείο αποθηκεύτηκε από νεότερη έκδοση του VectorCraft (έκδοση {v}) +@msg the file holds no preferences το αρχείο δεν περιέχει προτιμήσεις +@msg `{key}` names a folder, which preferences files leave out το `{key}` ορίζει φάκελο, και τα αρχεία προτιμήσεων δεν περιέχουν φακέλους +@msg the file is larger than 1 MB το αρχείο είναι μεγαλύτερο από 1 MB +@msg give `path` or `data` δώστε `path` ή `data` +@msg `{key}` must be an object το `{key}` πρέπει να είναι αντικείμενο +@msg `prefs.import` runs on its own, not as a batch step το `prefs.import` εκτελείται μόνο του, όχι ως βήμα δέσμης @msg unknown preset (one of {_1}) άγνωστη προεπιλογή (μία από τις {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) άγνωστη προεπιλογή `{name}` (high, medium, low ή αποθηκευμένη: δείτε flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) άγνωστη προεπιλογή `{name}` (δείτε flattener.presets.list) @@ -5569,6 +5608,7 @@ effect Points Σημεία # Strings added upstream after this catalog was written (machine-drafted; review welcome). cancels | Double-click the tool for options για ακύρωση | Διπλό κλικ στο εργαλείο για επιλογές out from a highlighted edge to place its dimension | προς τα έξω από μια επισημασμένη ακμή για τοποθέτηση της διάστασής της | + two points, then move and click to place an aligned, horizontal or vertical dimension | σε δύο σημεία, μετά μετακινήστε και κάντε κλικ για τοποθέτηση ευθυγραμμισμένης, οριζόντιας ή κατακόρυφης διάστασης | A legacy .ai file holds one artboard: each artboard you check is saved as a separate file. Ένα αρχείο .ai παλαιού τύπου περιέχει έναν πίνακα σχεδίασης: κάθε πίνακας σχεδίασης που επιλέγετε αποθηκεύεται ως ξεχωριστό αρχείο. Arrange Intertwine Area Διάταξη περιοχής διαπλοκής Batch… Μαζική επεξεργασία… @@ -5665,14 +5705,17 @@ effect Points Σημεία @msg Invalid drawing scale Μη έγκυρη κλίμακα σχεδίου @msg Invalid real scale Μη έγκυρη πραγματική κλίμακα @msg Measured anchor no longer exists Το μετρημένο σημείο αγκύρωσης δεν υπάρχει πλέον +@msg Invalid measured point Μη έγκυρο μετρημένο σημείο @msg Measured segment no longer exists Το μετρημένο τμήμα δεν υπάρχει πλέον @msg Non-finite dimension Η διάσταση δεν είναι πεπερασμένος αριθμός +@msg Only linear dimensions are horizontal or vertical Μόνο οι γραμμικές διαστάσεις είναι οριζόντιες ή κατακόρυφες @msg Scale Text Attributes: selected type has no scale to bake Κλιμάκωση ιδιοτήτων κειμένου: το επιλεγμένο κείμενο δεν έχει κλίμακα προς εφαρμογή @msg Scale must be drawing:real, for example 1:10 Η κλίμακα πρέπει να είναι σχέδιο:πραγματικό, για παράδειγμα 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Ο λόγος κλίμακας πρέπει να είναι μεταξύ 1:1000000 και 1000000:1 @msg Second measured segment no longer exists Το δεύτερο μετρημένο τμήμα δεν υπάρχει πλέον @msg Unknown dimension mode Άγνωστη λειτουργία διάστασης @msg Unknown dimension option {k} Άγνωστη επιλογή διάστασης {k} +@msg Unknown dimension orientation Άγνωστος προσανατολισμός διάστασης @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe το `mode` πρέπει να είναι grayscale, rgb, hsb, cmyk ή websafe @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @@ -6035,6 +6078,12 @@ axis Y Axis Άξονας Y Flag Σημαία Crosshair Σταυρόνημα Checkpoint Σημείο ελέγχου + Inventory Icons Εικονίδια αποθέματος + Sword Ξίφος + Shield Ασπίδα + Potion Φίλτρο + Key Κλειδί + Gem Πετράδι Open Symbol Library Άνοιγμα βιβλιοθήκης συμβόλων Save Symbol Library Αποθήκευση βιβλιοθήκης συμβόλων Save Symbol Library… Αποθήκευση βιβλιοθήκης συμβόλων… @@ -6685,3 +6734,31 @@ breakText Glyphs Γλύφοι No Suggestions Καμία πρόταση Edit Custom Dictionary Επεξεργασία προσαρμοσμένου λεξικού Entry: Λήμμα: +# Script Console + Script Console Κονσόλα σεναρίων + Clear Script Console Εκκαθάριση κονσόλας σεναρίων + Copy Script Console Αντιγραφή κονσόλας σεναρίων + Copy All Αντιγραφή όλων + Copy Selected Αντιγραφή επιλεγμένων + Finished Ολοκληρώθηκε + Ended with an error Τερματίστηκε με σφάλμα + Out of fuel Εξαντλήθηκε το όριο εντολών + Ended at a host limit Τερματίστηκε σε όριο του κεντρικού συστήματος + Ended at a limit Τερματίστηκε σε όριο + Stopped Διακόπηκε + Ended by an internal fault Τερματίστηκε λόγω εσωτερικού σφάλματος + time unavailable ο χρόνος δεν είναι διαθέσιμος + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} πιο αργές: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} κλήση προς το κεντρικό σύστημα|{n} κλήσεις προς το κεντρικό σύστημα +@plural {n} earlier line dropped|{n} earlier lines dropped {n} παλαιότερη γραμμή απορρίφθηκε|{n} παλαιότερες γραμμές απορρίφθηκαν +@plural {n} line cut|{n} lines cut {n} γραμμή περικόπηκε|{n} γραμμές περικόπηκαν +@msg `first` and `last` must be numbers of lines the console holds, first before last Τα `first` και `last` πρέπει να είναι αριθμοί γραμμών που κρατά η κονσόλα, το `first` πριν από το `last` + +# Deferred plug-in effects + Refresh Deferred Effects Ανανέωση εφέ σε αναμονή + Deferred Effects Εφέ σε αναμονή +@msg no plug-in effect is deferred κανένα εφέ προσθέτου δεν είναι σε αναμονή +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Άνοιξε με {n} εφέ προσθέτου σε αναμονή. Το Εφέ › Ανανέωση εφέ σε αναμονή το εκτελεί.|Άνοιξε με {n} εφέ προσθέτων σε αναμονή. Το Εφέ › Ανανέωση εφέ σε αναμονή τα εκτελεί. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e0903d19d7..c0e50d82e9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -289,6 +289,7 @@ font-technology Variable Variables Average… Promediar… Axis: Eje: Background Color: Color de fondo: + Guide Label: Etiqueta de las guías: Show Center Mark Mostrar marca central Show Cross Hairs Mostrar líneas en cruz Show Video Safe Areas Mostrar áreas seguras de video @@ -1896,6 +1897,7 @@ font-technology Variable Variables Lock Grid Bloquear cuadrícula Lock Guides Bloquear guías Lock Guides by Default Bloquear guías de forma predeterminada + Artboard Guides with Cmd/Ctrl + Ruler Drag Guías de mesa de trabajo con Cmd/Ctrl + arrastre desde la regla Lock Others Bloquear otros Lock Slices Bloquear sectores Lock Station Point Bloquear punto de estación @@ -2819,6 +2821,12 @@ digits Malayalam Malayálam Reset OpenType Features Restablecer funciones OpenType Reset Panel Restablecer panel Reset Preferences Restablecer preferencias + Export Preferences… Exportar preferencias… + Import Preferences… Importar preferencias… + Save the applied preferences to a JSON file Guardar las preferencias aplicadas en un archivo JSON + Apply the preferences in a file Export Preferences saved Aplicar las preferencias de un archivo guardado con Exportar preferencias + Export Preferences Exportar preferencias + Import Preferences Importar preferencias Search Preferences Buscar en preferencias No settings found No se encontraron ajustes Reset Profiles Restablecer perfiles @@ -2841,6 +2849,8 @@ digits Malayalam Malayálam Responsive Adaptable Restore Restaurar Restore every preference to its default (applied on OK) Restaurar todas las preferencias a sus valores predeterminados (se aplica al Aceptar) + Reset all preferences to their defaults? ¿Restablecer todas las preferencias a sus valores predeterminados? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Los valores predeterminados se aplican al hacer clic en Aceptar en Preferencias. Cancelar ahí conserva sus preferencias actuales. Restore Recovered Documents Restaurar documentos recuperados Restored documents open unsaved: save them to keep them. Los documentos restaurados se abren sin guardar: guárdalos para conservarlos. Restrict printing, editing and other tasks Restringir la impresión, la edición y otras tareas @@ -3146,6 +3156,13 @@ digits Malayalam Malayálam Quest Outline Misión Coin Shine Moneda Boss Alert Jefe + Status Effects Efectos de estado + Poison Tint Veneno + Freeze Edge Congelación + Burn Aura Quemadura + Stun Pulse Aturdimiento + Stealth Fade Sigilo + Shield Buff Escudo Shape Forma Shape Builder Generador de formas Shape Builder Regions Regiones del generador de formas @@ -3565,6 +3582,8 @@ digits Malayalam Malayálam Copies per Sheet (as many as fit, in a grid) Copias por hoja (tantas como quepan, en cuadrícula) Gutter: Medianil: Tint Matiz + Fill Tint Matiz de relleno + Stroke Tint Matiz de trazo Tip extends past the end point La punta se extiende más allá del punto final Tip on the end point Punta en el punto final Title Case Tipo Título @@ -4079,6 +4098,7 @@ axis Both Ambos Stop Script Detener script Show External Script Warning Mostrar advertencia de scripts externos A Script Is Running Se está ejecutando un script + Script Alert Aviso del script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. Do not show this warning again No volver a mostrar esta advertencia Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. @@ -4092,6 +4112,9 @@ axis Both Ambos @msg the script is too large to run el script es demasiado grande para ejecutarlo @msg a drag or an undo group is open; finish it before running a script hay un arrastre o un grupo de deshacer abierto; termínelo antes de ejecutar un script @msg the script left a document that cannot be kept el script dejó un documento que no se puede conservar +@msg the script is no longer in the Scripts folder el script ya no está en la carpeta Scripts + Some scripts were not listed Algunos scripts no se han incluido en la lista + The Scripts folder cannot be read No se puede leer la carpeta Scripts @msg the script's run is no longer available la ejecución del script ya no está disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando fallido cambió pasos de deshacer que no se pudieron restaurar, así que el script se detuvo @msg a recovery copy could not be written, so the script was not run no se pudo escribir una copia de recuperación, así que el script no se ejecutó @@ -4276,6 +4299,7 @@ axis Both Ambos @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis debe ser "vertical", "horizontal" o un ángulo en grados, no `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" fondo {other}: transparent, white, black o un color como "#ff8800" @msg bad color {v} color no válido {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` es null, el nombre de un color de capa o #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio debe ser un número de 0,1 a 10 @msg the Color Picker is not open el Selector de color no está abierto @msg the Simplify slider is not open el regulador de Simplificar no está abierto @@ -4681,6 +4705,20 @@ axis Both Ambos @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpresiones desconocidas `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` panel desconocido `{raw}` @msg unknown preference `{key}` preferencia desconocida `{key}` +@msg Preferences imported. Preferencias importadas. +@msg not a preferences file: {e} no es un archivo de preferencias: {e} +@msg not a preferences file: no JSON object no es un archivo de preferencias: no hay ningún objeto JSON +@msg not a preferences file (format `{format}`) no es un archivo de preferencias (formato `{format}`) +@msg not a preferences file: no `format` no es un archivo de preferencias: falta `format` +@msg not a preferences file: no `version` no es un archivo de preferencias: falta `version` +@msg not a preferences file: no `prefs` no es un archivo de preferencias: falta `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) el archivo se guardó con una versión más reciente de VectorCraft (versión {v}) +@msg the file holds no preferences el archivo no contiene preferencias +@msg `{key}` names a folder, which preferences files leave out `{key}` indica una carpeta, y los archivos de preferencias no incluyen carpetas +@msg the file is larger than 1 MB el archivo ocupa más de 1 MB +@msg give `path` or `data` indique `path` o `data` +@msg `{key}` must be an object `{key}` debe ser un objeto +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` se ejecuta por sí solo, no como paso de un lote @msg unknown preset (one of {_1}) preajuste desconocido (uno de estos: {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) preajuste desconocido `{name}` (high, medium, low o uno guardado: consulta flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) preajuste desconocido `{name}` (consulta flattener.presets.list) @@ -5429,6 +5467,7 @@ file-filter Swatch libraries Bibliotecas de muestras file-filter Flattener presets Preajustes del acoplador file-filter PDF presets Preajustes de PDF file-filter Print presets Preajustes de impresión +file-filter Preferences Preferencias file-filter Export presets Ajustes de exportación file-filter SVG Compressed SVG comprimido file-filter PDF-compatible .ai .ai compatible con PDF @@ -5630,6 +5669,7 @@ mark-style Japanese Japonesas Preview (1 inch on the page) Vista previa (1 pulgada en la página) Set as Default Establecer como predeterminado out from a highlighted edge to place its dimension | hacia fuera desde un borde resaltado para colocar su cota | + two points, then move and click to place an aligned, horizontal or vertical dimension | en dos puntos, luego mueva y haga clic para colocar una cota alineada, horizontal o vertical | cancels | Double-click the tool for options cancela | Doble clic en la herramienta para ver las opciones Angular Angular Away from the Line Lejos de la línea @@ -5651,14 +5691,17 @@ mark-style Japanese Japonesas @msg Invalid drawing scale Escala de dibujo no válida @msg Invalid real scale Escala real no válida @msg Measured anchor no longer exists El punto de ancla medido ya no existe +@msg Invalid measured point Punto medido no válido @msg Measured segment no longer exists El segmento medido ya no existe @msg Non-finite dimension Cota no finita +@msg Only linear dimensions are horizontal or vertical Solo las cotas lineales son horizontales o verticales @msg Scale Text Attributes: selected type has no scale to bake Escalar atributos de texto: el texto seleccionado no tiene escala que aplicar @msg Scale must be drawing:real, for example 1:10 La escala debe ser dibujo:real, por ejemplo 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 La relación de escala debe estar entre 1:1000000 y 1000000:1 @msg Second measured segment no longer exists El segundo segmento medido ya no existe @msg Unknown dimension mode Modo de cota desconocido @msg Unknown dimension option {k} Opción de cota desconocida {k} +@msg Unknown dimension orientation Orientación de cota desconocida @msg Unknown dimension style Estilo de cota desconocido @msg Unknown unit Unidad desconocida # Revolve cap description @@ -6026,6 +6069,12 @@ axis Y Axis Eje Y Flag Bandera Crosshair Punto de mira Checkpoint Punto de control + Inventory Icons Iconos de inventario + Sword Espada + Shield Escudo + Potion Poción + Key Llave + Gem Gema Open Symbol Library Abrir biblioteca de símbolos Save Symbol Library Guardar biblioteca de símbolos Save Symbol Library… Guardar biblioteca de símbolos… @@ -6676,3 +6725,31 @@ breakText Glyphs Glifos No Suggestions No hay sugerencias Edit Custom Dictionary Editar diccionario personalizado Entry: Entrada: +# Script Console + Script Console Consola de scripts + Clear Script Console Borrar consola de scripts + Copy Script Console Copiar consola de scripts + Copy All Copiar todo + Copy Selected Copiar selección + Finished Terminado + Ended with an error Terminado con un error + Out of fuel Límite de instrucciones agotado + Ended at a host limit Terminado en un límite del host + Ended at a limit Terminado en un límite + Stopped Detenido + Ended by an internal fault Terminado por un error interno + time unavailable tiempo no disponible + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} más lentos: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} llamada al host|{n} llamadas al host +@plural {n} earlier line dropped|{n} earlier lines dropped {n} línea anterior descartada|{n} líneas anteriores descartadas +@plural {n} line cut|{n} lines cut {n} línea recortada|{n} líneas recortadas +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` y `last` deben ser números de líneas que la consola conserva, `first` antes que `last` + +# Deferred plug-in effects + Refresh Deferred Effects Actualizar efectos aplazados + Deferred Effects Efectos aplazados +@msg no plug-in effect is deferred no hay ningún efecto de plugin aplazado +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Se abrió con {n} efecto de plugin aplazado. Efecto › Actualizar efectos aplazados lo ejecuta.|Se abrió con {n} efectos de plugin aplazados. Efecto › Actualizar efectos aplazados los ejecuta. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b593200aa5..cdbd875764 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -601,6 +601,7 @@ Show Guides Näytä apuviivat Lock Guides Lukitse apuviivat Lock Guides by Default Lukitse apuviivat oletuksena + Artboard Guides with Cmd/Ctrl + Ruler Drag Piirtoalustan apuviivat Cmd/Ctrl + vetämällä viivaimesta Unlock Guides Avaa apuviivojen lukitus Make Guides Luo apuviivat Release Guides Vapauta apuviivat @@ -773,6 +774,13 @@ Quest Outline Tehtävä Coin Shine Kolikko Boss Alert Bossi + Status Effects Tilatehosteet + Poison Tint Myrkky + Freeze Edge Jäädytys + Burn Aura Poltto + Stun Pulse Tainnutus + Stealth Fade Hiipiminen + Shield Buff Kilpi Outlines and Rules Ääriviivat ja viivat Hand-Drawn Käsin piirretyt Gradient Finishes Liukuväriviimeistelyt @@ -2243,6 +2251,8 @@ digits Malayalam Malajalam Green Vihreä Shifts the tints of global and spot colors; other colors stay. Siirtää globaalien värien ja spottivärien sävyjä; muut värit säilyvät. Tint Sävy + Fill Tint Täytön sävy + Stroke Tint Viivan sävy Color Guide Options Väriopasteen asetukset Less Vähemmän Steps: Vaiheet: @@ -2597,6 +2607,7 @@ digits Malayalam Malajalam File Dimensions Tiedoston mitat Transforms Muunnokset Background Color: Taustaväri: + Guide Label: Apuviivojen tunniste: Show Center Mark Näytä keskimerkki Show Cross Hairs Näytä hiusristikko Show Video Safe Areas Näytä videon turva-alueet @@ -3688,6 +3699,12 @@ theme Appearance Ulkoasu Real-time Drawing and Editing Reaaliaikainen piirto ja muokkaus Render Threads (-1 = Automatic) Renderöintisäikeet (-1 = automaattinen) Reset Preferences Palauta asetukset + Export Preferences… Vie asetukset… + Import Preferences… Tuo asetukset… + Save the applied preferences to a JSON file Tallenna käytössä olevat asetukset JSON-tiedostoon + Apply the preferences in a file Export Preferences saved Ota käyttöön asetukset tiedostosta, jonka Vie asetukset tallensi + Export Preferences Vie asetukset + Import Preferences Tuo asetukset Search Preferences Hae asetuksista No settings found Asetuksia ei löytynyt Scale Corners Skaalaa kulmat @@ -4062,6 +4079,8 @@ font-technology Variable Muuttuvat Preferences Asetukset Previous Edellinen Restore every preference to its default (applied on OK) Palauta kaikki asetukset oletuksiin (käytetään, kun valitaan OK) + Reset all preferences to their defaults? Palautetaanko kaikki asetukset oletuksiin? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Oletukset otetaan käyttöön, kun valitset Asetuksissa OK. Peruuta siellä säilyttää nykyiset asetuksesi. Smaller ↔ Larger Pienempi ↔ Suurempi Smart Guides (View → Smart Guides) Älykkäät apuviivat (Näytä → Älykkäät apuviivat) Couldn't save recovery data: {e} Palautustietoja ei voitu tallentaa: {e} @@ -4303,6 +4322,7 @@ imageTrace Outline Ääriviiva Stop Script Pysäytä komentosarja Show External Script Warning Näytä ulkoisten komentosarjojen varoitus A Script Is Running Komentosarja on käynnissä + Script Alert Komentosarjan ilmoitus A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. Do not show this warning again Älä näytä tätä varoitusta uudelleen Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. @@ -4316,6 +4336,9 @@ imageTrace Outline Ääriviiva @msg the script is too large to run komentosarja on liian suuri suoritettavaksi @msg a drag or an undo group is open; finish it before running a script vetäminen tai kumousryhmä on kesken; viimeistele se ennen komentosarjan suorittamista @msg the script left a document that cannot be kept komentosarja jätti asiakirjan, jota ei voi säilyttää +@msg the script is no longer in the Scripts folder komentosarja ei ole enää Scripts-kansiossa + Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu + The Scripts folder cannot be read Scripts-kansiota ei voi lukea @msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä @msg a failed command changed undo steps that could not be put back, so the script was stopped epäonnistunut komento muutti kumoamisvaiheita, joita ei voitu palauttaa, joten komentosarja pysäytettiin @msg a recovery copy could not be written, so the script was not run palautuskopiota ei voitu kirjoittaa, joten komentosarjaa ei suoritettu @@ -4498,6 +4521,7 @@ imageTrace Outline Ääriviiva @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis-arvon on oltava "vertical", "horizontal" tai kulma asteina, ei `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" tausta {other}: transparent, white, black tai väri, kuten "#ff8800" @msg bad color {v} virheellinen väri {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` on null, tasovärin nimi tai #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio on oltava luku väliltä 0,1–10 @msg bad colour `{hex}` (#rrggbb) virheellinen väri `{hex}` (#rrggbb) @msg bad page tree virheellinen sivupuu @@ -4891,6 +4915,20 @@ imageTrace Outline Ääriviiva @msg unknown overprints `{o}` (preserve, simulate or discard) tuntematon päällepainatusten käsittely `{o}` (preserve, simulate tai discard) @msg unknown panel `{raw}` tuntematon paneeli `{raw}` @msg unknown preference `{key}` tuntematon asetus `{key}` +@msg Preferences imported. Asetukset tuotiin. +@msg not a preferences file: {e} ei ole asetustiedosto: {e} +@msg not a preferences file: no JSON object ei ole asetustiedosto: ei JSON-objektia +@msg not a preferences file (format `{format}`) ei ole asetustiedosto (muoto `{format}`) +@msg not a preferences file: no `format` ei ole asetustiedosto: `format` puuttuu +@msg not a preferences file: no `version` ei ole asetustiedosto: `version` puuttuu +@msg not a preferences file: no `prefs` ei ole asetustiedosto: `prefs` puuttuu +@msg the file was saved by a newer version of VectorCraft (version {v}) tiedosto on tallennettu VectorCraftin uudemmalla versiolla (versio {v}) +@msg the file holds no preferences tiedostossa ei ole asetuksia +@msg `{key}` names a folder, which preferences files leave out `{key}` nimeää kansion, eikä asetustiedostoissa ole kansioita +@msg the file is larger than 1 MB tiedosto on suurempi kuin 1 Mt +@msg give `path` or `data` anna `path` tai `data` +@msg `{key}` must be an object `{key}` on oltava objekti +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` ajetaan yksinään, ei erän vaiheena @msg unknown preset (one of {_1}) tuntematon esiasetus (jokin seuraavista: {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) tuntematon esiasetus `{name}` (high, medium, low tai tallennettu: ks. flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) tuntematon esiasetus `{name}` (ks. flattener.presets.list) @@ -5446,6 +5484,7 @@ file-filter Swatch libraries Värimallikirjastot file-filter Flattener presets Litistyksen esiasetukset file-filter PDF presets PDF-esiasetukset file-filter Print presets Tulostuksen esiasetukset +file-filter Preferences Asetukset file-filter Export presets Vientiesiasetukset file-filter SVG Compressed Pakattu SVG file-filter PDF-compatible .ai PDF-yhteensopiva .ai @@ -5581,6 +5620,7 @@ mark-style Japanese Japanilainen # Strings added upstream after this catalog was written (machine-drafted; review welcome). cancels | Double-click the tool for options peruuttaa | Kaksoisnapsauta työkalua avataksesi asetukset out from a highlighted edge to place its dimension | ulospäin korostetusta reunasta sijoittaaksesi sen mitan | + two points, then move and click to place an aligned, horizontal or vertical dimension | kahta pistettä, siirrä sitten ja napsauta sijoittaaksesi tasatun, vaaka- tai pystysuuntaisen mitan | A legacy .ai file holds one artboard: each artboard you check is saved as a separate file. Vanhassa .ai-tiedostossa on yksi piirtoalusta: jokainen valitsemasi piirtoalusta tallennetaan omaksi tiedostokseen. Arrange Intertwine Area Järjestä lomitusalue Batch… Erä… @@ -5677,14 +5717,17 @@ mark-style Japanese Japanilainen @msg Invalid drawing scale Virheellinen piirustuksen mittakaava @msg Invalid real scale Virheellinen todellinen mittakaava @msg Measured anchor no longer exists Mitattua ankkuripistettä ei ole enää +@msg Invalid measured point Virheellinen mitattu piste @msg Measured segment no longer exists Mitattua segmenttiä ei ole enää @msg Non-finite dimension Mitta ei ole äärellinen luku +@msg Only linear dimensions are horizontal or vertical Vain lineaariset mitat ovat vaaka- tai pystysuuntaisia @msg Scale Text Attributes: selected type has no scale to bake Skaalaa tekstin attribuutit: valitulla tekstillä ei ole sovellettavaa skaalausta @msg Scale must be drawing:real, for example 1:10 Mittakaavan on oltava muotoa piirustus:todellinen, esimerkiksi 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Mittakaavan suhteen on oltava välillä 1:1000000–1000000:1 @msg Second measured segment no longer exists Toista mitattua segmenttiä ei ole enää @msg Unknown dimension mode Tuntematon mitoitustila @msg Unknown dimension option {k} Tuntematon mitoitusasetus {k} +@msg Unknown dimension orientation Tuntematon mitan suunta @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`-arvon on oltava grayscale, rgb, hsb, cmyk tai websafe @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @@ -6114,6 +6157,12 @@ axis Y Axis Y-akseli Flag Lippu Crosshair Tähtäin Checkpoint Tarkastuskohta + Inventory Icons Inventaarioikonit + Sword Miekka + Shield Kilpi + Potion Taikajuoma + Key Avain + Gem Jalokivi Open Symbol Library Avaa symbolikirjasto Save Symbol Library Tallenna symbolikirjasto Save Symbol Library… Tallenna symbolikirjasto… @@ -6768,3 +6817,31 @@ breakText Glyphs Merkit No Suggestions Ei ehdotuksia Edit Custom Dictionary Muokkaa omaa sanastoa Entry: Merkintä: +# Script Console + Script Console Komentosarjakonsoli + Clear Script Console Tyhjennä komentosarjakonsoli + Copy Script Console Kopioi komentosarjakonsoli + Copy All Kopioi kaikki + Copy Selected Kopioi valitut + Finished Valmis + Ended with an error Päättyi virheeseen + Out of fuel Käskyraja täyttyi + Ended at a host limit Päättyi isännän rajaan + Ended at a limit Päättyi rajaan + Stopped Pysäytetty + Ended by an internal fault Päättyi sisäiseen virheeseen + time unavailable aika ei käytettävissä + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} hitaimmat: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} isäntäkutsu|{n} isäntäkutsua +@plural {n} earlier line dropped|{n} earlier lines dropped {n} aiempi rivi poistettu|{n} aiempaa riviä poistettu +@plural {n} line cut|{n} lines cut {n} rivi katkaistu|{n} riviä katkaistu +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` ja `last` on oltava konsolin säilyttämien rivien numeroita, `first` ennen arvoa `last` + +# Deferred plug-in effects + Refresh Deferred Effects Päivitä lykätyt tehosteet + Deferred Effects Lykätyt tehosteet +@msg no plug-in effect is deferred yhtään laajennustehostetta ei ole lykätty +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Avattiin, ja {n} laajennustehoste lykättiin. Tehoste › Päivitä lykätyt tehosteet suorittaa sen.|Avattiin, ja {n} laajennustehostetta lykättiin. Tehoste › Päivitä lykätyt tehosteet suorittaa ne. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6dd4e37a41..cb81c4902c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -290,6 +290,7 @@ font-technology Variable Variables Average… Alignement… Axis: Axe : Background Color: Couleur d’arrière-plan : + Guide Label: Étiquette des repères : Show Center Mark Afficher le repère central Show Cross Hairs Afficher le réticule Show Video Safe Areas Afficher les zones de sécurité vidéo @@ -1890,6 +1891,7 @@ font-technology Variable Variables Lock Grid Verrouiller la grille Lock Guides Verrouiller les repères Lock Guides by Default Verrouiller les repères par défaut + Artboard Guides with Cmd/Ctrl + Ruler Drag Repères de plan de travail avec Cmd/Ctrl + glissement depuis la règle Lock Others Verrouiller les autres Lock Slices Verrouiller les tranches Lock Station Point Verrouiller le point d’observation @@ -2811,6 +2813,12 @@ digits Malayalam Malayalam Reset OpenType Features Réinitialiser les fonctions OpenType Reset Panel Réinitialiser le panneau Reset Preferences Réinitialiser les préférences + Export Preferences… Exporter les préférences… + Import Preferences… Importer des préférences… + Save the applied preferences to a JSON file Enregistrer les préférences appliquées dans un fichier JSON + Apply the preferences in a file Export Preferences saved Appliquer les préférences d’un fichier enregistré par Exporter les préférences + Export Preferences Exporter les préférences + Import Preferences Importer des préférences Search Preferences Rechercher dans les préférences No settings found Aucun réglage trouvé Reset Profiles Réinitialiser les profils @@ -2833,6 +2841,8 @@ digits Malayalam Malayalam Responsive Adaptatif Restore Restaurer Restore every preference to its default (applied on OK) Rétablir toutes les préférences à leur valeur par défaut (appliqué avec OK) + Reset all preferences to their defaults? Rétablir toutes les préférences à leur valeur par défaut ? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Les valeurs par défaut sont appliquées lorsque vous cliquez sur OK dans Préférences. Annuler y conserve vos préférences actuelles. Restore Recovered Documents Restaurer les documents récupérés Restored documents open unsaved: save them to keep them. Les documents restaurés s’ouvrent sans être enregistrés : enregistrez-les pour les conserver. Restrict printing, editing and other tasks Restreindre l’impression, la modification et d’autres tâches @@ -3138,6 +3148,13 @@ digits Malayalam Malayalam Quest Outline Quête Coin Shine Pièce Boss Alert Boss + Status Effects Effets de statut + Poison Tint Poison + Freeze Edge Gel + Burn Aura Brûlure + Stun Pulse Étourdissement + Stealth Fade Furtivité + Shield Buff Bouclier Shape Forme Shape Builder Concepteur de forme Shape Builder Regions Zones du Concepteur de forme @@ -3556,6 +3573,8 @@ digits Malayalam Malayalam Copies per Sheet (as many as fit, in a grid) Copies par feuille (autant qu’il en tient, en grille) Tiles are numbered across, then down; leave the range empty for every tile. Les carreaux sont numérotés de gauche à droite, puis de haut en bas ; laissez la plage vide pour tous les carreaux. Tint Teinte + Fill Tint Teinte du fond + Stroke Tint Teinte du contour Tip extends past the end point La pointe dépasse le point d’extrémité Tip on the end point Pointe sur le point d’extrémité Title Case Majuscule à chaque mot @@ -4068,6 +4087,7 @@ axis Both Les deux Stop Script Arrêter le script Show External Script Warning Afficher l’avertissement des scripts externes A Script Is Running Un script est en cours d’exécution + Script Alert Alerte de script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. Do not show this warning again Ne plus afficher cet avertissement Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau. @@ -4081,6 +4101,9 @@ axis Both Les deux @msg the script is too large to run le script est trop volumineux pour être exécuté @msg a drag or an undo group is open; finish it before running a script un glissement ou un groupe d’annulation est ouvert ; terminez-le avant d’exécuter un script @msg the script left a document that cannot be kept le script a laissé un document qui ne peut pas être conservé +@msg the script is no longer in the Scripts folder le script ne se trouve plus dans le dossier Scripts + Some scripts were not listed Certains scripts ne sont pas répertoriés + The Scripts folder cannot be read Impossible de lire le dossier Scripts @msg the script's run is no longer available l’exécution du script n’est plus disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped une commande en échec a modifié des étapes d’annulation qui n’ont pas pu être rétablies, le script a donc été arrêté @msg a recovery copy could not be written, so the script was not run une copie de récupération n’a pas pu être écrite, le script n’a donc pas été exécuté @@ -4265,6 +4288,7 @@ axis Both Les deux @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis doit être "vertical", "horizontal" ou un angle en degrés, pas `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" arrière-plan {other} : transparent, white, black ou une couleur comme "#ff8800" @msg bad color {v} couleur non valide {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` est null, le nom d’une couleur de calque ou #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio doit être un nombre de 0,1 à 10 @msg the Color Picker is not open le Sélecteur de couleurs n’est pas ouvert @msg the Simplify slider is not open le curseur Simplifier n’est pas ouvert @@ -4670,6 +4694,20 @@ axis Both Les deux @msg unknown overprints `{o}` (preserve, simulate or discard) surimpressions inconnues `{o}` (preserve, simulate ou discard) @msg unknown panel `{raw}` panneau inconnu `{raw}` @msg unknown preference `{key}` préférence inconnue `{key}` +@msg Preferences imported. Préférences importées. +@msg not a preferences file: {e} ce n’est pas un fichier de préférences : {e} +@msg not a preferences file: no JSON object ce n’est pas un fichier de préférences : aucun objet JSON +@msg not a preferences file (format `{format}`) ce n’est pas un fichier de préférences (format `{format}`) +@msg not a preferences file: no `format` ce n’est pas un fichier de préférences : `format` manquant +@msg not a preferences file: no `version` ce n’est pas un fichier de préférences : `version` manquant +@msg not a preferences file: no `prefs` ce n’est pas un fichier de préférences : `prefs` manquant +@msg the file was saved by a newer version of VectorCraft (version {v}) le fichier a été enregistré par une version plus récente de VectorCraft (version {v}) +@msg the file holds no preferences le fichier ne contient aucune préférence +@msg `{key}` names a folder, which preferences files leave out `{key}` désigne un dossier, et les fichiers de préférences n’incluent pas les dossiers +@msg the file is larger than 1 MB le fichier dépasse 1 Mo +@msg give `path` or `data` indiquez `path` ou `data` +@msg `{key}` must be an object `{key}` doit être un objet +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` s’exécute seul, pas comme étape d’un lot @msg unknown preset (one of {_1}) paramètre prédéfini inconnu (valeurs possibles : {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) paramètre prédéfini inconnu `{name}` (high, medium, low ou un paramètre enregistré : voir flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) paramètre prédéfini inconnu `{name}` (voir flattener.presets.list) @@ -5623,6 +5661,7 @@ file-filter Flattener presets Paramètres prédéfinis d’aplatissement file-filter PDF presets Paramètres prédéfinis PDF file-filter PDF-compatible .ai .ai compatible PDF file-filter Print presets Paramètres prédéfinis d’impression +file-filter Preferences Préférences file-filter Export presets Paramètres prédéfinis d’export file-filter SVG Compressed SVG compressé file-filter Swatch libraries Bibliothèques de nuances @@ -5676,6 +5715,7 @@ theme Appearance Apparence Preview (1 inch on the page) Aperçu (1 pouce sur la page) Set as Default Définir par défaut out from a highlighted edge to place its dimension | vers l'extérieur depuis un bord mis en évidence pour placer sa cote | + two points, then move and click to place an aligned, horizontal or vertical dimension | sur deux points, puis déplacez et cliquez pour placer une cote alignée, horizontale ou verticale | cancels | Double-click the tool for options annule | Double-clic sur l'outil pour les options Angular Angulaire Away from the Line À l'écart de la ligne @@ -5705,14 +5745,17 @@ theme Appearance Apparence @msg Invalid drawing scale Échelle du dessin non valide @msg Invalid real scale Échelle réelle non valide @msg Measured anchor no longer exists Le point d’ancrage mesuré n’existe plus +@msg Invalid measured point Point mesuré non valide @msg Measured segment no longer exists Le segment mesuré n’existe plus @msg Non-finite dimension Cote non finie +@msg Only linear dimensions are horizontal or vertical Seules les cotes linéaires sont horizontales ou verticales @msg Scale Text Attributes: selected type has no scale to bake Mettre à l’échelle les attributs de texte : le texte sélectionné n’a pas d’échelle à intégrer @msg Scale must be drawing:real, for example 1:10 L’échelle doit être dessin:réel, par exemple 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Le rapport d’échelle doit être compris entre 1:1000000 et 1000000:1 @msg Second measured segment no longer exists Le second segment mesuré n’existe plus @msg Unknown dimension mode Mode de cote inconnu @msg Unknown dimension option {k} Option de cote inconnue {k} +@msg Unknown dimension orientation Orientation de cote inconnue @msg Unknown dimension style Style de cote inconnu @msg Unknown unit Unité inconnue # Revolve cap description @@ -6079,6 +6122,12 @@ axis Y Axis Axe Y Flag Drapeau Crosshair Réticule Checkpoint Point de contrôle + Inventory Icons Icônes d’inventaire + Sword Épée + Shield Bouclier + Potion Potion + Key Clé + Gem Gemme Open Symbol Library Ouvrir une bibliothèque de symboles Save Symbol Library Enregistrer la bibliothèque de symboles Save Symbol Library… Enregistrer la bibliothèque de symboles… @@ -6728,3 +6777,31 @@ breakText Glyphs Glyphes No Suggestions Aucune suggestion Edit Custom Dictionary Modifier le dictionnaire personnalisé Entry: Entrée : +# Script Console + Script Console Console de scripts + Clear Script Console Effacer la console de scripts + Copy Script Console Copier la console de scripts + Copy All Tout copier + Copy Selected Copier la sélection + Finished Terminé + Ended with an error Terminé avec une erreur + Out of fuel Limite d’instructions atteinte + Ended at a host limit Terminé à une limite de l’hôte + Ended at a limit Terminé à une limite + Stopped Arrêté + Ended by an internal fault Terminé par une erreur interne + time unavailable temps indisponible + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} plus lentes : {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} appel à l’hôte|{n} appels à l’hôte +@plural {n} earlier line dropped|{n} earlier lines dropped {n} ligne antérieure supprimée|{n} lignes antérieures supprimées +@plural {n} line cut|{n} lines cut {n} ligne coupée|{n} lignes coupées +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` et `last` doivent être des numéros de lignes que la console contient, `first` avant `last` + +# Deferred plug-in effects + Refresh Deferred Effects Actualiser les effets différés + Deferred Effects Effets différés +@msg no plug-in effect is deferred aucun effet de plug-in n’est différé +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Ouvert avec {n} effet de plug-in différé. Effet › Actualiser les effets différés l’exécute.|Ouvert avec {n} effets de plug-in différés. Effet › Actualiser les effets différés les exécute. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3397e7f347..296f18e805 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -27,6 +27,7 @@ on the canvas to create one बनाने के लिए कैनवास पर on the canvas to create one ( बनाने के लिए कैनवास पर ( out from a highlighted edge to place its dimension | माप रखने के लिए हाइलाइट किए किनारे से बाहर की ओर | + two points, then move and click to place an aligned, horizontal or vertical dimension | दो बिंदुओं पर, फिर संरेखित, क्षैतिज या ऊर्ध्वाधर आयाम रखने के लिए पॉइंटर ले जाएँ और क्लिक करें | over paths to roughen their outlines | आउटलाइन खुरदरी करने के लिए पाथ पर | over paths, and hold still to keep going | पाथ पर, और जारी रखने के लिए स्थिर रखें | right or left to zoom in or out | ज़ूम इन या आउट करने के लिए दाएँ या बाएँ | @@ -496,6 +497,7 @@ antiAlias Sharp शार्प B5 B5 Back वापस Background Color: बैकग्राउंड रंग: + Guide Label: गाइड लेबल: Background Contents बैकग्राउंड सामग्री Background Level बैकग्राउंड स्तर Background: बैकग्राउंड: @@ -524,6 +526,12 @@ antiAlias Sharp शार्प Flag झंडा Crosshair क्रॉसहेयर Checkpoint चेकपॉइंट + Inventory Icons इन्वेंटरी आइकन + Sword तलवार + Shield ढाल + Potion औषधि + Key कुंजी + Gem रत्न Batch बैच Batch Trace Folder फ़ोल्डर बैच ट्रेस करें Batch… बैच… @@ -2566,6 +2574,7 @@ antiAlias Sharp शार्प Lock Grid लॉक ग्रिड Lock Guides गाइड्स लॉक करें Lock Guides by Default गाइड्स डिफ़ॉल्ट रूप से लॉक करें + Artboard Guides with Cmd/Ctrl + Ruler Drag Cmd/Ctrl + रूलर से ड्रैग करके आर्टबोर्ड गाइड्स Lock Others लॉक अन्य Lock Selected लॉक सिलेक्टेड Lock Slices स्लाइस लॉक करें @@ -3778,6 +3787,12 @@ antiAlias Sharp शार्प Reset Painting पेंटिंग रीसेट करें Reset Panel पैनल रीसेट करें Reset Preferences प्रेफ़रेंसेज़ रीसेट करें + Export Preferences… प्रेफ़रेंसेज़ निर्यात करें… + Import Preferences… प्रेफ़रेंसेज़ आयात करें… + Save the applied preferences to a JSON file लागू प्रेफ़रेंसेज़ को JSON फ़ाइल में सहेजें + Apply the preferences in a file Export Preferences saved प्रेफ़रेंसेज़ निर्यात करें से सहेजी गई फ़ाइल की प्रेफ़रेंसेज़ लागू करें + Export Preferences प्रेफ़रेंसेज़ निर्यात करें + Import Preferences प्रेफ़रेंसेज़ आयात करें Search Preferences प्रेफ़रेंसेज़ में खोजें No settings found कोई सेटिंग नहीं मिली Reset Printing and Proofing मुद्रण और प्रूफिंग रीसेट करें @@ -3820,6 +3835,8 @@ antiAlias Sharp शार्प Responsive उत्तरदायी Restore पुनर्स्थापित करें Restore every preference to its default (applied on OK) प्रत्येक वरीयता को उसके डिफ़ॉल्ट में पुनर्स्थापित करें ( OK पर लागू) + Reset all preferences to their defaults? सभी प्रेफ़रेंसेज़ को उनके डिफ़ॉल्ट पर रीसेट करें? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. डिफ़ॉल्ट तब लागू होते हैं जब आप प्रेफ़रेंसेज़ में ठीक है पर क्लिक करते हैं। वहाँ रद्द करें आपकी मौजूदा प्रेफ़रेंसेज़ बनाए रखता है। Restore Recovered Documents पुनर्स्थापना डॉक्यूमेंट Restored documents open unsaved: save them to keep them. रिकवर किए डॉक्यूमेंट बिना सेव किए ओपन होते हैं। रखने के लिए उन्हें सेव करें। Restrict printing, editing and other tasks प्रिंटिंग, एडिटिंग और बाकी कामों पर पाबंदी लगाएँ @@ -4250,6 +4267,13 @@ antiAlias Sharp शार्प Quest Outline क्वेस्ट Coin Shine सिक्का Boss Alert बॉस + Status Effects स्थिति प्रभाव + Poison Tint ज़हर + Freeze Edge ठंड + Burn Aura जलन + Stun Pulse स्तब्ध + Stealth Fade छिपना + Shield Buff ढाल Shaft: दस्ता: Shape शेप Shape Builder शेप बिल्डर @@ -4842,6 +4866,8 @@ antiAlias Sharp शार्प Tilt झुकाव Time (hhmmss) समय (hhmms) Tint टिंट + Fill Tint फ़िल टिंट + Stroke Tint स्ट्रोक टिंट Tint Reduction टिंट में कमी Tints टिंट्स Tints and Shades टिंट्स और शेड्स @@ -6030,6 +6056,7 @@ antiAlias Sharp शार्प @msg bad base64 बुरा आधार64 @msg bad color {c} बुरा रंग {c} @msg bad color {v} बुरा रंग {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` null, किसी लेयर रंग का नाम या #rrggbb होता है @msg bad colour बुरा रंग @msg bad colour {v} बुरा रंग {v} @msg bad colour {v} in groupColors groupColors में अमान्य रंग {v} @@ -6166,6 +6193,7 @@ antiAlias Sharp शार्प Stop Script स्क्रिप्ट रोकें Show External Script Warning बाहरी स्क्रिप्ट की चेतावनी दिखाएँ A Script Is Running एक स्क्रिप्ट चल रही है + Script Alert स्क्रिप्ट सूचना A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। Do not show this warning again यह चेतावनी फिर न दिखाएँ Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। @@ -6179,6 +6207,9 @@ antiAlias Sharp शार्प @msg the script is too large to run स्क्रिप्ट चलाने के लिए बहुत बड़ी है @msg a drag or an undo group is open; finish it before running a script कोई ड्रैग या पूर्ववत समूह खुला है; स्क्रिप्ट चलाने से पहले उसे पूरा करें @msg the script left a document that cannot be kept स्क्रिप्ट ने ऐसा दस्तावेज़ छोड़ा है जिसे रखा नहीं जा सकता +@msg the script is no longer in the Scripts folder स्क्रिप्ट अब Scripts फ़ोल्डर में नहीं है + Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं + The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता @msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है @msg a failed command changed undo steps that could not be put back, so the script was stopped एक विफल कमांड ने पूर्ववत चरण बदल दिए जिन्हें वापस नहीं रखा जा सका, इसलिए स्क्रिप्ट रोक दी गई @msg a recovery copy could not be written, so the script was not run रिकवरी प्रति नहीं लिखी जा सकी, इसलिए स्क्रिप्ट नहीं चलाई गई @@ -6608,6 +6639,7 @@ antiAlias Sharp शार्प @msg matrix must be finite and invertible, depth finite matrix: मैट्रिक्स को परिमित और उलटा, गहराई परिमित होना चाहिए @msg matte: {e} मैट: {e} @msg Measured anchor no longer exists मापने वाला एंकर अब मौजूद नहीं है +@msg Invalid measured point मापा गया बिंदु अमान्य है @msg Measured segment no longer exists मापदंड अब मौजूद नहीं है @msg member is for order front, forward, backward or back member केवल order front, forward, backward या back के लिए है @msg memory budget (the selection is too large to hand over) स्मृति बजट (चुनाव बहुत बड़ा है) @@ -6963,6 +6995,7 @@ antiAlias Sharp शार्प @msg node {_1} is not type नोड {_1} टाइप नहीं है @msg node {_1} is on a locked artboard नोड {_1} एक लॉक्ड आर्टबोर्ड पर है @msg Non-finite dimension गैर-परिष्कृत आयाम +@msg Only linear dimensions are horizontal or vertical केवल रैखिक आयाम क्षैतिज या ऊर्ध्वाधर होते हैं @msg None of these issues are left: check again इन मुद्दों में से कोई भी छोड़ दिया जाता है: फिर से जांच करें @msg not a blend मिश्रण नहीं @msg not a closed path एक बंद पाथ नहीं @@ -7809,6 +7842,7 @@ antiAlias Sharp शार्प @msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode अज्ञात नियंत्रण `{name}`: fillStroke, रंग, drawMode या screenMode @msg Unknown dimension mode अज्ञात आयाम मोड @msg Unknown dimension option {k} अज्ञात आयाम ऑप्शन {k} +@msg Unknown dimension orientation अज्ञात आयाम अभिविन्यास @msg Unknown dimension style अज्ञात आयाम स्टाइल @msg unknown effect `{e}` अज्ञात इफ़ेक्ट `{e}` @msg unknown effect `{id}` अज्ञात इफ़ेक्ट `{id}` @@ -7866,6 +7900,20 @@ antiAlias Sharp शार्प @msg unknown plate `{n}` अज्ञात प्लेट `{n}` @msg unknown preference `{k}` अज्ञात वरीयता `{k}` @msg unknown preference `{key}` अज्ञात वरीयता `{key}` +@msg Preferences imported. प्रेफ़रेंसेज़ आयात की गईं। +@msg not a preferences file: {e} प्रेफ़रेंसेज़ फ़ाइल नहीं: {e} +@msg not a preferences file: no JSON object प्रेफ़रेंसेज़ फ़ाइल नहीं: कोई JSON ऑब्जेक्ट नहीं +@msg not a preferences file (format `{format}`) प्रेफ़रेंसेज़ फ़ाइल नहीं (फ़ॉर्मैट `{format}`) +@msg not a preferences file: no `format` प्रेफ़रेंसेज़ फ़ाइल नहीं: `format` नहीं है +@msg not a preferences file: no `version` प्रेफ़रेंसेज़ फ़ाइल नहीं: `version` नहीं है +@msg not a preferences file: no `prefs` प्रेफ़रेंसेज़ फ़ाइल नहीं: `prefs` नहीं है +@msg the file was saved by a newer version of VectorCraft (version {v}) फ़ाइल VectorCraft के नए संस्करण से सहेजी गई थी (संस्करण {v}) +@msg the file holds no preferences फ़ाइल में कोई प्रेफ़रेंस नहीं है +@msg `{key}` names a folder, which preferences files leave out `{key}` एक फ़ोल्डर बताता है, और प्रेफ़रेंसेज़ फ़ाइलों में फ़ोल्डर नहीं होते +@msg the file is larger than 1 MB फ़ाइल 1 MB से बड़ी है +@msg give `path` or `data` `path` या `data` दें +@msg `{key}` must be an object `{key}` एक ऑब्जेक्ट होना चाहिए +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` अकेले चलता है, बैच के चरण के रूप में नहीं @msg unknown preset (one of {_1}) अज्ञात प्रीसेट ({_1} में से एक) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) अज्ञात प्रीसेट `{name}` (उच्च, मध्यम, निम्न या एक बचाया: flattener.presets.list देखें) @msg unknown preset `{name}` (see flattener.presets.list) अज्ञात प्रीसेट `{name}` (देखें flattener.presets.list) @@ -8065,6 +8113,7 @@ file-filter Flattener presets फ़्लैटनर प्रीसेट् file-filter PDF presets PDF प्रीसेट्स file-filter PDF-compatible .ai PDF-संगत .ai file-filter Print presets प्रिंट प्रीसेट्स +file-filter Preferences प्रेफ़रेंसेज़ file-filter SVG Compressed SVG संपीड़ित file-filter Swatch libraries स्वॉच लाइब्रेरीज़ file-filter Templates टेम्पलेट्स @@ -8174,3 +8223,31 @@ theme Appearance अपीयरेंस No Suggestions कोई सुझाव नहीं Edit Custom Dictionary कस्टम शब्दकोश संपादित करें Entry: प्रविष्टि: +# Script Console + Script Console स्क्रिप्ट कंसोल + Clear Script Console स्क्रिप्ट कंसोल साफ़ करें + Copy Script Console स्क्रिप्ट कंसोल कॉपी करें + Copy All सब कॉपी करें + Copy Selected चयनित कॉपी करें + Finished पूरा हुआ + Ended with an error त्रुटि के साथ समाप्त + Out of fuel निर्देश सीमा समाप्त + Ended at a host limit होस्ट सीमा पर समाप्त + Ended at a limit सीमा पर समाप्त + Stopped रोका गया + Ended by an internal fault आंतरिक त्रुटि से समाप्त + time unavailable समय उपलब्ध नहीं + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} सबसे धीमे: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} होस्ट कॉल|{n} होस्ट कॉल +@plural {n} earlier line dropped|{n} earlier lines dropped {n} पुरानी पंक्ति हटाई गई|{n} पुरानी पंक्तियाँ हटाई गईं +@plural {n} line cut|{n} lines cut {n} पंक्ति काटी गई|{n} पंक्तियाँ काटी गईं +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` और `last` कंसोल में रखी पंक्तियों की संख्याएँ होनी चाहिए, `first` पहले और `last` बाद में + +# Deferred plug-in effects + Refresh Deferred Effects स्थगित इफ़ेक्ट्स रिफ्रेश करें + Deferred Effects स्थगित इफ़ेक्ट्स +@msg no plug-in effect is deferred कोई प्लग-इन इफ़ेक्ट स्थगित नहीं है +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. {n} प्लग-इन इफ़ेक्ट स्थगित रखकर खोला गया। इफ़ेक्ट › स्थगित इफ़ेक्ट्स रिफ्रेश करें इसे चलाता है।|{n} प्लग-इन इफ़ेक्ट्स स्थगित रखकर खोला गया। इफ़ेक्ट › स्थगित इफ़ेक्ट्स रिफ्रेश करें इन्हें चलाता है। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4b813215e0..34b6be0ab7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -385,6 +385,7 @@ font-technology Variable Változó B4 B4 B5 B5 Background Color: Háttérszín: + Guide Label: Segédvonalak címkéje: Show Center Mark Középjel megjelenítése Show Cross Hairs Szálkereszt megjelenítése Show Video Safe Areas Biztonságos videoterületek megjelenítése @@ -1572,6 +1573,7 @@ file-filter Swatch libraries Színminta-könyvtárak file-filter Flattener presets Lapítási előbeállítások file-filter PDF presets PDF-előbeállítások file-filter Print presets Nyomtatási előbeállítások +file-filter Preferences Beállítások file-filter Export presets Exportálási előbeállítások file-filter SVG Compressed Tömörített SVG file-filter PDF-compatible .ai PDF-kompatibilis .ai @@ -2377,6 +2379,7 @@ file-filter Templates Sablonok Lock Grid Rács zárolása Lock Guides Segédvonalak zárolása Lock Guides by Default Segédvonalak zárolása alapértelmezetten + Artboard Guides with Cmd/Ctrl + Ruler Drag Rajztábla-segédvonalak Cmd/Ctrl + húzással a vonalzóból Lock Others Többi zárolása Lock Slices Szeletek zárolása Lock Station Point Nézőpont zárolása @@ -3361,6 +3364,12 @@ mark-style Japanese Japán Reset Painting Painting visszaállítása Reset Panel Panel visszaállítása Reset Preferences Beállítások visszaállítása + Export Preferences… Beállítások exportálása… + Import Preferences… Beállítások importálása… + Save the applied preferences to a JSON file Az alkalmazott beállítások mentése JSON-fájlba + Apply the preferences in a file Export Preferences saved A Beállítások exportálása paranccsal mentett fájl beállításainak alkalmazása + Export Preferences Beállítások exportálása + Import Preferences Beállítások importálása Search Preferences Keresés a beállításokban No settings found Nincs ilyen beállítás Reset Printing and Proofing Printing and Proofing visszaállítása @@ -3397,6 +3406,8 @@ mark-style Japanese Japán Responsive Reszponzív Restore Visszaállít Restore every preference to its default (applied on OK) Minden beállítás visszaállítása az alapértékre (az OK gombbal lép életbe) + Reset all preferences to their defaults? Visszaállítja az összes beállítást az alapértékre? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Az alapértékek akkor lépnek életbe, amikor a Beállításokban az OK gombra kattint. Az ottani Mégse megtartja a jelenlegi beállításokat. Restore Recovered Documents Helyreállított dokumentumok visszaállítása Restored documents open unsaved: save them to keep them. A visszaállított dokumentumok mentetlenül nyílnak meg: mentsd őket, ha meg akarod tartani. Restrict printing, editing and other tasks Nyomtatás, szerkesztés és más műveletek korlátozása @@ -3760,6 +3771,13 @@ mark-style Japanese Japán Quest Outline Küldetés Coin Shine Érme Boss Alert Főellenség + Status Effects Állapot hatások + Poison Tint Méreg + Freeze Edge Fagy + Burn Aura Égés + Stun Pulse Kábítás + Stealth Fade Lopakodás + Shield Buff Pajzs Shape Alakzat Shape Builder Alakzatépítő Shape Builder Regions Alakzatépítő területei @@ -4238,6 +4256,8 @@ mark-style Japanese Japán Tilt Dőlés Copies per Sheet (as many as fit, in a grid) Példány laponként (ahány elfér, rácsban) Tint Tónus + Fill Tint Kitöltés tónusa + Stroke Tint Körvonal tónusa Tints Tónusok Tints and Shades Tónusok és árnyalatok Tips Tippek @@ -4823,6 +4843,7 @@ imageTrace Outline Körvonal @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` az axis értéke "vertical", "horizontal" vagy fokban megadott szög lehet, ez nem az: `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black vagy egy szín, például "#ff8800" @msg bad color {v} hibás szín: {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb a `guideLabel` értéke null, egy rétegszín neve vagy #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio: 0,1 és 10 közötti szám kell @msg the Color Picker is not open a Színválasztó nincs megnyitva @msg the Simplify slider is not open az Egyszerűsítés csúszka nincs megnyitva @@ -4874,6 +4895,7 @@ imageTrace Outline Körvonal Stop Script Parancsfájl leállítása Show External Script Warning Figyelmeztetés külső parancsfájlok előtt A Script Is Running Egy parancsfájl fut + Script Alert Parancsfájl-értesítés A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra. @@ -4887,6 +4909,9 @@ imageTrace Outline Körvonal @msg the script is too large to run a parancsfájl túl nagy a futtatáshoz @msg a drag or an undo group is open; finish it before running a script húzás vagy visszavonási csoport van folyamatban; fejezze be a parancsfájl futtatása előtt @msg the script left a document that cannot be kept a parancsfájl olyan dokumentumot hagyott hátra, amely nem tartható meg +@msg the script is no longer in the Scripts folder a parancsfájl már nincs a Scripts mappában + Some scripts were not listed Néhány szkript nem szerepel a listában + The Scripts folder cannot be read A Scripts mappa nem olvasható @msg the script's run is no longer available a parancsfájl futása már nem érhető el @msg a failed command changed undo steps that could not be put back, so the script was stopped egy sikertelen parancs olyan visszavonási lépéseket módosított, amelyeket nem lehetett visszaállítani, ezért a parancsfájl leállt @msg a recovery copy could not be written, so the script was not run a helyreállítási másolatot nem sikerült kiírni, ezért a parancsfájl nem futott le @@ -5491,6 +5516,20 @@ imageTrace Outline Körvonal @msg unknown overprints `{o}` (preserve, simulate or discard) ismeretlen felülnyomás-kezelés: `{o}` (preserve, simulate vagy discard) @msg unknown panel `{raw}` ismeretlen panel: `{raw}` @msg unknown preference `{key}` ismeretlen beállítás: `{key}` +@msg Preferences imported. A beállítások importálva. +@msg not a preferences file: {e} nem beállításfájl: {e} +@msg not a preferences file: no JSON object nem beállításfájl: nincs JSON-objektum +@msg not a preferences file (format `{format}`) nem beállításfájl (formátum: `{format}`) +@msg not a preferences file: no `format` nem beállításfájl: nincs `format` +@msg not a preferences file: no `version` nem beállításfájl: nincs `version` +@msg not a preferences file: no `prefs` nem beállításfájl: nincs `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) a fájlt a VectorCraft újabb verziója mentette (verzió: {v}) +@msg the file holds no preferences a fájl nem tartalmaz beállításokat +@msg `{key}` names a folder, which preferences files leave out a(z) `{key}` mappát ad meg, a beállításfájlok pedig nem tartalmaznak mappákat +@msg the file is larger than 1 MB a fájl nagyobb 1 MB-nál +@msg give `path` or `data` adja meg a `path` vagy a `data` értékét +@msg `{key}` must be an object a(z) `{key}` értékének objektumnak kell lennie +@msg `prefs.import` runs on its own, not as a batch step a `prefs.import` önállóan fut, nem kötegelt lépésként @msg unknown preset (one of {_1}) ismeretlen előbeállítás (ezek egyike lehet: {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) ismeretlen előbeállítás: `{name}` (high, medium, low vagy egy mentett; lásd: flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) ismeretlen előbeállítás: `{name}` (lásd: flattener.presets.list) @@ -5663,6 +5702,7 @@ imageTrace Outline Körvonal Preview (1 inch on the page) Előnézet (1 hüvelyk az oldalon) Set as Default Beállítás alapértelmezettként out from a highlighted edge to place its dimension | egy kiemelt élről kifelé a méret elhelyezéséhez | + two points, then move and click to place an aligned, horizontal or vertical dimension | két pontra, majd mozgasd a mutatót, és kattints az igazított, vízszintes vagy függőleges méret elhelyezéséhez | cancels | Double-click the tool for options megszakítja | Dupla kattintás az eszközre a beállításokhoz Angular Szög Away from the Line A vonaltól távol @@ -5692,14 +5732,17 @@ imageTrace Outline Körvonal @msg Invalid drawing scale Érvénytelen rajzlépték @msg Invalid real scale Érvénytelen valós lépték @msg Measured anchor no longer exists A mért horgonypont már nem létezik +@msg Invalid measured point Érvénytelen mért pont @msg Measured segment no longer exists A mért szakasz már nem létezik @msg Non-finite dimension Nem véges méret +@msg Only linear dimensions are horizontal or vertical Csak a lineáris méretek lehetnek vízszintesek vagy függőlegesek @msg Scale Text Attributes: selected type has no scale to bake Szövegattribútumok méretezése: a kijelölt szövegnek nincs alkalmazható méretezése @msg Scale must be drawing:real, for example 1:10 A léptéknek rajz:valós alakúnak kell lennie, például 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 A lépték aránya 1:1000000 és 1000000:1 között lehet @msg Second measured segment no longer exists A második mért szakasz már nem létezik @msg Unknown dimension mode Ismeretlen méretezési mód @msg Unknown dimension option {k} Ismeretlen méretezési beállítás: {k} +@msg Unknown dimension orientation Ismeretlen méretezési tájolás @msg Unknown dimension style Ismeretlen méretezési stílus @msg Unknown unit Ismeretlen mértékegység # Revolve cap description @@ -6067,6 +6110,12 @@ axis Y Axis Y tengely Flag Zászló Crosshair Célkereszt Checkpoint Ellenőrzőpont + Inventory Icons Leltári ikonok + Sword Kard + Shield Pajzs + Potion Bájital + Key Kulcs + Gem Drágakő Open Symbol Library Szimbólumkönyvtár megnyitása Save Symbol Library Szimbólumkönyvtár mentése Save Symbol Library… Szimbólumkönyvtár mentése… @@ -6717,3 +6766,31 @@ breakText Glyphs Glifák No Suggestions Nincs javaslat Edit Custom Dictionary Egyéni szótár szerkesztése Entry: Bejegyzés: +# Script Console + Script Console Parancsfájlkonzol + Clear Script Console Parancsfájlkonzol törlése + Copy Script Console Parancsfájlkonzol másolása + Copy All Összes másolása + Copy Selected Kijelölés másolása + Finished Befejeződött + Ended with an error Hibával ért véget + Out of fuel Elfogyott az utasításkeret + Ended at a host limit Gazdakorlátnál ért véget + Ended at a limit Korlátnál ért véget + Stopped Leállítva + Ended by an internal fault Belső hiba miatt ért véget + time unavailable az idő nem érhető el + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} leglassabbak: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} gazdahívás +@plural {n} earlier line dropped|{n} earlier lines dropped {n} korábbi sor elvetve +@plural {n} line cut|{n} lines cut {n} sor levágva +@msg `first` and `last` must be numbers of lines the console holds, first before last A `first` és a `last` a konzolban tárolt sorok számai legyenek, a `first` a `last` előtt + +# Deferred plug-in effects + Refresh Deferred Effects Elhalasztott effektusok frissítése + Deferred Effects Elhalasztott effektusok +@msg no plug-in effect is deferred nincs elhalasztott bővítményeffektus +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Megnyitva, elhalasztott bővítményeffektusok: {n}. Az Effektus › Elhalasztott effektusok frissítése futtatja őket. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 33d229c85a..16854b5bb7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -55,6 +55,8 @@ Scripts Skrip Check Script… Periksa skrip… Check Script Periksa skrip + Some scripts were not listed Beberapa skrip tidak dicantumkan + The Scripts folder cannot be read Folder Scripts tidak dapat dibaca Other Script… Skrip lain… Document Setup… Pengaturan dokumen… Switch Units Ganti satuan @@ -560,6 +562,7 @@ Show Guides Tampilkan panduan Lock Guides Kunci panduan Lock Guides by Default Kunci panduan secara default + Artboard Guides with Cmd/Ctrl + Ruler Drag Panduan artboard dengan Cmd/Ctrl + seret dari penggaris Unlock Guides Buka kunci panduan Make Guides Buat panduan Release Guides Lepaskan panduan @@ -719,6 +722,13 @@ Quest Outline Quest Coin Shine Koin Boss Alert Boss + Status Effects Efek Status + Poison Tint Racun + Freeze Edge Beku + Burn Aura Bakar + Stun Pulse Pingsan + Stealth Fade Menghilang + Shield Buff Perisai Outlines and Rules Garis luar dan garis Hand-Drawn Gambar tangan Gradient Finishes Finishing gradien @@ -2088,6 +2098,8 @@ digits Malayalam Malayalam Green Hijau Shifts the tints of global and spot colors; other colors stay. Menggeser tint warna global dan warna spot; warna lainnya tetap. Tint Tint + Fill Tint Tint isian + Stroke Tint Tint stroke Color Guide Options Opsi panduan warna Less Lebih sedikit Steps: Langkah: @@ -2441,6 +2453,7 @@ digits Malayalam Malayalam File Dimensions Dimensi file Transforms Transformasi Background Color: Warna latar belakang: + Guide Label: Label panduan: Show Center Mark Tampilkan tanda tengah Show Cross Hairs Tampilkan garis silang Show Video Safe Areas Tampilkan area aman video @@ -3487,6 +3500,12 @@ theme Appearance Tampilan Real-time Drawing and Editing Penggambaran dan pengeditan waktu nyata Render Threads (-1 = Automatic) Utas render (-1 = Otomatis) Reset Preferences Atur ulang preferensi + Export Preferences… Ekspor preferensi… + Import Preferences… Impor preferensi… + Save the applied preferences to a JSON file Simpan preferensi yang diterapkan ke file JSON + Apply the preferences in a file Export Preferences saved Terapkan preferensi dari file yang disimpan oleh Ekspor preferensi + Export Preferences Ekspor preferensi + Import Preferences Impor preferensi Search Preferences Cari preferensi No settings found Tidak ada pengaturan yang ditemukan Scale Corners Skalakan sudut @@ -3857,6 +3876,8 @@ font-technology Variable Variabel Preferences Preferensi Previous Sebelumnya Restore every preference to its default (applied on OK) Kembalikan semua preferensi ke defaultnya (diterapkan saat OK) + Reset all preferences to their defaults? Atur ulang semua preferensi ke defaultnya? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Nilai default diterapkan saat Anda mengklik OK di Preferensi. Batal di sana mempertahankan preferensi Anda saat ini. Smaller ↔ Larger Lebih kecil ↔ Lebih besar Smart Guides (View → Smart Guides) Panduan pintar (Tampilan → Panduan pintar) Couldn't save recovery data: {e} Tidak dapat menyimpan data pemulihan: {e} @@ -4085,6 +4106,7 @@ imageTrace Outline Kontur Stop Script Hentikan Skrip Show External Script Warning Tampilkan Peringatan Skrip Eksternal A Script Is Running Skrip Sedang Berjalan + Script Alert Peringatan Skrip A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. Do not show this warning again Jangan tampilkan peringatan ini lagi Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi. @@ -4602,6 +4624,20 @@ imageTrace Outline Kontur @msg unknown overprints `{o}` (preserve, simulate or discard) overprint `{o}` tidak dikenal (pertahankan, simulasikan, atau buang) @msg unknown panel `{raw}` panel `{raw}` tidak dikenal @msg unknown preference `{key}` preferensi `{key}` tidak dikenal +@msg Preferences imported. Preferensi diimpor. +@msg not a preferences file: {e} bukan file preferensi: {e} +@msg not a preferences file: no JSON object bukan file preferensi: tidak ada objek JSON +@msg not a preferences file (format `{format}`) bukan file preferensi (format `{format}`) +@msg not a preferences file: no `format` bukan file preferensi: tidak ada `format` +@msg not a preferences file: no `version` bukan file preferensi: tidak ada `version` +@msg not a preferences file: no `prefs` bukan file preferensi: tidak ada `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) file disimpan oleh versi VectorCraft yang lebih baru (versi {v}) +@msg the file holds no preferences file tidak berisi preferensi +@msg `{key}` names a folder, which preferences files leave out `{key}` menunjuk folder, dan file preferensi tidak menyertakan folder +@msg the file is larger than 1 MB file lebih besar dari 1 MB +@msg give `path` or `data` berikan `path` atau `data` +@msg `{key}` must be an object `{key}` harus berupa objek +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` dijalankan sendiri, bukan sebagai langkah batch @msg unknown preset (one of {_1}) preset tidak dikenal (salah satu dari {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) preset `{name}` tidak dikenal (tinggi, sedang, rendah, atau yang tersimpan: lihat flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) preset `{name}` tidak dikenal (lihat flattener.presets.list) @@ -5098,6 +5134,7 @@ file-filter Swatch libraries Pustaka swatch file-filter Flattener presets Preset perata file-filter PDF presets Preset PDF file-filter Print presets Preset cetak +file-filter Preferences Preferensi file-filter Export presets Preset ekspor file-filter SVG Compressed SVG terkompresi file-filter PDF-compatible .ai .ai kompatibel PDF @@ -5272,6 +5309,7 @@ mark-style Japanese Jepang Preview (1 inch on the page) Pratinjau (1 inci di halaman) Set as Default Atur sebagai default out from a highlighted edge to place its dimension | keluar dari tepi yang disorot untuk menempatkan dimensinya | + two points, then move and click to place an aligned, horizontal or vertical dimension | dua titik, lalu gerakkan dan klik untuk menempatkan dimensi sejajar, horizontal, atau vertikal | cancels | Double-click the tool for options membatalkan | Klik dua kali alat untuk opsi Angular Sudut Away from the Line Menjauhi garis @@ -5301,14 +5339,17 @@ mark-style Japanese Jepang @msg Invalid drawing scale Skala gambar tidak valid @msg Invalid real scale Skala sebenarnya tidak valid @msg Measured anchor no longer exists Titik jangkar yang diukur sudah tidak ada +@msg Invalid measured point Titik yang diukur tidak valid @msg Measured segment no longer exists Segmen yang diukur sudah tidak ada @msg Non-finite dimension Dimensi bukan bilangan berhingga +@msg Only linear dimensions are horizontal or vertical Hanya dimensi linear yang horizontal atau vertikal @msg Scale Text Attributes: selected type has no scale to bake Skalakan atribut teks: teks yang dipilih tidak memiliki skala untuk diterapkan @msg Scale must be drawing:real, for example 1:10 Skala harus dalam format gambar:sebenarnya, misalnya 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Rasio skala harus antara 1:1000000 dan 1000000:1 @msg Second measured segment no longer exists Segmen yang diukur kedua sudah tidak ada @msg Unknown dimension mode Mode dimensi tidak dikenal @msg Unknown dimension option {k} Opsi dimensi {k} tidak dikenal +@msg Unknown dimension orientation Orientasi dimensi tidak dikenal @msg Unknown dimension style Gaya dimensi tidak dikenal @msg Unknown unit Satuan tidak dikenal Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Menutup ujung melingkar profil terbuka. Sapuan parsial mempertahankan sisi potongannya tetap terbuka. @@ -5873,6 +5914,12 @@ axis Y Axis Sumbu Y Flag Bendera Crosshair Bidik silang Checkpoint Pos pemeriksaan + Inventory Icons Ikon Inventaris + Sword Pedang + Shield Perisai + Potion Ramuan + Key Kunci + Gem Permata Open Symbol Library Buka pustaka simbol Save Symbol Library Simpan pustaka simbol Save Symbol Library… Simpan pustaka simbol… @@ -6475,3 +6522,28 @@ breakText Glyphs Glif @msg side is left or right, not `{s}` side adalah left atau right, bukan `{s}` Edit Custom Dictionary Edit kamus kustom Entry: Entri: +# Script Console + Script Console Konsol Skrip + Clear Script Console Bersihkan Konsol Skrip + Copy Script Console Salin Konsol Skrip + Copy All Salin Semua + Copy Selected Salin yang Dipilih + Finished Selesai + Ended with an error Berakhir dengan galat + Out of fuel Batas instruksi tercapai + Ended at a host limit Berakhir pada batas host + Ended at a limit Berakhir pada batas + Stopped Dihentikan + Ended by an internal fault Berakhir karena galat internal + time unavailable waktu tidak tersedia + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} paling lambat: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} panggilan host +@plural {n} earlier line dropped|{n} earlier lines dropped {n} baris lama dibuang +@plural {n} line cut|{n} lines cut {n} baris dipotong + +# Deferred plug-in effects + Refresh Deferred Effects Segarkan efek yang ditunda + Deferred Effects Efek yang ditunda diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b5fd752e9b..6a8f3d7253 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -289,6 +289,7 @@ font-technology Variable Variabili Average… Media… Axis: Asse: Background Color: Colore di sfondo: + Guide Label: Etichetta delle guide: Show Center Mark Mostra segno centrale Show Cross Hairs Mostra mirino Show Video Safe Areas Mostra aree sicure video @@ -1278,6 +1279,7 @@ file-filter Swatch libraries Librerie campioni file-filter Flattener presets Preset di appiattimento file-filter PDF presets Preset PDF file-filter Print presets Preset di stampa +file-filter Preferences Preferenze file-filter Export presets Predefiniti di esportazione file-filter SVG Compressed SVG compresso file-filter PDF-compatible .ai .ai compatibile con PDF @@ -1925,6 +1927,7 @@ file-filter Templates Modelli Lock Grid Blocca griglia Lock Guides Blocca guide Lock Guides by Default Blocca guide per impostazione predefinita + Artboard Guides with Cmd/Ctrl + Ruler Drag Guide della tavola da disegno con Cmd/Ctrl + trascinamento dal righello Lock Others Blocca altri Lock Slices Blocca sezioni Lock Station Point Blocca punto di osservazione @@ -2852,6 +2855,12 @@ digits Malayalam Malayalam Reset OpenType Features Reimposta funzioni OpenType Reset Panel Reimposta pannello Reset Preferences Reimposta preferenze + Export Preferences… Esporta preferenze… + Import Preferences… Importa preferenze… + Save the applied preferences to a JSON file Salva le preferenze applicate in un file JSON + Apply the preferences in a file Export Preferences saved Applica le preferenze di un file salvato con Esporta preferenze + Export Preferences Esporta preferenze + Import Preferences Importa preferenze Search Preferences Cerca nelle preferenze No settings found Nessuna impostazione trovata Reset Profiles Reimposta profili @@ -2875,6 +2884,8 @@ digits Malayalam Malayalam Responsive Adattivo Restore Ripristina Restore every preference to its default (applied on OK) Ripristina tutte le preferenze ai valori predefiniti (applicato con OK) + Reset all preferences to their defaults? Ripristinare tutte le preferenze ai valori predefiniti? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. I valori predefiniti vengono applicati quando fai clic su OK in Preferenze. Annulla lì mantiene le preferenze attuali. Restore Recovered Documents Ripristina documenti recuperati Restored documents open unsaved: save them to keep them. I documenti ripristinati si aprono senza essere salvati: salvali per conservarli. Restrict printing, editing and other tasks Limita la stampa, la modifica e altre operazioni @@ -3182,6 +3193,13 @@ digits Malayalam Malayalam Quest Outline Missione Coin Shine Moneta Boss Alert Boss + Status Effects Effetti di stato + Poison Tint Veleno + Freeze Edge Gelo + Burn Aura Bruciatura + Stun Pulse Stordimento + Stealth Fade Furtività + Shield Buff Scudo Shape Forma Shape Builder Generatore forme Shape Builder Regions Aree del Generatore forme @@ -3601,6 +3619,8 @@ digits Malayalam Malayalam Copies per Sheet (as many as fit, in a grid) Copie per foglio (quante ne entrano, in griglia) Gutter: Spazio intermedio: Tint Tinta + Fill Tint Tinta riempimento + Stroke Tint Tinta traccia Tip extends past the end point La punta si estende oltre il punto finale Tip on the end point Punta sul punto finale Title Case Iniziali maiuscole @@ -4121,6 +4141,7 @@ axis Both Entrambi Stop Script Interrompi script Show External Script Warning Mostra avviso per gli script esterni A Script Is Running È in esecuzione uno script + Script Alert Avviso dello script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. Do not show this warning again Non mostrare più questo avviso Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. @@ -4134,6 +4155,9 @@ axis Both Entrambi @msg the script is too large to run lo script è troppo grande per essere eseguito @msg a drag or an undo group is open; finish it before running a script è aperto un trascinamento o un gruppo di annullamento; completalo prima di eseguire uno script @msg the script left a document that cannot be kept lo script ha lasciato un documento che non può essere conservato +@msg the script is no longer in the Scripts folder lo script non è più nella cartella Scripts + Some scripts were not listed Alcuni script non sono stati elencati + The Scripts folder cannot be read Impossibile leggere la cartella Scripts @msg the script's run is no longer available l'esecuzione dello script non è più disponibile @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando non riuscito ha modificato passaggi di annullamento che non è stato possibile ripristinare, quindi lo script è stato interrotto @msg a recovery copy could not be written, so the script was not run non è stato possibile scrivere una copia di recupero, quindi lo script non è stato eseguito @@ -4318,6 +4342,7 @@ axis Both Entrambi @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve essere "vertical", "horizontal" o un angolo in gradi, non `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" sfondo {other}: transparent, white, black o un colore come "#ff8800" @msg bad color {v} colore non valido {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` è null, il nome di un colore di livello o #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio deve essere un numero da 0,1 a 10 @msg the Color Picker is not open il Selettore colore non è aperto @msg the Simplify slider is not open il cursore Semplifica non è aperto @@ -4723,6 +4748,20 @@ axis Both Entrambi @msg unknown overprints `{o}` (preserve, simulate or discard) valore di sovrastampa sconosciuto `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` pannello sconosciuto `{raw}` @msg unknown preference `{key}` preferenza sconosciuta `{key}` +@msg Preferences imported. Preferenze importate. +@msg not a preferences file: {e} non è un file di preferenze: {e} +@msg not a preferences file: no JSON object non è un file di preferenze: nessun oggetto JSON +@msg not a preferences file (format `{format}`) non è un file di preferenze (formato `{format}`) +@msg not a preferences file: no `format` non è un file di preferenze: manca `format` +@msg not a preferences file: no `version` non è un file di preferenze: manca `version` +@msg not a preferences file: no `prefs` non è un file di preferenze: manca `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) il file è stato salvato da una versione più recente di VectorCraft (versione {v}) +@msg the file holds no preferences il file non contiene preferenze +@msg `{key}` names a folder, which preferences files leave out `{key}` indica una cartella, e i file di preferenze non includono cartelle +@msg the file is larger than 1 MB il file supera 1 MB +@msg give `path` or `data` specifica `path` o `data` +@msg `{key}` must be an object `{key}` deve essere un oggetto +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` viene eseguito da solo, non come passo di un batch @msg unknown preset (one of {_1}) preset sconosciuto (uno dei seguenti: {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) preset sconosciuto `{name}` (high, medium, low o uno salvato: vedi flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) preset sconosciuto `{name}` (vedi flattener.presets.list) @@ -5290,6 +5329,7 @@ lighting Light Luce Preview (1 inch on the page) Anteprima (1 pollice sulla pagina) Set as Default Imposta come predefinito out from a highlighted edge to place its dimension | verso l'esterno da un bordo evidenziato per posizionarne la quota | + two points, then move and click to place an aligned, horizontal or vertical dimension | su due punti, poi sposta e fai clic per posizionare una quota allineata, orizzontale o verticale | cancels | Double-click the tool for options annulla | Doppio clic sullo strumento per le opzioni Linear Lineare Angular Angolare @@ -5322,14 +5362,17 @@ lighting Light Luce @msg Invalid drawing scale Scala del disegno non valida @msg Invalid real scale Scala reale non valida @msg Measured anchor no longer exists Il punto di ancoraggio misurato non esiste più +@msg Invalid measured point Punto misurato non valido @msg Measured segment no longer exists Il segmento misurato non esiste più @msg Non-finite dimension Quota non finita +@msg Only linear dimensions are horizontal or vertical Solo le quote lineari sono orizzontali o verticali @msg Scale Text Attributes: selected type has no scale to bake Scala attributi di testo: il testo selezionato non ha una scala da incorporare @msg Scale must be drawing:real, for example 1:10 La scala deve essere disegno:reale, ad esempio 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Il rapporto di scala deve essere compreso tra 1:1000000 e 1000000:1 @msg Second measured segment no longer exists Il secondo segmento misurato non esiste più @msg Unknown dimension mode Modalità di quota sconosciuta @msg Unknown dimension option {k} Opzione di quota sconosciuta {k} +@msg Unknown dimension orientation Orientamento della quota sconosciuto @msg Unknown dimension style Stile di quota sconosciuto @msg Unknown unit Unità sconosciuta # Revolve cap description @@ -5701,6 +5744,12 @@ axis Y Axis Asse Y Flag Bandiera Crosshair Mirino Checkpoint Punto di controllo + Inventory Icons Icone inventario + Sword Spada + Shield Scudo + Potion Pozione + Key Chiave + Gem Gemma Open Symbol Library Apri libreria simboli Save Symbol Library Salva libreria simboli Save Symbol Library… Salva libreria simboli… @@ -6354,3 +6403,31 @@ breakText Glyphs Glifi No Suggestions Nessun suggerimento Edit Custom Dictionary Modifica dizionario personalizzato Entry: Voce: +# Script Console + Script Console Console script + Clear Script Console Cancella console script + Copy Script Console Copia console script + Copy All Copia tutto + Copy Selected Copia selezione + Finished Terminato + Ended with an error Terminato con un errore + Out of fuel Limite di istruzioni esaurito + Ended at a host limit Terminato a un limite dell'host + Ended at a limit Terminato a un limite + Stopped Interrotto + Ended by an internal fault Terminato per un errore interno + time unavailable tempo non disponibile + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} più lenti: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} chiamata all'host|{n} chiamate all'host +@plural {n} earlier line dropped|{n} earlier lines dropped {n} riga precedente scartata|{n} righe precedenti scartate +@plural {n} line cut|{n} lines cut {n} riga tagliata|{n} righe tagliate +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devono essere numeri di righe presenti nella console, `first` prima di `last` + +# Deferred plug-in effects + Refresh Deferred Effects Aggiorna effetti rimandati + Deferred Effects Effetti rimandati +@msg no plug-in effect is deferred nessun effetto plug-in è rimandato +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Aperto con {n} effetto plug-in rimandato. Effetto › Aggiorna effetti rimandati lo esegue.|Aperto con {n} effetti plug-in rimandati. Effetto › Aggiorna effetti rimandati li esegue. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 56fc8a5907..aabe534b69 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -628,6 +628,7 @@ digits Malayalam マラヤーラム数字 Hide Guides ガイドを隠す Lock Guides ガイドをロック Lock Guides by Default ガイドを初期設定でロック + Artboard Guides with Cmd/Ctrl + Ruler Drag Cmd/Ctrl + 定規からのドラッグでアートボードガイド Make Guides ガイドを作成 Release Guides ガイドを解除 Clear Guides ガイドを消去 @@ -806,6 +807,13 @@ digits Malayalam マラヤーラム数字 Quest Outline クエスト Coin Shine コイン Boss Alert ボス + Status Effects ステータス効果 + Poison Tint 毒 + Freeze Edge 凍結 + Burn Aura 火傷 + Stun Pulse 気絶 + Stealth Fade ステルス + Shield Buff シールド Outlines and Rules アウトラインと罫線 Hand-Drawn 手描き風 Gradient Finishes グラデーション仕上げ @@ -1076,6 +1084,7 @@ antiAlias Sharp シャープ Average 平均 BLANK DOCUMENT PRESETS 空白のドキュメントプリセット Background Color: 背景色: + Guide Label: ガイドのラベル: Show Center Mark 中心マークを表示 Show Cross Hairs 十字線を表示 Show Video Safe Areas ビデオセーフエリアを表示 @@ -2843,6 +2852,12 @@ mark-style Japanese 日本式 Reset OpenType Features OpenType 機能をリセット Reset Panel パネルをリセット Reset Preferences 環境設定をリセット + Export Preferences… 環境設定を書き出し… + Import Preferences… 環境設定を読み込み… + Save the applied preferences to a JSON file 適用中の環境設定を JSON ファイルに保存 + Apply the preferences in a file Export Preferences saved 「環境設定を書き出し」で保存したファイルの環境設定を適用 + Export Preferences 環境設定を書き出し + Import Preferences 環境設定を読み込み Search Preferences 環境設定を検索 No settings found 設定が見つかりません Reset Profiles プロファイルをリセット @@ -2859,6 +2874,8 @@ mark-style Japanese 日本式 Restore 復元 Restore Recovered Documents 復帰したドキュメントを復元 Restore every preference to its default (applied on OK) すべての環境設定を初期値に戻す (OK で適用) + Reset all preferences to their defaults? すべての環境設定を初期値に戻しますか? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 初期値は環境設定で OK をクリックすると適用されます。そこでキャンセルすると現在の環境設定が保たれます。 Restored documents open unsaved: save them to keep them. 復元したドキュメントは未保存の状態で開きます。保存して残してください。 Restrict printing, editing and other tasks 印刷、編集などの操作を制限 Reverse Gradient グラデーションを反転 @@ -3639,6 +3656,7 @@ file-filter Swatch libraries スウォッチライブラリ file-filter Flattener presets 分割・統合プリセット file-filter PDF presets PDF プリセット file-filter Print presets プリントプリセット +file-filter Preferences 環境設定 file-filter Export presets 書き出しプリセット file-filter SVG Compressed SVG 圧縮 file-filter PDF-compatible .ai PDF 互換の .ai @@ -3879,6 +3897,8 @@ file-filter Templates テンプレート Text Wrap Options テキストの回り込みオプション Tile Full Pages ページ全体を分割 Tint 濃度 + Fill Tint 濃度 (塗り) + Stroke Tint 濃度 (線) Tip extends past the end point 先端をパスの端点より先に伸ばす Tip on the end point 先端をパスの端点に合わせる Top 上 @@ -4427,6 +4447,20 @@ swatch Bright Violet ビビッドバイオレット @msg `{key}` must be between {min} and {max} (got {x}) `{key}` は {min} から {max} までの値にしてください (指定値: {x}) @msg `{key}` must be one of {_1} `{key}` は {_1} のいずれかにしてください @msg unknown preference `{key}` `{key}` は不明な環境設定の項目です +@msg Preferences imported. 環境設定を読み込みました。 +@msg not a preferences file: {e} 環境設定ファイルではありません: {e} +@msg not a preferences file: no JSON object 環境設定ファイルではありません: JSON オブジェクトがありません +@msg not a preferences file (format `{format}`) 環境設定ファイルではありません (形式 `{format}`) +@msg not a preferences file: no `format` 環境設定ファイルではありません: `format` がありません +@msg not a preferences file: no `version` 環境設定ファイルではありません: `version` がありません +@msg not a preferences file: no `prefs` 環境設定ファイルではありません: `prefs` がありません +@msg the file was saved by a newer version of VectorCraft (version {v}) ファイルは新しいバージョンの VectorCraft で保存されています (バージョン {v}) +@msg the file holds no preferences ファイルに環境設定がありません +@msg `{key}` names a folder, which preferences files leave out `{key}` はフォルダーを指定しますが、環境設定ファイルにはフォルダーを含めません +@msg the file is larger than 1 MB ファイルが 1 MB を超えています +@msg give `path` or `data` `path` または `data` を指定してください +@msg `{key}` must be an object `{key}` はオブジェクトである必要があります +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` は単独で実行します。バッチのステップにはできません @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) データ復帰のコピーを保存する場所がありません: 環境設定 → ファイル管理 → データ復帰 → フォルダー (recoveryFolder) を設定してください @msg Data Recovery can't keep copies in {path}: {e} データ復帰は {path} にコピーを保存できません: {e} @msg Plug-ins can't be loaded from {path}: {e} {path} からプラグインを読み込めません: {e} @@ -4660,6 +4694,7 @@ swatch Bright Violet ビビッドバイオレット @msg {label}… {label}… @msg no blend options ブレンドオプションがありません @msg bad color {v} カラー {v} が正しくありません +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` は null、レイヤーカラーの名前、または #rrggbb です @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio には 0.1 〜 10 の数値を指定してください @msg the Color Picker is not open カラーピッカーが開いていません @msg the Simplify slider is not open 単純化スライダーが開いていません @@ -4836,6 +4871,7 @@ swatch Bright Violet ビビッドバイオレット Stop Script スクリプトを停止 Show External Script Warning 外部スクリプトの警告を表示 A Script Is Running スクリプトの実行中 + Script Alert スクリプトの通知 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 Do not show this warning again 今後この警告を表示しない Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 @@ -4849,6 +4885,9 @@ swatch Bright Violet ビビッドバイオレット @msg the script is too large to run スクリプトが大きすぎて実行できません @msg a drag or an undo group is open; finish it before running a script ドラッグまたは取り消しグループが開いています。スクリプトを実行する前に完了してください @msg the script left a document that cannot be kept スクリプトが保持できないドキュメントを残しました +@msg the script is no longer in the Scripts folder スクリプトは Scripts フォルダーにもうありません + Some scripts were not listed 一部のスクリプトは一覧に表示されていません + The Scripts folder cannot be read Scripts フォルダーを読み込めません @msg the script's run is no longer available スクリプトの実行は利用できなくなりました @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗したコマンドが元に戻せない取り消し手順を変更したため、スクリプトを停止しました @msg a recovery copy could not be written, so the script was not run 復元用のコピーを書き込めなかったため、スクリプトは実行されませんでした @@ -5341,6 +5380,7 @@ lighting Light ライト Preview (1 inch on the page) プレビュー(ページ上の 1 インチ) Set as Default デフォルトに設定 out from a highlighted edge to place its dimension | でハイライトされた辺から外側へ寸法を配置 | + two points, then move and click to place an aligned, horizontal or vertical dimension | で 2 点を指定し、移動してクリックすると平行、水平または垂直の寸法を配置 | cancels | Double-click the tool for options でキャンセル | ツールをダブルクリックしてオプション Linear 直線 Angular 角度 @@ -5365,14 +5405,17 @@ lighting Light ライト @msg Invalid drawing scale 図面の縮尺が無効です @msg Invalid real scale 実寸の縮尺が無効です @msg Measured anchor no longer exists 測定したアンカーポイントはもう存在しません +@msg Invalid measured point 測定した点が無効です @msg Measured segment no longer exists 測定したセグメントはもう存在しません @msg Non-finite dimension 寸法が有限ではありません +@msg Only linear dimensions are horizontal or vertical 水平または垂直にできるのは直線寸法のみです @msg Scale Text Attributes: selected type has no scale to bake テキスト属性を拡大・縮小: 選択したテキストに取り込むスケールがありません @msg Scale must be drawing:real, for example 1:10 縮尺は 図面:実寸 の形式にしてください (例: 1:10) @msg Scale ratio must be between 1:1000000 and 1000000:1 縮尺の比率は 1:1000000 から 1000000:1 の間にしてください @msg Second measured segment no longer exists 2 番目の測定セグメントはもう存在しません @msg Unknown dimension mode 寸法のモードが不明です @msg Unknown dimension option {k} 不明な寸法オプション {k} +@msg Unknown dimension orientation 寸法の方向が不明です @msg Unknown dimension style 寸法のスタイルが不明です @msg Unknown unit 単位が不明です # Revolve cap description @@ -5766,6 +5809,12 @@ axis Y Axis Y 軸 Flag 旗 Crosshair クロスヘア Checkpoint チェックポイント + Inventory Icons インベントリアイコン + Sword 剣 + Shield 盾 + Potion ポーション + Key 鍵 + Gem 宝石 Open Symbol Library シンボルライブラリを開く Save Symbol Library シンボルライブラリを保存 Save Symbol Library… シンボルライブラリを保存… @@ -6419,3 +6468,31 @@ breakText Glyphs 字形 No Suggestions 候補なし Edit Custom Dictionary カスタム辞書を編集 Entry: エントリ: +# Script Console + Script Console スクリプトコンソール + Clear Script Console スクリプトコンソールを消去 + Copy Script Console スクリプトコンソールをコピー + Copy All すべてコピー + Copy Selected 選択範囲をコピー + Finished 完了 + Ended with an error エラーで終了 + Out of fuel 命令数の上限に到達 + Ended at a host limit ホストの上限で終了 + Ended at a limit 上限で終了 + Stopped 停止 + Ended by an internal fault 内部エラーで終了 + time unavailable 時間を取得できません + {ms} ms {ms} ms + {time}, {calls} {time}、{calls} + slowest: {commands} 最も遅いコマンド:{commands} + {dropped}, {cut} {dropped}、{cut} +@plural {n} host call|{n} host calls ホスト呼び出し {n} 回 +@plural {n} earlier line dropped|{n} earlier lines dropped 古い行 {n} 行を破棄 +@plural {n} line cut|{n} lines cut {n} 行を切り詰め +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` と `last` には、コンソールが保持している行の番号を、`first` が `last` より前になるよう指定してください + +# Deferred plug-in effects + Refresh Deferred Effects 保留中の効果を更新 + Deferred Effects 保留中の効果 +@msg no plug-in effect is deferred 保留中のプラグイン効果はありません +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. プラグイン効果を {n} 件保留して開きました。「効果 › 保留中の効果を更新」で実行します。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 388dd4a01e..bb6a5da7d9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -522,6 +522,7 @@ Show Guides დამხმარე ხაზების ჩვენება Lock Guides დამხმარე ხაზების ჩაკეტვა Lock Guides by Default დამხმარე ხაზების ნაგულისხმევად ჩაკეტვა + Artboard Guides with Cmd/Ctrl + Ruler Drag სამუშაო დაფის დამხმარე ხაზები Cmd/Ctrl + სახაზავიდან გადათრევით Unlock Guides დამხმარე ხაზების განბლოკვა Make Guides დამხმარე ხაზების შექმნა Release Guides დამხმარე ხაზების მოხსნა @@ -669,6 +670,13 @@ Quest Outline ქვესტი Coin Shine მონეტა Boss Alert ბოსი + Status Effects სტატუსის ეფექტები + Poison Tint შხამი + Freeze Edge გაყინვა + Burn Aura დაწვა + Stun Pulse დაბნეულობა + Stealth Fade შენიღბვა + Shield Buff ფარი Outlines and Rules კონტურები და ხაზები Hand-Drawn ხელით დახატული Gradient Finishes გრადიენტული ზედაპირები @@ -1994,6 +2002,8 @@ digits Malayalam მალაიალამური Green მწვანე Shifts the tints of global and spot colors; other colors stay. ცვლის გლობალური და სპოტ-ფერების ტონირებებს; სხვა ფერები უცვლელი რჩება. Tint ტონირება + Fill Tint შევსების ტონირება + Stroke Tint კონტურის ტონირება Color Guide Options ფერის გზამკვლევის პარამეტრები Less ნაკლები Steps: ბიჯები: @@ -2342,6 +2352,7 @@ digits Malayalam მალაიალამური File Dimensions ფაილის ზომები Transforms გარდაქმნები Background Color: ფონის ფერი: + Guide Label: დამხმარე ხაზების იარლიყი: Show Center Mark ცენტრის ნიშნის ჩვენება Show Cross Hairs ჯვარედინი ხაზების ჩვენება Show Video Safe Areas ვიდეოს უსაფრთხო არეების ჩვენება @@ -3307,6 +3318,12 @@ theme Appearance იერსახე Real-time Drawing and Editing რეალურ დროში ხატვა და რედაქტირება Render Threads (-1 = Automatic) ნაკადები (-1 = ავტომატური) Reset Preferences პარამეტრების ჩამოყრა + Export Preferences… პარამეტრების ექსპორტირება… + Import Preferences… პარამეტრების იმპორტირება… + Save the applied preferences to a JSON file გამოყენებული პარამეტრების შენახვა JSON ფაილში + Apply the preferences in a file Export Preferences saved პარამეტრების გამოყენება ფაილიდან, რომელიც „პარამეტრების ექსპორტირებამ“ შეინახა + Export Preferences პარამეტრების ექსპორტირება + Import Preferences პარამეტრების იმპორტირება Search Preferences პარამეტრებში ძიება No settings found პარამეტრები ვერ მოიძებნა Scale Corners კუთხეების მასშტაბირება @@ -3648,6 +3665,8 @@ font-technology Variable ცვლადი Preferences პარამეტრები Previous წინა Restore every preference to its default (applied on OK) ყველა პარამეტრის ნაგულისხმევ მნიშვნელობაზე დაბრუნება (გამოიყენება OK-ზე დაჭერისას) + Reset all preferences to their defaults? დავაბრუნოთ ყველა პარამეტრი ნაგულისხმევ მნიშვნელობებზე? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. ნაგულისხმევი მნიშვნელობები გამოიყენება, როცა პარამეტრებში OK-ს დააჭერთ. იქ გაუქმება ინარჩუნებს თქვენს მიმდინარე პარამეტრებს. Smaller ↔ Larger უფრო პატარა ↔ უფრო დიდი Smart Guides (View → Smart Guides) ჭკვიანი დამხმარე ხაზები (ხედი → ჭკვიანი დამხმარე ხაზები) Couldn't save recovery data: {e} აღდგენის მონაცემები ვერ შეინახა: {e} @@ -4033,6 +4052,7 @@ font-technology Variable ცვლადი @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis უნდა იყოს "vertical", "horizontal" ან კუთხე გრადუსებში და არა `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" ფონი {other}: transparent, white, black ან ფერი, მაგალითად "#ff8800" @msg bad color {v} არასწორი ფერი {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` არის null, ფენის ფერის სახელი ან #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio უნდა იყოს რიცხვი 0,1-დან 10-მდე @msg bad colour `{hex}` (#rrggbb) არასწორი ფერი `{hex}` (#rrggbb) @msg bad page tree გვერდების არასწორი ხე @@ -4405,6 +4425,20 @@ font-technology Variable ცვლადი @msg unknown overprints `{o}` (preserve, simulate or discard) უცნობი ზედდაბეჭდვა `{o}` (preserve, simulate ან discard) @msg unknown panel `{raw}` უცნობი პანელი `{raw}` @msg unknown preference `{key}` უცნობი პარამეტრი `{key}` +@msg Preferences imported. პარამეტრები იმპორტირებულია. +@msg not a preferences file: {e} ეს არ არის პარამეტრების ფაილი: {e} +@msg not a preferences file: no JSON object ეს არ არის პარამეტრების ფაილი: JSON ობიექტი არ არის +@msg not a preferences file (format `{format}`) ეს არ არის პარამეტრების ფაილი (ფორმატი `{format}`) +@msg not a preferences file: no `format` ეს არ არის პარამეტრების ფაილი: `format` არ არის +@msg not a preferences file: no `version` ეს არ არის პარამეტრების ფაილი: `version` არ არის +@msg not a preferences file: no `prefs` ეს არ არის პარამეტრების ფაილი: `prefs` არ არის +@msg the file was saved by a newer version of VectorCraft (version {v}) ფაილი შენახულია VectorCraft-ის უფრო ახალი ვერსიით (ვერსია {v}) +@msg the file holds no preferences ფაილში პარამეტრები არ არის +@msg `{key}` names a folder, which preferences files leave out `{key}` საქაღალდეს მიუთითებს, პარამეტრების ფაილები კი საქაღალდეებს არ შეიცავს +@msg the file is larger than 1 MB ფაილი 1 MB-ზე დიდია +@msg give `path` or `data` მიუთითეთ `path` ან `data` +@msg `{key}` must be an object `{key}` უნდა იყოს ობიექტი +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` ცალკე სრულდება და არა პაკეტის ნაბიჯად @msg unknown preset (one of {_1}) უცნობი პრესეტი (ერთ-ერთი: {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) უცნობი პრესეტი `{name}` (high, medium, low ან შენახული: იხ. flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) უცნობი პრესეტი `{name}` (იხ. flattener.presets.list) @@ -4991,6 +5025,7 @@ file-filter Swatch libraries ფერის ნიმუშების ბი file-filter Flattener presets გაბრტყელების პრესეტები file-filter PDF presets PDF-ის პრესეტები file-filter Print presets ბეჭდვის პრესეტები +file-filter Preferences პარამეტრები file-filter Export presets ექსპორტის პრესეტები file-filter SVG Compressed შეკუმშული SVG file-filter PDF-compatible .ai PDF-თან თავსებადი .ai @@ -5151,6 +5186,7 @@ imageTrace Outline კონტური Stop Script სკრიპტის შეჩერება Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება A Script Is Running სკრიპტი მუშაობს + Script Alert სკრიპტის შეტყობინება A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. Do not show this warning again აღარ აჩვენო ეს გაფრთხილება Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. @@ -5164,6 +5200,9 @@ imageTrace Outline კონტური @msg the script is too large to run სკრიპტი გასაშვებად ძალიან დიდია @msg a drag or an undo group is open; finish it before running a script ღიაა გადათრევა ან გაუქმების ჯგუფი; დაასრულეთ სკრიპტის გაშვებამდე @msg the script left a document that cannot be kept სკრიპტმა დატოვა დოკუმენტი, რომლის შენახვა შეუძლებელია +@msg the script is no longer in the Scripts folder სკრიპტი აღარ არის Scripts საქაღალდეში + Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი + The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია @msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი @msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ შეცვალა გაუქმების ნაბიჯები, რომელთა აღდგენა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა @msg a recovery copy could not be written, so the script was not run აღდგენის ასლის ჩაწერა ვერ მოხერხდა, ამიტომ სკრიპტი არ გაეშვა @@ -5287,6 +5326,7 @@ imageTrace Outline კონტური Preview (1 inch on the page) წინასწარი ნახვა (1 დუიმი გვერდზე) Set as Default ნაგულისხმევად დაყენება out from a highlighted edge to place its dimension | — გამოკვეთილი კიდიდან გარეთ, მისი ზომის დასასმელად | + two points, then move and click to place an aligned, horizontal or vertical dimension | — ორ წერტილზე, შემდეგ გადაადგილეთ და დააწკაპუნეთ გასწორებული, ჰორიზონტალური ან ვერტიკალური ზომის დასასმელად | cancels | Double-click the tool for options — გაუქმება | პარამეტრებისთვის ორჯერ დაწკაპეთ ხელსაწყოზე Angular კუთხური Away from the Line ხაზისგან მოშორებით @@ -5316,14 +5356,17 @@ imageTrace Outline კონტური @msg Invalid drawing scale ნახაზის არასწორი მასშტაბი @msg Invalid real scale რეალური ზომის არასწორი მასშტაბი @msg Measured anchor no longer exists გაზომილი საყრდენი წერტილი აღარ არსებობს +@msg Invalid measured point გაზომილი წერტილი არასწორია @msg Measured segment no longer exists გაზომილი სეგმენტი აღარ არსებობს @msg Non-finite dimension ზომა სასრული რიცხვი არ არის +@msg Only linear dimensions are horizontal or vertical მხოლოდ ხაზოვანი ზომებია ჰორიზონტალური ან ვერტიკალური @msg Scale Text Attributes: selected type has no scale to bake ტექსტის ატრიბუტების მასშტაბირება: არჩეულ ტექსტს არ აქვს გადასაყვანი მასშტაბი @msg Scale must be drawing:real, for example 1:10 მასშტაბი უნდა იყოს ნახაზი:რეალური, მაგალითად 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 მასშტაბის შეფარდება 1:1000000-სა და 1000000:1-ს შორის უნდა იყოს @msg Second measured segment no longer exists მეორე გაზომილი სეგმენტი აღარ არსებობს @msg Unknown dimension mode ზომის უცნობი რეჟიმი @msg Unknown dimension option {k} ზომის უცნობი პარამეტრი {k} +@msg Unknown dimension orientation ზომის უცნობი ორიენტაცია @msg Unknown dimension style ზომის უცნობი სტილი @msg Unknown unit უცნობი ერთეული Close the circular ends of open profiles. Partial sweeps keep their cut sides open. ღია პროფილების წრიული ბოლოების დახურვა. ნაწილობრივი ბრუნვისას ჭრის მხარეები ღია რჩება. @@ -6007,6 +6050,12 @@ axis Y Axis Y ღერძი Flag დროშა Crosshair სამიზნე Checkpoint საკონტროლო წერტილი + Inventory Icons ინვენტარის ხატულები + Sword მახვილი + Shield ფარი + Potion წამალი + Key გასაღები + Gem ძვირფასი ქვა Open Symbol Library სიმბოლოების ბიბლიოთეკის გახსნა Save Symbol Library სიმბოლოების ბიბლიოთეკის შენახვა Save Symbol Library… სიმბოლოების ბიბლიოთეკის შენახვა… @@ -6794,3 +6843,31 @@ font-script Japanese იაპონური No Suggestions შემოთავაზებები არ არის Edit Custom Dictionary მომხმარებლის ლექსიკონის რედაქტირება Entry: ჩანაწერი: +# Script Console + Script Console სკრიპტების კონსოლი + Clear Script Console სკრიპტების კონსოლის გასუფთავება + Copy Script Console სკრიპტების კონსოლის კოპირება + Copy All ყველაფრის კოპირება + Copy Selected მონიშნულის კოპირება + Finished დასრულდა + Ended with an error დასრულდა შეცდომით + Out of fuel ინსტრუქციების ლიმიტი ამოიწურა + Ended at a host limit დასრულდა ჰოსტის ლიმიტზე + Ended at a limit დასრულდა ლიმიტზე + Stopped შეჩერდა + Ended by an internal fault დასრულდა შიდა შეცდომის გამო + time unavailable დრო მიუწვდომელია + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} ყველაზე ნელი: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls ჰოსტის {n} გამოძახება +@plural {n} earlier line dropped|{n} earlier lines dropped {n} ძველი სტრიქონი წაიშალა +@plural {n} line cut|{n} lines cut {n} სტრიქონი შემოკლდა +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` და `last` უნდა იყოს კონსოლში შენახული სტრიქონების ნომრები და `first` უნდა იყოს `last`-ზე წინ + +# Deferred plug-in effects + Refresh Deferred Effects გადადებული ეფექტების განახლება + Deferred Effects გადადებული ეფექტები +@msg no plug-in effect is deferred პლაგინის ეფექტი არ არის გადადებული +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. გაიხსნა, გადადებული პლაგინის ეფექტები: {n}. ეფექტი › გადადებული ეფექტების განახლება მათ გაუშვებს. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 03930932a7..b7f5824635 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -623,6 +623,7 @@ digits Malayalam 말라얄람어 Hide Guides 안내선 숨기기 Lock Guides 안내선 잠그기 Lock Guides by Default 기본적으로 안내선 잠그기 + Artboard Guides with Cmd/Ctrl + Ruler Drag Cmd/Ctrl + 눈금자 드래그로 아트보드 안내선 Make Guides 안내선 만들기 Release Guides 안내선 해제 Clear Guides 안내선 지우기 @@ -799,6 +800,13 @@ digits Malayalam 말라얄람어 Quest Outline 퀘스트 Coin Shine 코인 Boss Alert 보스 + Status Effects 상태 효과 + Poison Tint 독 + Freeze Edge 빙결 + Burn Aura 화상 + Stun Pulse 기절 + Stealth Fade 은신 + Shield Buff 방패 Outlines and Rules 윤곽선과 괘선 Hand-Drawn 손그림 Gradient Finishes 그레이디언트 마감 @@ -1066,6 +1074,7 @@ antiAlias Sharp 날카롭게 Average 평균 BLANK DOCUMENT PRESETS 빈 문서 프리셋 Background Color: 배경색: + Guide Label: 안내선 레이블: Show Center Mark 중심 표시 보기 Show Cross Hairs 십자선 보기 Show Video Safe Areas 비디오 안전 영역 보기 @@ -2832,6 +2841,12 @@ mark-style Japanese 일본식 Reset OpenType Features OpenType 기능 재설정 Reset Panel 패널 재설정 Reset Preferences 환경 설정 재설정 + Export Preferences… 환경 설정 내보내기… + Import Preferences… 환경 설정 가져오기… + Save the applied preferences to a JSON file 적용된 환경 설정을 JSON 파일로 저장 + Apply the preferences in a file Export Preferences saved 환경 설정 내보내기로 저장한 파일의 환경 설정 적용 + Export Preferences 환경 설정 내보내기 + Import Preferences 환경 설정 가져오기 Search Preferences 환경 설정 검색 No settings found 설정을 찾을 수 없음 Reset Profiles 프로필 재설정 @@ -2848,6 +2863,8 @@ mark-style Japanese 일본식 Restore 복원 Restore Recovered Documents 복구된 문서 복원 Restore every preference to its default (applied on OK) 모든 환경 설정을 기본값으로 복원(확인 시 적용) + Reset all preferences to their defaults? 모든 환경 설정을 기본값으로 재설정하시겠습니까? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 기본값은 환경 설정에서 확인을 클릭하면 적용됩니다. 그곳에서 취소를 누르면 현재 환경 설정이 유지됩니다. Restored documents open unsaved: save them to keep them. 복원된 문서는 저장되지 않은 상태로 열립니다. 보존하려면 저장하세요. Restrict printing, editing and other tasks 인쇄, 편집 등의 작업 제한 Reverse Gradient 그레이디언트 반전 @@ -3627,6 +3644,7 @@ file-filter Swatch libraries 견본 라이브러리 file-filter Flattener presets 병합 프리셋 file-filter PDF presets PDF 프리셋 file-filter Print presets 인쇄 프리셋 +file-filter Preferences 환경 설정 file-filter Export presets 내보내기 사전 설정 file-filter SVG Compressed 압축된 SVG file-filter PDF-compatible .ai PDF 호환 .ai @@ -3867,6 +3885,8 @@ file-filter Templates 템플릿 Text Wrap Options 텍스트 감싸기 옵션 Tile Full Pages 전체 페이지 타일링 Tint 색조 + Fill Tint 칠 색조 + Stroke Tint 선 색조 Tip extends past the end point 끝이 끝점을 지나 연장됨 Tip on the end point 끝이 끝점에 위치 Top 위쪽 @@ -4354,6 +4374,20 @@ theme Appearance 외관 @msg `{key}` must be between {min} and {max} (got {x}) `{key}`은(는) {min}에서 {max} 사이여야 합니다({x} 입력됨) @msg `{key}` must be one of {_1} `{key}`은(는) {_1} 중 하나여야 합니다 @msg unknown preference `{key}` 알 수 없는 환경 설정 `{key}` +@msg Preferences imported. 환경 설정을 가져왔습니다. +@msg not a preferences file: {e} 환경 설정 파일이 아닙니다: {e} +@msg not a preferences file: no JSON object 환경 설정 파일이 아닙니다: JSON 개체가 없습니다 +@msg not a preferences file (format `{format}`) 환경 설정 파일이 아닙니다(형식 `{format}`) +@msg not a preferences file: no `format` 환경 설정 파일이 아닙니다: `format`이 없습니다 +@msg not a preferences file: no `version` 환경 설정 파일이 아닙니다: `version`이 없습니다 +@msg not a preferences file: no `prefs` 환경 설정 파일이 아닙니다: `prefs`가 없습니다 +@msg the file was saved by a newer version of VectorCraft (version {v}) 더 새로운 버전의 VectorCraft에서 저장한 파일입니다(버전 {v}) +@msg the file holds no preferences 파일에 환경 설정이 없습니다 +@msg `{key}` names a folder, which preferences files leave out `{key}`은(는) 폴더를 지정하며, 환경 설정 파일에는 폴더가 포함되지 않습니다 +@msg the file is larger than 1 MB 파일이 1MB보다 큽니다 +@msg give `path` or `data` `path` 또는 `data`를 지정하세요 +@msg `{key}` must be an object `{key}`은(는) 개체여야 합니다 +@msg `prefs.import` runs on its own, not as a batch step `prefs.import`은(는) 일괄 처리 단계가 아니라 단독으로 실행됩니다 @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 데이터 복구에 복사본을 보관할 곳이 없습니다. 환경 설정 → 파일 처리 → 데이터 복구 → 폴더(recoveryFolder)를 지정하세요 @msg Data Recovery can't keep copies in {path}: {e} 데이터 복구가 {path}에 복사본을 보관할 수 없습니다: {e} @msg Plug-ins can't be loaded from {path}: {e} {path}에서 플러그인을 불러올 수 없습니다: {e} @@ -4587,6 +4621,7 @@ theme Appearance 외관 @msg {label}… {label}… @msg no blend options 혼합 옵션이 없습니다 @msg bad color {v} 잘못된 색상 {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel`은 null, 레이어 색상 이름 또는 #rrggbb입니다 @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio은(는) 0.1에서 10 사이의 숫자여야 합니다 @msg the Color Picker is not open 색상 피커가 열려 있지 않습니다 @msg the Simplify slider is not open 단순화 슬라이더가 열려 있지 않습니다 @@ -4763,6 +4798,7 @@ theme Appearance 외관 Stop Script 스크립트 중지 Show External Script Warning 외부 스크립트 경고 표시 A Script Is Running 스크립트 실행 중 + Script Alert 스크립트 알림 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. Do not show this warning again 이 경고를 다시 표시하지 않음 Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. @@ -4776,6 +4812,9 @@ theme Appearance 외관 @msg the script is too large to run 스크립트가 너무 커서 실행할 수 없습니다 @msg a drag or an undo group is open; finish it before running a script 드래그 또는 실행 취소 그룹이 열려 있습니다. 스크립트를 실행하기 전에 완료하세요 @msg the script left a document that cannot be kept 스크립트가 유지할 수 없는 문서를 남겼습니다 +@msg the script is no longer in the Scripts folder 스크립트가 더 이상 Scripts 폴더에 없습니다 + Some scripts were not listed 일부 스크립트가 나열되지 않았습니다 + The Scripts folder cannot be read Scripts 폴더를 읽을 수 없습니다 @msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다 @msg a failed command changed undo steps that could not be put back, so the script was stopped 실패한 명령이 되돌릴 수 없는 실행 취소 단계를 변경하여 스크립트를 중지했습니다 @msg a recovery copy could not be written, so the script was not run 복구 사본을 쓸 수 없어 스크립트를 실행하지 않았습니다 @@ -5251,6 +5290,7 @@ lighting Light 광원 Preview (1 inch on the page) 미리 보기 (페이지의 1인치) Set as Default 기본값으로 설정 out from a highlighted edge to place its dimension | 강조된 가장자리에서 바깥쪽으로 끌어 치수 배치 | + two points, then move and click to place an aligned, horizontal or vertical dimension | 으로 두 점을 지정한 다음 이동하고 클릭하여 정렬, 가로 또는 세로 치수 배치 | cancels | Double-click the tool for options 취소 | 도구를 두 번 클릭하면 옵션 Linear 선형 Angular 각도 @@ -5283,14 +5323,17 @@ lighting Light 광원 @msg Invalid drawing scale 잘못된 도면 축척 @msg Invalid real scale 잘못된 실제 축척 @msg Measured anchor no longer exists 측정한 고정점이 더 이상 없습니다 +@msg Invalid measured point 측정한 점이 잘못되었습니다 @msg Measured segment no longer exists 측정한 세그먼트가 더 이상 없습니다 @msg Non-finite dimension 유한하지 않은 치수 +@msg Only linear dimensions are horizontal or vertical 선형 치수만 가로 또는 세로로 지정할 수 있습니다 @msg Scale Text Attributes: selected type has no scale to bake 텍스트 속성 크기 조절: 선택한 텍스트에 적용할 크기 조절이 없습니다 @msg Scale must be drawing:real, for example 1:10 축척은 도면:실제 형식이어야 합니다(예: 1:10) @msg Scale ratio must be between 1:1000000 and 1000000:1 축척 비율은 1:1000000에서 1000000:1 사이여야 합니다 @msg Second measured segment no longer exists 두 번째 측정 세그먼트가 더 이상 없습니다 @msg Unknown dimension mode 알 수 없는 치수 모드 @msg Unknown dimension option {k} 알 수 없는 치수 옵션 {k} +@msg Unknown dimension orientation 알 수 없는 치수 방향 @msg Unknown dimension style 알 수 없는 치수 스타일 @msg Unknown unit 알 수 없는 단위 # Revolve cap description @@ -5662,6 +5705,12 @@ axis Y Axis Y축 Flag 깃발 Crosshair 십자선 Checkpoint 체크포인트 + Inventory Icons 인벤토리 아이콘 + Sword 검 + Shield 방패 + Potion 포션 + Key 열쇠 + Gem 보석 Open Symbol Library 심볼 라이브러리 열기 Save Symbol Library 심볼 라이브러리 저장 Save Symbol Library… 심볼 라이브러리 저장… @@ -6315,3 +6364,31 @@ breakText Glyphs 글리프 No Suggestions 제안 없음 Edit Custom Dictionary 사용자 사전 편집 Entry: 항목: +# Script Console + Script Console 스크립트 콘솔 + Clear Script Console 스크립트 콘솔 지우기 + Copy Script Console 스크립트 콘솔 복사 + Copy All 모두 복사 + Copy Selected 선택 항목 복사 + Finished 완료됨 + Ended with an error 오류로 종료됨 + Out of fuel 명령 한도에 도달함 + Ended at a host limit 호스트 한도에서 종료됨 + Ended at a limit 한도에서 종료됨 + Stopped 중지됨 + Ended by an internal fault 내부 오류로 종료됨 + time unavailable 시간 정보 없음 + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} 가장 느린 명령: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls 호스트 호출 {n}회 +@plural {n} earlier line dropped|{n} earlier lines dropped 이전 줄 {n}개 삭제됨 +@plural {n} line cut|{n} lines cut 줄 {n}개 잘림 +@msg `first` and `last` must be numbers of lines the console holds, first before last `first`와 `last`는 콘솔에 있는 줄 번호여야 하며 `first`가 `last`보다 앞서야 합니다 + +# Deferred plug-in effects + Refresh Deferred Effects 보류된 효과 새로 고침 + Deferred Effects 보류된 효과 +@msg no plug-in effect is deferred 보류된 플러그인 효과가 없습니다 +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. 플러그인 효과 {n}개를 보류하고 열었습니다. 효과 › 보류된 효과 새로 고침으로 실행합니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c5151622d4..32db6785bb 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -55,6 +55,8 @@ Scripts Scripts Check Script… Script controleren… Check Script Script controleren + Some scripts were not listed Sommige scripts zijn niet weergegeven + The Scripts folder cannot be read De map Scripts kan niet worden gelezen Other Script… Ander script… Document Setup… Documentinstellingen… Switch Units Eenheden wisselen @@ -574,6 +576,7 @@ Show Guides Hulplijnen tonen Lock Guides Hulplijnen vergrendelen Lock Guides by Default Hulplijnen standaard vergrendelen + Artboard Guides with Cmd/Ctrl + Ruler Drag Tekenbordhulplijnen met Cmd/Ctrl + slepen vanuit liniaal Unlock Guides Hulplijnen ontgrendelen Make Guides Hulplijnen maken Release Guides Hulplijnen vrijgeven @@ -733,6 +736,13 @@ Quest Outline Quest Coin Shine Munt Boss Alert Baas + Status Effects Statuseffecten + Poison Tint Gif + Freeze Edge Bevriezing + Burn Aura Brand + Stun Pulse Verdoving + Stealth Fade Sluipen + Shield Buff Schild Outlines and Rules Omtrekken en lijnen Hand-Drawn Handgetekend Gradient Finishes Verloopafwerkingen @@ -2102,6 +2112,8 @@ digits Malayalam Malayalam Green Groen Shifts the tints of global and spot colors; other colors stay. Verschuift de tinten van globale kleuren en spotkleuren; andere kleuren blijven ongewijzigd. Tint Tint + Fill Tint Vultint + Stroke Tint Contourtint Color Guide Options Opties voor kleurengids Less Minder Steps: Stappen: @@ -2455,6 +2467,7 @@ digits Malayalam Malayalam File Dimensions Bestandsafmetingen Transforms Transformaties Background Color: Achtergrondkleur: + Guide Label: Hulplijnlabel: Show Center Mark Middenmarkering tonen Show Cross Hairs Dradenkruis tonen Show Video Safe Areas Veilige videogebieden tonen @@ -3501,6 +3514,12 @@ theme Appearance Vormgeving Real-time Drawing and Editing Tekenen en bewerken in realtime Render Threads (-1 = Automatic) Renderthreads (-1 = automatisch) Reset Preferences Voorkeuren herstellen + Export Preferences… Voorkeuren exporteren… + Import Preferences… Voorkeuren importeren… + Save the applied preferences to a JSON file De toegepaste voorkeuren in een JSON-bestand opslaan + Apply the preferences in a file Export Preferences saved De voorkeuren toepassen uit een bestand dat Voorkeuren exporteren heeft opgeslagen + Export Preferences Voorkeuren exporteren + Import Preferences Voorkeuren importeren Search Preferences Voorkeuren doorzoeken No settings found Geen instellingen gevonden Scale Corners Hoeken schalen @@ -3871,6 +3890,8 @@ font-technology Variable Variabel Preferences Voorkeuren Previous Vorige Restore every preference to its default (applied on OK) Elke voorkeur terugzetten naar de standaard (toegepast bij OK) + Reset all preferences to their defaults? Alle voorkeuren terugzetten naar de standaardwaarden? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. De standaardwaarden worden toegepast wanneer u in Voorkeuren op OK klikt. Annuleren daar behoudt uw huidige voorkeuren. Smaller ↔ Larger Kleiner ↔ Groter Smart Guides (View → Smart Guides) Slimme hulplijnen (Beeld → Slimme hulplijnen) Couldn't save recovery data: {e} Kon herstelgegevens niet opslaan: {e} @@ -4099,6 +4120,7 @@ imageTrace Outline Contour Stop Script Script stoppen Show External Script Warning Waarschuwing voor externe scripts tonen A Script Is Running Er wordt een script uitgevoerd + Script Alert Scriptmelding A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. Do not show this warning again Deze waarschuwing niet meer tonen Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af. @@ -4614,6 +4636,20 @@ imageTrace Outline Contour @msg unknown overprints `{o}` (preserve, simulate or discard) onbekende overdruk `{o}` (behouden, simuleren of verwerpen) @msg unknown panel `{raw}` onbekend paneel `{raw}` @msg unknown preference `{key}` onbekende voorkeur `{key}` +@msg Preferences imported. Voorkeuren geïmporteerd. +@msg not a preferences file: {e} geen voorkeurenbestand: {e} +@msg not a preferences file: no JSON object geen voorkeurenbestand: geen JSON-object +@msg not a preferences file (format `{format}`) geen voorkeurenbestand (indeling `{format}`) +@msg not a preferences file: no `format` geen voorkeurenbestand: geen `format` +@msg not a preferences file: no `version` geen voorkeurenbestand: geen `version` +@msg not a preferences file: no `prefs` geen voorkeurenbestand: geen `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) het bestand is opgeslagen met een nieuwere versie van VectorCraft (versie {v}) +@msg the file holds no preferences het bestand bevat geen voorkeuren +@msg `{key}` names a folder, which preferences files leave out `{key}` geeft een map aan, en voorkeurenbestanden bevatten geen mappen +@msg the file is larger than 1 MB het bestand is groter dan 1 MB +@msg give `path` or `data` geef `path` of `data` op +@msg `{key}` must be an object `{key}` moet een object zijn +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` wordt los uitgevoerd, niet als stap van een batch @msg unknown preset (one of {_1}) onbekende voorinstelling (één van {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) onbekende voorinstelling `{name}` (hoog, middel, laag of een opgeslagen voorinstelling: zie flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) onbekende voorinstelling `{name}` (zie flattener.presets.list) @@ -5110,6 +5146,7 @@ file-filter Swatch libraries Stalenbibliotheken file-filter Flattener presets Afvlakvoorinstellingen file-filter PDF presets PDF-voorinstellingen file-filter Print presets Afdrukvoorinstellingen +file-filter Preferences Voorkeuren file-filter Export presets Exportvoorinstellingen file-filter SVG Compressed Gecomprimeerde SVG file-filter PDF-compatible .ai PDF-compatibel .ai @@ -5284,6 +5321,7 @@ mark-style Japanese Japans Preview (1 inch on the page) Voorbeeld (1 inch op de pagina) Set as Default Als standaard instellen out from a highlighted edge to place its dimension | uit een gemarkeerde rand om de bijbehorende maatlijn te plaatsen | + two points, then move and click to place an aligned, horizontal or vertical dimension | op twee punten, verplaats daarna en klik om een uitgelijnde, horizontale of verticale maatlijn te plaatsen | cancels | Double-click the tool for options annuleert | Dubbelklik op het gereedschap voor opties Angular Hoek Away from the Line Van de lijn af @@ -5313,14 +5351,17 @@ mark-style Japanese Japans @msg Invalid drawing scale Ongeldige tekeningsschaal @msg Invalid real scale Ongeldige werkelijke schaal @msg Measured anchor no longer exists Gemeten ankerpunt bestaat niet meer +@msg Invalid measured point Ongeldig gemeten punt @msg Measured segment no longer exists Gemeten segment bestaat niet meer @msg Non-finite dimension Niet-eindige maatlijn +@msg Only linear dimensions are horizontal or vertical Alleen lineaire maatlijnen zijn horizontaal of verticaal @msg Scale Text Attributes: selected type has no scale to bake Tekstkenmerken schalen: de geselecteerde tekst heeft geen schaling om toe te passen @msg Scale must be drawing:real, for example 1:10 Schaal moet tekening:werkelijk zijn, bijvoorbeeld 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Schaalverhouding moet tussen 1:1000000 en 1000000:1 liggen @msg Second measured segment no longer exists Tweede gemeten segment bestaat niet meer @msg Unknown dimension mode Onbekende maatlijnmodus @msg Unknown dimension option {k} Onbekende maatlijnoptie {k} +@msg Unknown dimension orientation Onbekende maatlijnrichting @msg Unknown dimension style Onbekende maatlijnstijl @msg Unknown unit Onbekende eenheid Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Sluit de ronde uiteinden van open profielen. Gedeeltelijke omwentelingen houden hun afgesneden zijden open. @@ -5924,6 +5965,12 @@ axis Y Axis Y-as Flag Vlag Crosshair Vizier Checkpoint Controlepunt + Inventory Icons Inventarisiconen + Sword Zwaard + Shield Schild + Potion Drank + Key Sleutel + Gem Edelsteen Open Symbol Library Symboolbibliotheek openen Save Symbol Library Symboolbibliotheek opslaan Save Symbol Library… Symboolbibliotheek opslaan… @@ -6526,3 +6573,28 @@ breakText Glyphs Glyphs @msg side is left or right, not `{s}` side is left of right, niet `{s}` Edit Custom Dictionary Aangepast woordenboek bewerken Entry: Item: +# Script Console + Script Console Scriptconsole + Clear Script Console Scriptconsole wissen + Copy Script Console Scriptconsole kopiëren + Copy All Alles kopiëren + Copy Selected Selectie kopiëren + Finished Voltooid + Ended with an error Beëindigd met een fout + Out of fuel Instructielimiet bereikt + Ended at a host limit Beëindigd bij een hostlimiet + Ended at a limit Beëindigd bij een limiet + Stopped Gestopt + Ended by an internal fault Beëindigd door een interne fout + time unavailable tijd niet beschikbaar + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} traagste: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} host-aanroep|{n} host-aanroepen +@plural {n} earlier line dropped|{n} earlier lines dropped {n} eerdere regel verwijderd|{n} eerdere regels verwijderd +@plural {n} line cut|{n} lines cut {n} regel ingekort|{n} regels ingekort + +# Deferred plug-in effects + Refresh Deferred Effects Uitgestelde effecten vernieuwen + Deferred Effects Uitgestelde effecten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 58016a4bd0..398adf5f50 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -567,6 +567,7 @@ Show Guides Pokaż linie pomocnicze Lock Guides Zablokuj linie pomocnicze Lock Guides by Default Domyślnie blokuj linie pomocnicze + Artboard Guides with Cmd/Ctrl + Ruler Drag Linie pomocnicze obszaru kompozycji z Cmd/Ctrl + przeciąganiem z linijki Unlock Guides Odblokuj linie pomocnicze Make Guides Utwórz linie pomocnicze Release Guides Uwolnij linie pomocnicze @@ -729,6 +730,13 @@ Quest Outline Zadanie Coin Shine Moneta Boss Alert Boss + Status Effects Efekty statusu + Poison Tint Trucizna + Freeze Edge Mróz + Burn Aura Oparzenie + Stun Pulse Ogłuszenie + Stealth Fade Ukrycie + Shield Buff Tarcza Outlines and Rules Kontury i linie Hand-Drawn Rysowane odręcznie Gradient Finishes Wykończenia gradientowe @@ -2200,6 +2208,8 @@ digits Malayalam Malajalam Green Zielony Shifts the tints of global and spot colors; other colors stay. Przesuwa tinty kolorów globalnych i dodatkowych; pozostałe kolory bez zmian. Tint Tinta + Fill Tint Tinta wypełnienia + Stroke Tint Tinta obrysu Color Guide Options Opcje przewodnika kolorów Less Mniej Steps: Kroki: @@ -2566,6 +2576,7 @@ digits Malayalam Malajalam File Dimensions Wymiary pliku Transforms Przekształcenia Background Color: Kolor tła: + Guide Label: Etykieta linii pomocniczych: Show Center Mark Pokaż znacznik środka Show Cross Hairs Pokaż krzyż nitkowy Show Video Safe Areas Pokaż bezpieczne obszary wideo @@ -3627,6 +3638,12 @@ theme Appearance Wygląd Real-time Drawing and Editing Rysowanie i edycja w czasie rzeczywistym Render Threads (-1 = Automatic) Wątki renderowania (-1 = automatycznie) Reset Preferences Resetuj preferencje + Export Preferences… Eksportuj preferencje… + Import Preferences… Importuj preferencje… + Save the applied preferences to a JSON file Zapisz zastosowane preferencje w pliku JSON + Apply the preferences in a file Export Preferences saved Zastosuj preferencje z pliku zapisanego poleceniem Eksportuj preferencje + Export Preferences Eksportuj preferencje + Import Preferences Importuj preferencje Search Preferences Szukaj w preferencjach No settings found Nie znaleziono ustawień Scale Corners Skaluj narożniki @@ -3983,6 +4000,8 @@ font-technology Variable Zmienne Preferences Preferencje Previous Wstecz Restore every preference to its default (applied on OK) Przywróć domyślne wartości wszystkich preferencji (zastosowane po OK) + Reset all preferences to their defaults? Przywrócić domyślne wartości wszystkich preferencji? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Wartości domyślne zostaną zastosowane po kliknięciu OK w Preferencjach. Anuluj w tym oknie zachowuje bieżące preferencje. Smaller ↔ Larger Mniejszy ↔ większy Smart Guides (View → Smart Guides) Inteligentne linie pomocnicze (Widok → Inteligentne linie pomocnicze) Couldn't save recovery data: {e} Nie udało się zapisać danych odzyskiwania: {e} @@ -4212,6 +4231,7 @@ imageTrace Outline Kontur Stop Script Zatrzymaj skrypt Show External Script Warning Pokazuj ostrzeżenie o skryptach zewnętrznych A Script Is Running Skrypt jest uruchomiony + Script Alert Komunikat skryptu A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. Do not show this warning again Nie pokazuj więcej tego ostrzeżenia Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. @@ -4225,6 +4245,9 @@ imageTrace Outline Kontur @msg the script is too large to run skrypt jest zbyt duży, aby go uruchomić @msg a drag or an undo group is open; finish it before running a script otwarte jest przeciąganie lub grupa cofania; zakończ je przed uruchomieniem skryptu @msg the script left a document that cannot be kept skrypt pozostawił dokument, którego nie można zachować +@msg the script is no longer in the Scripts folder skryptu nie ma już w folderze Scripts + Some scripts were not listed Niektóre skrypty nie zostały wyświetlone + The Scripts folder cannot be read Nie można odczytać folderu Scripts @msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne @msg a failed command changed undo steps that could not be put back, so the script was stopped nieudane polecenie zmieniło kroki cofania, których nie udało się przywrócić, więc skrypt został zatrzymany @msg a recovery copy could not be written, so the script was not run nie udało się zapisać kopii odzyskiwania, więc skrypt nie został uruchomiony @@ -4408,6 +4431,7 @@ imageTrace Outline Kontur @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis musi mieć wartość "vertical", "horizontal" lub kąt w stopniach, nie `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" tło {other}: transparent, white, black lub kolor, np. "#ff8800" @msg bad color {v} nieprawidłowy kolor {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` to null, nazwa koloru warstwy lub #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio musi być liczbą od 0,1 do 10 @msg the Color Picker is not open Próbnik kolorów nie jest otwarty @msg the Simplify slider is not open Suwak Uprość nie jest otwarty @@ -4815,6 +4839,20 @@ imageTrace Outline Kontur @msg unknown overprints `{o}` (preserve, simulate or discard) nieznana wartość nadruków `{o}` (preserve, simulate lub discard) @msg unknown panel `{raw}` nieznany panel `{raw}` @msg unknown preference `{key}` nieznana preferencja `{key}` +@msg Preferences imported. Zaimportowano preferencje. +@msg not a preferences file: {e} to nie jest plik preferencji: {e} +@msg not a preferences file: no JSON object to nie jest plik preferencji: brak obiektu JSON +@msg not a preferences file (format `{format}`) to nie jest plik preferencji (format `{format}`) +@msg not a preferences file: no `format` to nie jest plik preferencji: brak `format` +@msg not a preferences file: no `version` to nie jest plik preferencji: brak `version` +@msg not a preferences file: no `prefs` to nie jest plik preferencji: brak `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) plik zapisano w nowszej wersji programu VectorCraft (wersja {v}) +@msg the file holds no preferences plik nie zawiera preferencji +@msg `{key}` names a folder, which preferences files leave out `{key}` wskazuje folder, a pliki preferencji nie zawierają folderów +@msg the file is larger than 1 MB plik jest większy niż 1 MB +@msg give `path` or `data` podaj `path` lub `data` +@msg `{key}` must be an object `{key}` musi być obiektem +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` działa samodzielnie, nie jako krok wsadu @msg unknown preset (one of {_1}) nieznane ustawienie (jedno z: {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) nieznane ustawienie `{name}` (high, medium, low lub zapisane: patrz flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) nieznane ustawienie `{name}` (patrz flattener.presets.list) @@ -5393,6 +5431,7 @@ file-filter Swatch libraries Biblioteki próbek file-filter Flattener presets Ustawienia spłaszczania file-filter PDF presets Ustawienia PDF file-filter Print presets Ustawienia drukowania +file-filter Preferences Preferencje file-filter Export presets Ustawienia eksportu file-filter SVG Compressed SVG skompresowany file-filter PDF-compatible .ai .ai zgodny z PDF @@ -5533,6 +5572,7 @@ mark-style Japanese Japońskie Preview (1 inch on the page) Podgląd (1 cal na stronie) Set as Default Ustaw jako domyślne out from a highlighted edge to place its dimension | od podświetlonej krawędzi na zewnątrz, aby umieścić jej wymiar | + two points, then move and click to place an aligned, horizontal or vertical dimension | dwa punkty, potem przesuń i kliknij, aby umieścić wymiar wyrównany, poziomy lub pionowy | cancels | Double-click the tool for options anuluje | Kliknij dwukrotnie narzędzie, aby wyświetlić opcje Angular Kątowy Away from the Line Z dala od linii @@ -5562,14 +5602,17 @@ mark-style Japanese Japońskie @msg Invalid drawing scale Nieprawidłowa skala rysunku @msg Invalid real scale Nieprawidłowa skala rzeczywista @msg Measured anchor no longer exists Mierzony punkt kontrolny już nie istnieje +@msg Invalid measured point Nieprawidłowy mierzony punkt @msg Measured segment no longer exists Mierzony odcinek już nie istnieje @msg Non-finite dimension Wymiar nie jest liczbą skończoną +@msg Only linear dimensions are horizontal or vertical Tylko wymiary liniowe są poziome lub pionowe @msg Scale Text Attributes: selected type has no scale to bake Skaluj atrybuty tekstu: wybrany tekst nie ma skali do zastosowania @msg Scale must be drawing:real, for example 1:10 Skala musi mieć postać rysunek:rzeczywistość, na przykład 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Współczynnik skali musi mieścić się między 1:1000000 a 1000000:1 @msg Second measured segment no longer exists Drugi mierzony odcinek już nie istnieje @msg Unknown dimension mode Nieznany tryb wymiaru @msg Unknown dimension option {k} Nieznana opcja wymiaru {k} +@msg Unknown dimension orientation Nieznana orientacja wymiaru @msg Unknown dimension style Nieznany styl wymiaru @msg Unknown unit Nieznana jednostka # Revolve cap description @@ -5938,6 +5981,12 @@ axis Y Axis Oś Y Flag Flaga Crosshair Celownik Checkpoint Punkt kontrolny + Inventory Icons Ikony ekwipunku + Sword Miecz + Shield Tarcza + Potion Mikstura + Key Klucz + Gem Klejnot Open Symbol Library Otwórz bibliotekę symboli Save Symbol Library Zapisz bibliotekę symboli Save Symbol Library… Zapisz bibliotekę symboli… @@ -6589,3 +6638,31 @@ breakText Glyphs Glify No Suggestions Brak sugestii Edit Custom Dictionary Edytuj słownik użytkownika Entry: Wpis: +# Script Console + Script Console Konsola skryptów + Clear Script Console Wyczyść konsolę skryptów + Copy Script Console Kopiuj konsolę skryptów + Copy All Kopiuj wszystko + Copy Selected Kopiuj zaznaczenie + Finished Zakończono + Ended with an error Zakończono z błędem + Out of fuel Wyczerpano limit instrukcji + Ended at a host limit Zakończono na limicie hosta + Ended at a limit Zakończono na limicie + Stopped Zatrzymano + Ended by an internal fault Zakończono z powodu błędu wewnętrznego + time unavailable czas niedostępny + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} najwolniejsze: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} wywołanie hosta|{n} wywołania hosta|{n} wywołań hosta +@plural {n} earlier line dropped|{n} earlier lines dropped {n} odrzucony wcześniejszy wiersz|{n} odrzucone wcześniejsze wiersze|{n} odrzuconych wcześniejszych wierszy +@plural {n} line cut|{n} lines cut {n} skrócony wiersz|{n} skrócone wiersze|{n} skróconych wierszy +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` muszą być numerami wierszy przechowywanych w konsoli, `first` przed `last` + +# Deferred plug-in effects + Refresh Deferred Effects Odśwież odroczone efekty + Deferred Effects Odroczone efekty +@msg no plug-in effect is deferred żaden efekt wtyczki nie jest odroczony +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Otwarto z {n} odroczonym efektem wtyczki. Efekt › Odśwież odroczone efekty go uruchamia.|Otwarto z {n} odroczonymi efektami wtyczek. Efekt › Odśwież odroczone efekty je uruchamia.|Otwarto z {n} odroczonymi efektami wtyczek. Efekt › Odśwież odroczone efekty je uruchamia. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b0d940693f..9ede5521a8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -275,6 +275,7 @@ antiAlias Sharp Nítido Average… Média… BLANK DOCUMENT PRESETS PREDEFINIDOS DE DOCUMENTO EM BRANCO Background Color: Cor do Plano de Fundo: + Guide Label: Rótulo das Guias: Show Center Mark Mostrar Marca Central Show Cross Hairs Mostrar Linhas Cruzadas Show Video Safe Areas Mostrar Áreas Seguras de Vídeo @@ -1617,6 +1618,7 @@ antiAlias Sharp Nítido Lock Grid Bloquear Grade Lock Guides Bloquear Guias Lock Guides by Default Bloquear Guias por Padrão + Artboard Guides with Cmd/Ctrl + Ruler Drag Guias de Prancheta com Cmd/Ctrl + Arrastar da Régua Lock Slices Bloquear Fatias Lock Station Point Bloquear Ponto de Estação Lossless (lossy WebP isn't available yet) Sem Perdas (WebP com perdas ainda não está disponível) @@ -2356,6 +2358,12 @@ digits Malayalam Malaiala Reset OpenType Features Redefinir Recursos OpenType Reset Panel Redefinir Painel Reset Preferences Redefinir Preferências + Export Preferences… Exportar Preferências… + Import Preferences… Importar Preferências… + Save the applied preferences to a JSON file Salvar as preferências aplicadas em um arquivo JSON + Apply the preferences in a file Export Preferences saved Aplicar as preferências de um arquivo salvo com Exportar Preferências + Export Preferences Exportar Preferências + Import Preferences Importar Preferências Search Preferences Pesquisar nas Preferências No settings found Nenhuma configuração encontrada Reset Profiles Redefinir Perfis @@ -2377,6 +2385,8 @@ digits Malayalam Malaiala Restore Restaurar Restore Recovered Documents Restaurar Documentos Recuperados Restore every preference to its default (applied on OK) Restaurar toda preferência ao padrão (aplicado em OK) + Reset all preferences to their defaults? Redefinir todas as preferências para o padrão? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Os padrões são aplicados quando você clica em OK em Preferências. Cancelar ali mantém suas preferências atuais. Restored documents open unsaved: save them to keep them. Os documentos restaurados abrem sem salvar: salve-os para mantê-los. Restrict printing, editing and other tasks Restringir impressão, edição e outras tarefas Reverse Front to Back Inverter da Frente para Trás @@ -2638,6 +2648,13 @@ digits Malayalam Malaiala Quest Outline Missão Coin Shine Moeda Boss Alert Chefe + Status Effects Efeitos de status + Poison Tint Veneno + Freeze Edge Congelamento + Burn Aura Queimadura + Stun Pulse Atordoamento + Stealth Fade Furtividade + Shield Buff Escudo Shape Forma Shape Builder Construtor de Formas Shape Builder Regions Regiões do Construtor de Formas @@ -3832,6 +3849,7 @@ axis Both Ambos @msg at this scale the drawing is {w} × {h} pt, more than the canvas holds: choose a smaller scale or fit it to the artboard nesta escala o desenho tem {w} × {h} pt, mais do que a tela comporta: escolha uma escala menor ou ajuste-o à prancheta @msg background {other}: transparent, white, black or a colour such as "#ff8800" plano de fundo {other}: transparent, white, black ou uma cor como "#ff8800" @msg bad color {v} cor inválida {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` é null, o nome de uma cor de camada ou #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio deve ser um número de 0,1 a 10 @msg bad colour `{hex}` (#rrggbb) cor inválida `{hex}` (#rrggbb) @msg bad page tree árvore de páginas inválida @@ -4229,6 +4247,20 @@ axis Both Ambos @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpressões desconhecidas `{o}` (preserve, simulate ou discard) @msg unknown panel `{raw}` painel desconhecido `{raw}` @msg unknown preference `{key}` preferência desconhecida `{key}` +@msg Preferences imported. Preferências importadas. +@msg not a preferences file: {e} não é um arquivo de preferências: {e} +@msg not a preferences file: no JSON object não é um arquivo de preferências: nenhum objeto JSON +@msg not a preferences file (format `{format}`) não é um arquivo de preferências (formato `{format}`) +@msg not a preferences file: no `format` não é um arquivo de preferências: falta `format` +@msg not a preferences file: no `version` não é um arquivo de preferências: falta `version` +@msg not a preferences file: no `prefs` não é um arquivo de preferências: falta `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) o arquivo foi salvo por uma versão mais recente do VectorCraft (versão {v}) +@msg the file holds no preferences o arquivo não contém preferências +@msg `{key}` names a folder, which preferences files leave out `{key}` indica uma pasta, e os arquivos de preferências não incluem pastas +@msg the file is larger than 1 MB o arquivo tem mais de 1 MB +@msg give `path` or `data` informe `path` ou `data` +@msg `{key}` must be an object `{key}` deve ser um objeto +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` é executado sozinho, não como etapa de um lote @msg unknown preset (one of {_1}) predefinição desconhecida (uma de {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) predefinição desconhecida `{name}` (high, medium, low ou uma salva: veja flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) predefinição desconhecida `{name}` (veja flattener.presets.list) @@ -4994,6 +5026,8 @@ axis Both Ambos Text Wrap Options Opções de Quebra de Texto Tile Full Pages Dividir em Páginas Inteiras Tint Tom + Fill Tint Tom de Preenchimento + Stroke Tint Tom do Traçado Tip extends past the end point A ponta se estende além do ponto final Tip on the end point Ponta no ponto final Toolbar: Add Tool Barra de Ferramentas: Adicionar Ferramenta @@ -5041,6 +5075,7 @@ axis Both Ambos Stop Script Parar script Show External Script Warning Mostrar aviso de scripts externos A Script Is Running Um script está em execução + Script Alert Alerta do script A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. Do not show this warning again Não mostrar este aviso novamente Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. @@ -5054,6 +5089,9 @@ axis Both Ambos @msg the script is too large to run o script é grande demais para ser executado @msg a drag or an undo group is open; finish it before running a script há um arraste ou um grupo de desfazer aberto; conclua-o antes de executar um script @msg the script left a document that cannot be kept o script deixou um documento que não pode ser mantido +@msg the script is no longer in the Scripts folder o script não está mais na pasta Scripts + Some scripts were not listed Alguns scripts não foram listados + The Scripts folder cannot be read Não é possível ler a pasta Scripts @msg the script's run is no longer available a execução do script não está mais disponível @msg a failed command changed undo steps that could not be put back, so the script was stopped um comando que falhou alterou etapas de desfazer que não puderam ser restauradas, então o script foi interrompido @msg a recovery copy could not be written, so the script was not run não foi possível gravar uma cópia de recuperação, portanto o script não foi executado @@ -5436,6 +5474,7 @@ file-filter Swatch libraries Bibliotecas de amostras file-filter Flattener presets Predefinidos de achatamento file-filter PDF presets Predefinidos de PDF file-filter Print presets Predefinidos de impressão +file-filter Preferences Preferências file-filter Export presets Predefinições de exportação file-filter SVG Compressed SVG Compactado file-filter PDF-compatible .ai .ai compatível com PDF @@ -5642,14 +5681,17 @@ mark-style Japanese Japonesas @msg Invalid drawing scale Escala de desenho inválida @msg Invalid real scale Escala real inválida @msg Measured anchor no longer exists O ponto de ancoragem medido não existe mais +@msg Invalid measured point Ponto medido inválido @msg Measured segment no longer exists O segmento medido não existe mais @msg Non-finite dimension Cota não finita +@msg Only linear dimensions are horizontal or vertical Somente cotas lineares são horizontais ou verticais @msg Scale Text Attributes: selected type has no scale to bake Dimensionar Atributos de Texto: o texto selecionado não tem escala para aplicar @msg Scale must be drawing:real, for example 1:10 A escala deve ser desenho:real, por exemplo 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 A proporção da escala deve estar entre 1:1000000 e 1000000:1 @msg Second measured segment no longer exists O segundo segmento medido não existe mais @msg Unknown dimension mode Modo de cota desconhecido @msg Unknown dimension option {k} Opção de cota desconhecida {k} +@msg Unknown dimension orientation Orientação de cota desconhecida @msg the Color Picker is not open o Seletor de Cores não está aberto @msg the Simplify slider is not open o controle deslizante Simplificar não está aberto @msg the Smooth slider is not open o controle deslizante Suavizar não está aberto @@ -5669,6 +5711,7 @@ mark-style Japanese Japonesas This system has no screen color sampler Este sistema não tem coletor de cores da tela cancels | Double-click the tool for options cancela | Clique duas vezes na ferramenta para ver as opções out from a highlighted edge to place its dimension | para fora a partir de uma borda destacada para posicionar a cota | + two points, then move and click to place an aligned, horizontal or vertical dimension | em dois pontos, depois mova e clique para posicionar uma cota alinhada, horizontal ou vertical | Color Panel Options Opções do Painel Cor @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve ser grayscale, rgb, hsb, cmyk ou websafe @msg the image can't be read as a texture a imagem não pode ser lida como textura @@ -5999,6 +6042,12 @@ axis Y Axis Eixo Y Flag Bandeira Crosshair Mira Checkpoint Ponto de verificação + Inventory Icons Ícones de inventário + Sword Espada + Shield Escudo + Potion Poção + Key Chave + Gem Gema Open Symbol Library Abrir Biblioteca de Símbolos Save Symbol Library Salvar Biblioteca de Símbolos Save Symbol Library… Salvar Biblioteca de Símbolos… @@ -6806,3 +6855,31 @@ swatch Yellow Green Verde-amarelado No Suggestions Nenhuma Sugestão Edit Custom Dictionary Editar Dicionário Personalizado Entry: Entrada: +# Script Console + Script Console Console de scripts + Clear Script Console Limpar console de scripts + Copy Script Console Copiar console de scripts + Copy All Copiar tudo + Copy Selected Copiar seleção + Finished Concluído + Ended with an error Encerrado com um erro + Out of fuel Limite de instruções esgotado + Ended at a host limit Encerrado em um limite do host + Ended at a limit Encerrado em um limite + Stopped Interrompido + Ended by an internal fault Encerrado por um erro interno + time unavailable tempo indisponível + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} mais lentos: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} chamada ao host|{n} chamadas ao host +@plural {n} earlier line dropped|{n} earlier lines dropped {n} linha anterior descartada|{n} linhas anteriores descartadas +@plural {n} line cut|{n} lines cut {n} linha cortada|{n} linhas cortadas +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` e `last` devem ser números de linhas que o console mantém, `first` antes de `last` + +# Deferred plug-in effects + Refresh Deferred Effects Atualizar Efeitos Adiados + Deferred Effects Efeitos Adiados +@msg no plug-in effect is deferred nenhum efeito de plug-in está adiado +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Aberto com {n} efeito de plug-in adiado. Efeito › Atualizar Efeitos Adiados o executa.|Aberto com {n} efeitos de plug-in adiados. Efeito › Atualizar Efeitos Adiados os executa. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a00325e8b8..50eb9e969d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -287,6 +287,7 @@ font-technology Variable Вариативные Average… Усреднить… Axis: Ось: Background Color: Цвет фона: + Guide Label: Метка направляющих: Show Center Mark Показать центральную метку Show Cross Hairs Показать перекрестие Show Video Safe Areas Показать безопасные зоны видео @@ -1275,6 +1276,7 @@ file-filter Swatch libraries Библиотеки образцов file-filter Flattener presets Наборы объединения file-filter PDF presets Наборы PDF file-filter Print presets Наборы печати +file-filter Preferences Настройки file-filter Export presets Наборы настроек экспорта file-filter SVG Compressed Сжатый SVG file-filter PDF-compatible .ai .ai, совместимый с PDF @@ -1922,6 +1924,7 @@ file-filter Templates Шаблоны Lock Grid Заблокировать сетку Lock Guides Заблокировать направляющие Lock Guides by Default Блокировать направляющие по умолчанию + Artboard Guides with Cmd/Ctrl + Ruler Drag Направляющие монтажной области с Cmd/Ctrl + перетаскиванием с линейки Lock Others Заблокировать остальные Lock Slices Заблокировать фрагменты Lock Station Point Заблокировать точку стояния @@ -2847,6 +2850,12 @@ digits Malayalam Малаялам Reset OpenType Features Сбросить функции OpenType Reset Panel Сбросить панель Reset Preferences Сбросить настройки + Export Preferences… Экспортировать настройки… + Import Preferences… Импортировать настройки… + Save the applied preferences to a JSON file Сохранить применённые настройки в файл JSON + Apply the preferences in a file Export Preferences saved Применить настройки из файла, сохранённого командой «Экспортировать настройки» + Export Preferences Экспортировать настройки + Import Preferences Импортировать настройки Search Preferences Поиск в настройках No settings found Настройки не найдены Reset Profiles Сбросить профили @@ -2870,6 +2879,8 @@ digits Malayalam Малаялам Responsive Адаптивный Restore Восстановить Restore every preference to its default (applied on OK) Восстановить все настройки по умолчанию (применяется при нажатии ОК) + Reset all preferences to their defaults? Сбросить все настройки до значений по умолчанию? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Значения по умолчанию применяются, когда вы нажимаете ОК в окне «Настройки». Отмена там сохраняет текущие настройки. Restore Recovered Documents Восстановить восстановленные документы Restored documents open unsaved: save them to keep them. Восстановленные документы открываются несохранёнными: сохраните их, чтобы оставить. Restrict printing, editing and other tasks Ограничить печать, редактирование и другие задачи @@ -3177,6 +3188,13 @@ digits Malayalam Малаялам Quest Outline Квест Coin Shine Монета Boss Alert Босс + Status Effects Эффекты статуса + Poison Tint Яд + Freeze Edge Заморозка + Burn Aura Ожог + Stun Pulse Оглушение + Stealth Fade Скрытность + Shield Buff Щит Shape Фигура Shape Builder Создание фигур Shape Builder Regions Области создания фигур @@ -3595,6 +3613,8 @@ digits Malayalam Малаялам Tiles are numbered across, then down; leave the range empty for every tile. Плитки нумеруются слева направо, затем вниз; оставьте диапазон пустым для всех плиток. Copies per Sheet (as many as fit, in a grid) Копий на лист (сколько поместится, сеткой) Tint Оттенок + Fill Tint Оттенок заливки + Stroke Tint Оттенок обводки Tip extends past the end point Кончик выходит за конечную точку Tip on the end point Кончик на конечной точке Title Case Как в заголовке @@ -4115,6 +4135,7 @@ axis Both Оба Stop Script Остановить скрипт Show External Script Warning Показывать предупреждение о внешних скриптах A Script Is Running Выполняется скрипт + Script Alert Сообщение скрипта A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. Do not show this warning again Больше не показывать это предупреждение Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. @@ -4128,6 +4149,9 @@ axis Both Оба @msg the script is too large to run скрипт слишком велик для выполнения @msg a drag or an undo group is open; finish it before running a script открыто перетаскивание или группа отмены; завершите их перед запуском скрипта @msg the script left a document that cannot be kept скрипт оставил документ, который нельзя сохранить +@msg the script is no longer in the Scripts folder скрипт больше не находится в папке Scripts + Some scripts were not listed Некоторые сценарии не показаны + The Scripts folder cannot be read Не удалось прочитать папку Scripts @msg the script's run is no longer available выполнение скрипта больше недоступно @msg a failed command changed undo steps that could not be put back, so the script was stopped неудавшаяся команда изменила шаги отмены, которые не удалось восстановить, поэтому скрипт остановлен @msg a recovery copy could not be written, so the script was not run не удалось записать копию для восстановления, поэтому скрипт не выполнен @@ -4312,6 +4336,7 @@ axis Both Оба @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis должно быть "vertical", "horizontal" или углом в градусах, а не `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" фон {other}: transparent, white, black или цвет, например "#ff8800" @msg bad color {v} недопустимый цвет {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` должен быть null, именем цвета слоя или #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio должно быть числом от 0,1 до 10 @msg the Color Picker is not open палитра цветов не открыта @msg the Simplify slider is not open ползунок «Упростить» не открыт @@ -4717,6 +4742,20 @@ axis Both Оба @msg unknown overprints `{o}` (preserve, simulate or discard) неизвестные наложения `{o}` (preserve, simulate или discard) @msg unknown panel `{raw}` неизвестная панель `{raw}` @msg unknown preference `{key}` неизвестная настройка `{key}` +@msg Preferences imported. Настройки импортированы. +@msg not a preferences file: {e} не является файлом настроек: {e} +@msg not a preferences file: no JSON object не является файлом настроек: нет объекта JSON +@msg not a preferences file (format `{format}`) не является файлом настроек (формат `{format}`) +@msg not a preferences file: no `format` не является файлом настроек: нет `format` +@msg not a preferences file: no `version` не является файлом настроек: нет `version` +@msg not a preferences file: no `prefs` не является файлом настроек: нет `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) файл сохранён более новой версией VectorCraft (версия {v}) +@msg the file holds no preferences файл не содержит настроек +@msg `{key}` names a folder, which preferences files leave out `{key}` указывает папку, а файлы настроек не содержат папок +@msg the file is larger than 1 MB файл больше 1 МБ +@msg give `path` or `data` укажите `path` или `data` +@msg `{key}` must be an object `{key}` должен быть объектом +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` выполняется отдельно, а не как шаг пакета @msg unknown preset (one of {_1}) неизвестный набор (один из: {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) неизвестный набор `{name}` (high, medium, low или сохранённый: см. flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) неизвестный набор `{name}` (см. flattener.presets.list) @@ -5284,6 +5323,7 @@ lighting Light Свет Preview (1 inch on the page) Просмотр (1 дюйм на странице) Set as Default Установить по умолчанию out from a highlighted edge to place its dimension | наружу от подсвеченного края, чтобы разместить его размер | + two points, then move and click to place an aligned, horizontal or vertical dimension | по двум точкам, затем переместите и щёлкните, чтобы разместить выровненный, горизонтальный или вертикальный размер | cancels | Double-click the tool for options отменяет | Двойной щелчок по инструменту открывает параметры Linear Линейный Angular Угловой @@ -5316,14 +5356,17 @@ lighting Light Свет @msg Invalid drawing scale Недопустимый масштаб чертежа @msg Invalid real scale Недопустимый реальный масштаб @msg Measured anchor no longer exists Измеряемая опорная точка больше не существует +@msg Invalid measured point Недопустимая измеряемая точка @msg Measured segment no longer exists Измеряемый сегмент больше не существует @msg Non-finite dimension Размер не является конечным числом +@msg Only linear dimensions are horizontal or vertical Только линейные размеры бывают горизонтальными или вертикальными @msg Scale Text Attributes: selected type has no scale to bake Масштабировать атрибуты текста: у выбранного текста нет масштаба для применения @msg Scale must be drawing:real, for example 1:10 Масштаб должен быть в виде чертёж:реальность, например 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Соотношение масштаба должно быть от 1:1000000 до 1000000:1 @msg Second measured segment no longer exists Второй измеряемый сегмент больше не существует @msg Unknown dimension mode Неизвестный режим размера @msg Unknown dimension option {k} Неизвестный параметр размера {k} +@msg Unknown dimension orientation Неизвестная ориентация размера @msg Unknown dimension style Неизвестный стиль размера @msg Unknown unit Неизвестная единица # Revolve cap description @@ -5695,6 +5738,12 @@ axis Y Axis Ось Y Flag Флаг Crosshair Прицел Checkpoint Контрольная точка + Inventory Icons Иконки инвентаря + Sword Меч + Shield Щит + Potion Зелье + Key Ключ + Gem Самоцвет Open Symbol Library Открыть библиотеку символов Save Symbol Library Сохранить библиотеку символов Save Symbol Library… Сохранить библиотеку символов… @@ -6822,3 +6871,31 @@ shape Open Открытый No Suggestions Нет вариантов Edit Custom Dictionary Редактировать пользовательский словарь Entry: Запись: +# Script Console + Script Console Консоль скриптов + Clear Script Console Очистить консоль скриптов + Copy Script Console Копировать консоль скриптов + Copy All Копировать всё + Copy Selected Копировать выделенное + Finished Завершено + Ended with an error Завершено с ошибкой + Out of fuel Исчерпан лимит инструкций + Ended at a host limit Завершено на лимите хоста + Ended at a limit Завершено на лимите + Stopped Остановлено + Ended by an internal fault Завершено из-за внутренней ошибки + time unavailable время недоступно + {ms} ms {ms} мс + {time}, {calls} {time}, {calls} + slowest: {commands} самые медленные: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} вызов хоста|{n} вызова хоста|{n} вызовов хоста +@plural {n} earlier line dropped|{n} earlier lines dropped {n} прежняя строка отброшена|{n} прежние строки отброшены|{n} прежних строк отброшено +@plural {n} line cut|{n} lines cut {n} строка обрезана|{n} строки обрезаны|{n} строк обрезано +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` и `last` должны быть номерами строк, которые хранит консоль, причём `first` не позже `last` + +# Deferred plug-in effects + Refresh Deferred Effects Обновить отложенные эффекты + Deferred Effects Отложенные эффекты +@msg no plug-in effect is deferred нет отложенных эффектов модулей +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Открыто с {n} отложенным эффектом модуля. Эффект › Обновить отложенные эффекты выполнит его.|Открыто с {n} отложенными эффектами модулей. Эффект › Обновить отложенные эффекты выполнит их.|Открыто с {n} отложенными эффектами модулей. Эффект › Обновить отложенные эффекты выполнит их. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f2b24e7d08..60324bb91e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -278,6 +278,7 @@ font-technology Variable Variabla Average… Medelvärde… Axis: Axel: Background Color: Bakgrundsfärg: + Guide Label: Stödlinjeetikett: Show Center Mark Visa mittmarkering Show Cross Hairs Visa hårkors Show Video Safe Areas Visa videosäkra områden @@ -1837,6 +1838,7 @@ font-technology Variable Variabla Lock Grid Lås rutnät Lock Guides Lås stödlinjer Lock Guides by Default Lås stödlinjer som standard + Artboard Guides with Cmd/Ctrl + Ruler Drag Stödlinjer för rityta med Cmd/Ctrl + dra från linjal Lock Others Lås övriga Lock Slices Lås skivor Lock Station Point Lås betraktarpunkt @@ -2755,6 +2757,12 @@ digits Malayalam Malayalam Reset OpenType Features Återställ OpenType-funktioner Reset Panel Återställ panel Reset Preferences Återställ inställningar + Export Preferences… Exportera inställningar… + Import Preferences… Importera inställningar… + Save the applied preferences to a JSON file Spara de tillämpade inställningarna i en JSON-fil + Apply the preferences in a file Export Preferences saved Tillämpa inställningarna i en fil som Exportera inställningar har sparat + Export Preferences Exportera inställningar + Import Preferences Importera inställningar Search Preferences Sök i inställningar No settings found Inga inställningar hittades Reset Profiles Återställ profiler @@ -2777,6 +2785,8 @@ digits Malayalam Malayalam Responsive Responsiv Restore Återställ Restore every preference to its default (applied on OK) Återställ alla inställningar till standard (verkställs vid OK) + Reset all preferences to their defaults? Återställa alla inställningar till standard? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Standardvärdena verkställs när du klickar på OK i Inställningar. Avbryt där behåller dina nuvarande inställningar. Restore Recovered Documents Återställ återskapade dokument Restored documents open unsaved: save them to keep them. Återställda dokument öppnas osparade: spara dem för att behålla dem. Restrict printing, editing and other tasks Begränsa utskrift, redigering och andra åtgärder @@ -3070,6 +3080,13 @@ digits Malayalam Malayalam Quest Outline Uppdrag Coin Shine Mynt Boss Alert Boss + Status Effects Statuseffekter + Poison Tint Gift + Freeze Edge Frost + Burn Aura Bränna + Stun Pulse Bedövning + Stealth Fade Smyga + Shield Buff Sköld Shape Form Shape Builder Formbyggare Shape Builder Regions Formbyggarområden @@ -3486,6 +3503,8 @@ digits Malayalam Malayalam Tiles are numbered across, then down; leave the range empty for every tile. Rutorna numreras från vänster till höger och sedan nedåt. Lämna omfånget tomt för att få med alla rutor. Copies per Sheet (as many as fit, in a grid) Kopior per ark (så många som får plats, i ett rutnät) Tint Färgton + Fill Tint Fyllnadsfärgton + Stroke Tint Konturfärgton Tip extends past the end point Spetsen sträcker sig förbi slutpunkten Tip on the end point Spetsen på slutpunkten Title Case Inledande versaler @@ -3989,6 +4008,7 @@ axis Both Båda Stop Script Stoppa skript Show External Script Warning Visa varning för externa skript A Script Is Running Ett skript körs + Script Alert Skriptmeddelande A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. Do not show this warning again Visa inte den här varningen igen Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. @@ -4002,6 +4022,9 @@ axis Both Båda @msg the script is too large to run skriptet är för stort för att köras @msg a drag or an undo group is open; finish it before running a script en dragning eller ångragrupp är öppen; avsluta den innan du kör ett skript @msg the script left a document that cannot be kept skriptet lämnade ett dokument som inte kan behållas +@msg the script is no longer in the Scripts folder skriptet finns inte längre i mappen Scripts + Some scripts were not listed Vissa skript visas inte i listan + The Scripts folder cannot be read Mappen Scripts kan inte läsas @msg the script's run is no longer available skriptets körning är inte längre tillgänglig @msg a failed command changed undo steps that could not be put back, so the script was stopped ett misslyckat kommando ändrade ångrasteg som inte kunde återställas, så skriptet stoppades @msg a recovery copy could not be written, so the script was not run en återställningskopia kunde inte skrivas, så skriptet kördes inte @@ -4185,6 +4208,7 @@ axis Both Båda @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis måste vara "vertical", "horizontal" eller en vinkel i grader, inte `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black eller en färg som "#ff8800" @msg bad color {v} ogiltig färg {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` är null, namnet på en lagerfärg eller #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio måste vara ett tal från 0,1 till 10 @msg bad colour `{hex}` (#rrggbb) ogiltig färg `{hex}` (#rrggbb) @msg bad page tree ogiltigt sidträd @@ -4579,6 +4603,20 @@ axis Both Båda @msg unknown overprints `{o}` (preserve, simulate or discard) okänt värde för övertryck `{o}` (preserve, simulate eller discard) @msg unknown panel `{raw}` okänd panel `{raw}` @msg unknown preference `{key}` okänd inställning `{key}` +@msg Preferences imported. Inställningarna har importerats. +@msg not a preferences file: {e} inte en inställningsfil: {e} +@msg not a preferences file: no JSON object inte en inställningsfil: inget JSON-objekt +@msg not a preferences file (format `{format}`) inte en inställningsfil (format `{format}`) +@msg not a preferences file: no `format` inte en inställningsfil: inget `format` +@msg not a preferences file: no `version` inte en inställningsfil: ingen `version` +@msg not a preferences file: no `prefs` inte en inställningsfil: ingen `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) filen sparades av en nyare version av VectorCraft (version {v}) +@msg the file holds no preferences filen innehåller inga inställningar +@msg `{key}` names a folder, which preferences files leave out `{key}` anger en mapp, och inställningsfiler innehåller inga mappar +@msg the file is larger than 1 MB filen är större än 1 MB +@msg give `path` or `data` ange `path` eller `data` +@msg `{key}` must be an object `{key}` måste vara ett objekt +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` körs för sig, inte som ett steg i en batch @msg unknown preset (one of {_1}) okänd förinställning (en av {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) okänd förinställning `{name}` (high, medium, low eller en sparad: se flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) okänd förinställning `{name}` (se flattener.presets.list) @@ -5527,6 +5565,7 @@ file-filter Flattener presets Förinställningar för plattning file-filter PDF presets PDF-förinställningar file-filter PDF-compatible .ai PDF-kompatibel .ai file-filter Print presets Utskriftsförinställningar +file-filter Preferences Inställningar file-filter Export presets Exportförinställningar file-filter SVG Compressed SVG komprimerad file-filter Swatch libraries Färgrutebibliotek @@ -5573,6 +5612,7 @@ theme Appearance Utseende 3d Light Ljus cancels | Double-click the tool for options avbryter | Dubbelklicka på verktyget för alternativ out from a highlighted edge to place its dimension | utåt från en framhävd kant för att placera dess mått | + two points, then move and click to place an aligned, horizontal or vertical dimension | på två punkter, flytta sedan och klicka för att placera ett justerat, vågrätt eller lodrätt mått | A legacy .ai file holds one artboard: each artboard you check is saved as a separate file. En äldre .ai-fil rymmer en rityta: varje rityta du markerar sparas som en separat fil. Arrange Intertwine Area Ordna sammanflätningsområde Batch… Batch… @@ -5669,14 +5709,17 @@ theme Appearance Utseende @msg Invalid drawing scale Ogiltig ritningsskala @msg Invalid real scale Ogiltig verklig skala @msg Measured anchor no longer exists Den mätta ankarpunkten finns inte längre +@msg Invalid measured point Ogiltig mätt punkt @msg Measured segment no longer exists Det mätta segmentet finns inte längre @msg Non-finite dimension Måttet är inte ett ändligt tal +@msg Only linear dimensions are horizontal or vertical Endast linjära mått är vågräta eller lodräta @msg Scale Text Attributes: selected type has no scale to bake Skala textattribut: det valda texten har ingen skalning att tillämpa @msg Scale must be drawing:real, for example 1:10 Skalan måste anges som ritning:verklighet, till exempel 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Skalförhållandet måste ligga mellan 1:1000000 och 1000000:1 @msg Second measured segment no longer exists Det andra mätta segmentet finns inte längre @msg Unknown dimension mode Okänt måttläge @msg Unknown dimension option {k} Okänt måttalternativ {k} +@msg Unknown dimension orientation Okänd måttriktning @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` måste vara grayscale, rgb, hsb, cmyk eller websafe @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @@ -6107,6 +6150,12 @@ axis Y Axis Y-axel Flag Flagga Crosshair Hårkors Checkpoint Kontrollpunkt + Inventory Icons Inventarieikoner + Sword Svärd + Shield Sköld + Potion Dryck + Key Nyckel + Gem Ädelsten Open Symbol Library Öppna symbolbibliotek Save Symbol Library Spara symbolbibliotek Save Symbol Library… Spara symbolbibliotek… @@ -8218,3 +8267,31 @@ digits Hindi Hindi No Suggestions Inga förslag Edit Custom Dictionary Redigera egen ordlista Entry: Post: +# Script Console + Script Console Skriptkonsol + Clear Script Console Rensa skriptkonsolen + Copy Script Console Kopiera skriptkonsolen + Copy All Kopiera allt + Copy Selected Kopiera markerade + Finished Klar + Ended with an error Avslutades med ett fel + Out of fuel Instruktionsgränsen nåddes + Ended at a host limit Avslutades vid en värdgräns + Ended at a limit Avslutades vid en gräns + Stopped Stoppad + Ended by an internal fault Avslutades av ett internt fel + time unavailable tid ej tillgänglig + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} långsammast: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} värdanrop|{n} värdanrop +@plural {n} earlier line dropped|{n} earlier lines dropped {n} tidigare rad borttagen|{n} tidigare rader borttagna +@plural {n} line cut|{n} lines cut {n} rad avkortad|{n} rader avkortade +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` och `last` måste vara nummer på rader som konsolen har kvar, `first` före `last` + +# Deferred plug-in effects + Refresh Deferred Effects Uppdatera uppskjutna effekter + Deferred Effects Uppskjutna effekter +@msg no plug-in effect is deferred ingen plugineffekt är uppskjuten +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Öppnades med {n} uppskjuten plugineffekt. Effekt › Uppdatera uppskjutna effekter kör den.|Öppnades med {n} uppskjutna plugineffekter. Effekt › Uppdatera uppskjutna effekter kör dem. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index fd842dd342..79cbd7a648 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -227,6 +227,24 @@ fn each_language_counts_with_its_plural_rule() { } } +/// The Script Console's counted phrases have a row in every complete catalog, and a count picks +/// the language's own form. +#[test] +fn script_console_counts_take_each_language_s_form() { + const COUNTED: [(&str, &str); 3] = + [("{n} host call", "{n} host calls"), ("{n} earlier line dropped", "{n} earlier lines dropped"), ("{n} line cut", "{n} lines cut")]; + for l in LANGUAGES.iter().filter(|l| l.complete_menus) { + for (one, other) in COUNTED { + assert!(l.catalog().plural(one, other, 0).is_some(), "{} is missing the row for {other}", l.code); + } + } + assert_eq!([1, 2].map(|n| trn(de(), n, COUNTED[0].0, COUNTED[0].1)), ["1 Host-Aufruf", "2 Host-Aufrufe"]); + let ru = Lang::from_code("ru").expect("registered"); + assert_eq!([1, 3, 5].map(|n| trn(ru, n, COUNTED[2].0, COUNTED[2].1)), ["1 строка обрезана", "3 строки обрезаны", "5 строк обрезано"]); + let fr = Lang::from_code("fr").expect("registered"); + assert_eq!([0, 1].map(|n| trn(fr, n, COUNTED[1].0, COUNTED[1].1)), ["0 ligne antérieure supprimée", "1 ligne antérieure supprimée"]); +} + #[test] fn candidates_walk_from_specific_to_general() { assert_eq!(candidates("pt_BR.UTF-8"), ["pt-br", "pt"]); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 76d73994b5..496dba8cf5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -274,6 +274,7 @@ font-technology Variable Değişken Average… Ortalama… Axis: Eksen: Background Color: Arka Plan Rengi: + Guide Label: Kılavuz Etiketi: Show Center Mark Merkez İşaretini Göster Show Cross Hairs Artı Çizgilerini Göster Show Video Safe Areas Video Güvenli Alanlarını Göster @@ -1730,6 +1731,7 @@ font-technology Variable Değişken Lock Grid Izgarayı Kilitle Lock Guides Kilit Kılavuzları Lock Guides by Default Kılavuzları Varsayılan Olarak Kilitle + Artboard Guides with Cmd/Ctrl + Ruler Drag Cmd/Ctrl + Cetvelden Sürükleme ile Çalışma Yüzeyi Kılavuzları Lock Others Diğerlerini Kilitle Lock Slices Dilimleri Kilitle Lock Station Point Kilit İstasyon Noktası @@ -2624,6 +2626,12 @@ digits Malayalam Malayalam Reset OpenType Features OpenType Özelliklerini Sıfırla Reset Panel Paneli Sıfırla Reset Preferences Tercihleri Sıfırla + Export Preferences… Tercihleri Dışa Aktar… + Import Preferences… Tercihleri İçe Aktar… + Save the applied preferences to a JSON file Uygulanan tercihleri bir JSON dosyasına kaydet + Apply the preferences in a file Export Preferences saved Tercihleri Dışa Aktar ile kaydedilen bir dosyadaki tercihleri uygula + Export Preferences Tercihleri Dışa Aktar + Import Preferences Tercihleri İçe Aktar Search Preferences Tercihlerde Ara No settings found Ayar bulunamadı Reset Profiles Profilleri Sıfırla @@ -2646,6 +2654,8 @@ digits Malayalam Malayalam Responsive duyarlı Restore Geri yükle Restore every preference to its default (applied on OK) Her tercihi varsayılana geri yükleyin (Tamam'a uygulanır) + Reset all preferences to their defaults? Tüm tercihler varsayılanlarına sıfırlansın mı? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Varsayılanlar, Tercihler'de Tamam'a tıkladığınızda uygulanır. Oradaki İptal, mevcut tercihlerinizi korur. Restore Recovered Documents Kurtarılan Belgeleri Geri Yükle Restored documents open unsaved: save them to keep them. Geri yüklenen belgeler kaydedilmeden açılır: saklamak için kaydedin. Restrict printing, editing and other tasks Yazdırmayı, düzenlemeyi ve diğer görevleri kısıtlayın @@ -2974,6 +2984,13 @@ digits Malayalam Malayalam Quest Outline Görev Coin Shine Jeton Boss Alert Boss + Status Effects Durum Etkileri + Poison Tint Zehir + Freeze Edge Donma + Burn Aura Yanma + Stun Pulse Sersemletme + Stealth Fade Gizlilik + Shield Buff Kalkan Shape Şekil Shape Builder Şekil Oluşturucu Shape Builder Regions Şekil Oluşturucu Bölgeleri @@ -3375,6 +3392,8 @@ digits Malayalam Malayalam tile {number} kiremit {number} Tiles are numbered across, then down; leave the range empty for every tile. Fayanslar önce baştan sonra aşağı doğru numaralandırılır; aralığı her döşeme için boş bırakın. Tint Renk tonu + Fill Tint Dolgu Renk Tonu + Stroke Tint Kontur Renk Tonu Tip extends past the end point İpucu bitiş noktasının ötesine uzanıyor Tip on the end point Bitiş noktasına dair ipucu Title Case Başlık Durumu @@ -3871,6 +3890,7 @@ axis Both Her İkisi Stop Script Betiği Durdur Show External Script Warning Harici Betik Uyarısını Göster A Script Is Running Bir Betik Çalışıyor + Script Alert Betik Uyarısı A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. Do not show this warning again Bu uyarıyı bir daha gösterme Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın. @@ -3884,6 +3904,9 @@ axis Both Her İkisi @msg the script is too large to run betik çalıştırılamayacak kadar büyük @msg a drag or an undo group is open; finish it before running a script bir sürükleme veya geri alma grubu açık; betiği çalıştırmadan önce tamamlayın @msg the script left a document that cannot be kept betik, saklanamayan bir belge bıraktı +@msg the script is no longer in the Scripts folder betik artık Scripts klasöründe değil + Some scripts were not listed Bazı komut dosyaları listelenmedi + The Scripts folder cannot be read Scripts klasörü okunamıyor @msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor @msg a failed command changed undo steps that could not be put back, so the script was stopped başarısız bir komut geri yüklenemeyen geri alma adımlarını değiştirdi, bu yüzden betik durduruldu @msg a recovery copy could not be written, so the script was not run kurtarma kopyası yazılamadı, bu nedenle betik çalıştırılmadı @@ -4041,6 +4064,7 @@ axis Both Her İkisi @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis "vertical", "horizontal" veya derece cinsinden bir açı olmalıdır, `{v}` değil @msg background {other}: transparent, white, black or a colour such as "#ff8800" arka plan {other}: şeffaf, beyaz, siyah veya "#ff8800" gibi bir renk @msg bad color {v} kötü renk {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` null, bir katman renginin adı veya #rrggbb olur @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio 0,1 ile 10 arasında bir sayı olmalıdır @msg the Color Picker is not open Renk Seçici açık değil @msg the screen color sampler is already open ekran rengi örnekleyici zaten açık @@ -4428,6 +4452,20 @@ axis Both Her İkisi @msg unknown overprints `{o}` (preserve, simulate or discard) bilinmeyen üst baskılar `{o}` (koru, benzet veya at) @msg unknown panel `{raw}` bilinmeyen panel `{raw}` @msg unknown preference `{key}` bilinmeyen tercih `{key}` +@msg Preferences imported. Tercihler içe aktarıldı. +@msg not a preferences file: {e} tercih dosyası değil: {e} +@msg not a preferences file: no JSON object tercih dosyası değil: JSON nesnesi yok +@msg not a preferences file (format `{format}`) tercih dosyası değil (biçim `{format}`) +@msg not a preferences file: no `format` tercih dosyası değil: `format` yok +@msg not a preferences file: no `version` tercih dosyası değil: `version` yok +@msg not a preferences file: no `prefs` tercih dosyası değil: `prefs` yok +@msg the file was saved by a newer version of VectorCraft (version {v}) dosya VectorCraft'ın daha yeni bir sürümüyle kaydedilmiş (sürüm {v}) +@msg the file holds no preferences dosyada tercih yok +@msg `{key}` names a folder, which preferences files leave out `{key}` bir klasör belirtir ve tercih dosyaları klasör içermez +@msg the file is larger than 1 MB dosya 1 MB'tan büyük +@msg give `path` or `data` `path` veya `data` verin +@msg `{key}` must be an object `{key}` bir nesne olmalıdır +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` tek başına çalışır, toplu iş adımı olarak değil @msg unknown preset (one of {_1}) bilinmeyen ön ayar ({_1}'den biri) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) bilinmeyen ön ayar `{name}` (yüksek, orta, düşük veya kaydedilmiş bir ayar: bkz. flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) bilinmeyen ön ayar `{name}` (bkz. düzleştirici.presets.list) @@ -5324,6 +5362,7 @@ file-filter Flattener presets Düzleştirici önayarları file-filter PDF presets PDF önayarları file-filter PDF-compatible .ai PDF ile uyumlu .ai file-filter Print presets Baskı önayarları +file-filter Preferences Tercihler file-filter SVG Compressed Sıkıştırılmış SVG file-filter Swatch libraries Renk örneği kitaplıkları file-filter Templates Şablonlar @@ -5361,6 +5400,7 @@ theme Appearance Görünüm Preview (1 inch on the page) Önizleme (sayfada 1 inç) Set as Default Varsayılan Olarak Ayarla out from a highlighted edge to place its dimension | boyutunu yerleştirmek için vurgulanan kenardan dışarı | + two points, then move and click to place an aligned, horizontal or vertical dimension | ile iki nokta seçin, ardından hizalı, yatay veya dikey bir boyut yerleştirmek için hareket ettirip tıklayın | cancels | Double-click the tool for options iptal | Seçenekler için araca çift tıklayın Angular Açısal Away from the Line Çizgiden Uzakta @@ -5390,13 +5430,16 @@ theme Appearance Görünüm @msg Invalid drawing scale Geçersiz çizim ölçeği @msg Invalid real scale Geçersiz gerçek ölçek @msg Measured anchor no longer exists Ölçülen çapa artık mevcut değil +@msg Invalid measured point Geçersiz ölçülen nokta @msg Measured segment no longer exists Ölçülen segment artık mevcut değil @msg Non-finite dimension Sonlu olmayan boyut +@msg Only linear dimensions are horizontal or vertical Yalnızca doğrusal boyutlar yatay veya dikey olabilir @msg Scale must be drawing:real, for example 1:10 Ölçek çizim olmalıdır:gerçek, örneğin 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Ölçek oranı 1:1000000 ile 1000000:1 arasında olmalıdır @msg Second measured segment no longer exists Ölçülen ikinci segment artık mevcut değil @msg Unknown dimension mode Bilinmeyen boyut modu @msg Unknown dimension option {k} Bilinmeyen boyut seçeneği {k} +@msg Unknown dimension orientation Bilinmeyen boyut yönü @msg Unknown dimension style Bilinmeyen boyut stili @msg Unknown unit Bilinmeyen birim Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Açık profillerin dairesel uçlarını kapatın. Kısmi süpürmeler kesik taraflarını açık tutar. @@ -6040,6 +6083,12 @@ axis Y Axis Y ekseni Flag Bayrak Crosshair Nişangah Checkpoint Kontrol noktası + Inventory Icons Envanter Simgeleri + Sword Kılıç + Shield Kalkan + Potion İksir + Key Anahtar + Gem Mücevher Open Symbol Library Sembol Kitaplığını Aç Save Symbol Library Sembol Kitaplığını Kaydet Save Symbol Library… Sembol Kitaplığını Kaydet… @@ -6689,3 +6738,31 @@ breakText Glyphs Glifler No Suggestions Öneri Yok Edit Custom Dictionary Özel Sözlüğü Düzenle Entry: Giriş: +# Script Console + Script Console Betik Konsolu + Clear Script Console Betik Konsolunu Temizle + Copy Script Console Betik Konsolunu Kopyala + Copy All Tümünü Kopyala + Copy Selected Seçileni Kopyala + Finished Bitti + Ended with an error Bir hatayla sona erdi + Out of fuel Komut sınırına ulaşıldı + Ended at a host limit Bir ana bilgisayar sınırında sona erdi + Ended at a limit Bir sınırda sona erdi + Stopped Durduruldu + Ended by an internal fault Bir iç hata nedeniyle sona erdi + time unavailable süre kullanılamıyor + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} en yavaşlar: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} ana bilgisayar çağrısı +@plural {n} earlier line dropped|{n} earlier lines dropped {n} eski satır atıldı +@plural {n} line cut|{n} lines cut {n} satır kesildi +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` ve `last`, konsolun tuttuğu satırların numaraları olmalı ve `first`, `last` değerinden önce gelmeli + +# Deferred plug-in effects + Refresh Deferred Effects Ertelenen Efektleri Yenile + Deferred Effects Ertelenen Efektler +@msg no plug-in effect is deferred ertelenen eklenti efekti yok +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. {n} eklenti efekti ertelenerek açıldı. Efekt › Ertelenen Efektleri Yenile bunları çalıştırır. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4652ce4ca8..c1b1c3bdaf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -283,6 +283,7 @@ font-technology Variable Варіативні Average… Усереднити… Axis: Вісь: Background Color: Колір тла: + Guide Label: Мітка напрямних: Show Center Mark Показати центральну позначку Show Cross Hairs Показати перехрестя Show Video Safe Areas Показати безпечні зони відео @@ -1272,6 +1273,7 @@ file-filter Swatch libraries Бібліотеки зразків file-filter Flattener presets Набори зведення file-filter PDF presets Набори PDF file-filter Print presets Набори друку +file-filter Preferences Налаштування file-filter Export presets Набори параметрів експорту file-filter SVG Compressed Стиснутий SVG file-filter PDF-compatible .ai .ai, сумісний з PDF @@ -1919,6 +1921,7 @@ file-filter Templates Шаблони Lock Grid Заблокувати сітку Lock Guides Заблокувати напрямні Lock Guides by Default Блокувати напрямні за замовчуванням + Artboard Guides with Cmd/Ctrl + Ruler Drag Напрямні монтажної області з Cmd/Ctrl + перетягуванням з лінійки Lock Others Заблокувати решту Lock Slices Заблокувати фрагменти Lock Station Point Заблокувати точку стояння @@ -2844,6 +2847,12 @@ digits Malayalam Малаялам Reset OpenType Features Скинути функції OpenType Reset Panel Скинути панель Reset Preferences Скинути налаштування + Export Preferences… Експортувати налаштування… + Import Preferences… Імпортувати налаштування… + Save the applied preferences to a JSON file Зберегти застосовані налаштування у файл JSON + Apply the preferences in a file Export Preferences saved Застосувати налаштування з файлу, збереженого командою «Експортувати налаштування» + Export Preferences Експортувати налаштування + Import Preferences Імпортувати налаштування Search Preferences Пошук у налаштуваннях No settings found Налаштування не знайдено Reset Profiles Скинути профілі @@ -2867,6 +2876,8 @@ digits Malayalam Малаялам Responsive Адаптивний Restore Відновити Restore every preference to its default (applied on OK) Відновити всі параметри за промовчанням (застосовується при натисканні ОК) + Reset all preferences to their defaults? Скинути всі налаштування до значень за промовчанням? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Значення за промовчанням застосовуються, коли ви натискаєте ОК у вікні «Налаштування». Скасувати там зберігає поточні налаштування. Restore Recovered Documents Відновити відновлені документи Restored documents open unsaved: save them to keep them. Відновлені документи відкриваються незбереженими: збережіть їх, щоб залишити. Restrict printing, editing and other tasks Обмежити друк, редагування та інші завдання @@ -3174,6 +3185,13 @@ digits Malayalam Малаялам Quest Outline Квест Coin Shine Монета Boss Alert Бос + Status Effects Ефекти статусу + Poison Tint Отрута + Freeze Edge Заморозка + Burn Aura Опік + Stun Pulse Оглушення + Stealth Fade Невидимість + Shield Buff Щит Shape Фігура Shape Builder Створення фігур Shape Builder Regions Області створення фігур @@ -3594,6 +3612,8 @@ effect Points Точки Copies per Sheet (as many as fit, in a grid) Копій на аркуш (скільки поміститься, сіткою) Gutter: Проміжок: Tint Відтінок + Fill Tint Відтінок заливки + Stroke Tint Відтінок обведення Tip extends past the end point Кінчик виходить за кінцеву точку Tip on the end point Кінчик на кінцевій точці Title Case Як у заголовку @@ -4105,6 +4125,7 @@ axis Both Обидві Stop Script Зупинити скрипт Show External Script Warning Показувати попередження про зовнішні скрипти A Script Is Running Виконується скрипт + Script Alert Повідомлення скрипту A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. Do not show this warning again Більше не показувати це попередження Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. @@ -4118,6 +4139,9 @@ axis Both Обидві @msg the script is too large to run скрипт завеликий для виконання @msg a drag or an undo group is open; finish it before running a script відкрито перетягування або групу скасування; завершіть їх перед запуском скрипта @msg the script left a document that cannot be kept скрипт залишив документ, який не можна зберегти +@msg the script is no longer in the Scripts folder скрипт більше не міститься в папці Scripts + Some scripts were not listed Деякі сценарії не показано + The Scripts folder cannot be read Не вдалося прочитати папку Scripts @msg the script's run is no longer available виконання скрипта більше не доступне @msg a failed command changed undo steps that could not be put back, so the script was stopped невдала команда змінила кроки скасування, які не вдалося відновити, тому скрипт зупинено @msg a recovery copy could not be written, so the script was not run не вдалося записати копію для відновлення, тому скрипт не виконано @@ -4302,6 +4326,7 @@ axis Both Обидві @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis має бути "vertical", "horizontal" або кутом у градусах, а не `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" фон {other}: transparent, white, black або колір, наприклад "#ff8800" @msg bad color {v} неприпустимий колір {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` має бути null, назвою кольору шару або #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio має бути числом від 0,1 до 10 @msg the Color Picker is not open палітра кольорів не відкрита @msg the Simplify slider is not open повзунок «Спростити» не відкрито @@ -4707,6 +4732,20 @@ axis Both Обидві @msg unknown overprints `{o}` (preserve, simulate or discard) невідомі накладення `{o}` (preserve, simulate або discard) @msg unknown panel `{raw}` невідома панель `{raw}` @msg unknown preference `{key}` невідоме налаштування `{key}` +@msg Preferences imported. Налаштування імпортовано. +@msg not a preferences file: {e} не є файлом налаштувань: {e} +@msg not a preferences file: no JSON object не є файлом налаштувань: немає об’єкта JSON +@msg not a preferences file (format `{format}`) не є файлом налаштувань (формат `{format}`) +@msg not a preferences file: no `format` не є файлом налаштувань: немає `format` +@msg not a preferences file: no `version` не є файлом налаштувань: немає `version` +@msg not a preferences file: no `prefs` не є файлом налаштувань: немає `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) файл збережено новішою версією VectorCraft (версія {v}) +@msg the file holds no preferences файл не містить налаштувань +@msg `{key}` names a folder, which preferences files leave out `{key}` вказує теку, а файли налаштувань не містять тек +@msg the file is larger than 1 MB файл більший за 1 МБ +@msg give `path` or `data` вкажіть `path` або `data` +@msg `{key}` must be an object `{key}` має бути об’єктом +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` виконується окремо, а не як крок пакета @msg unknown preset (one of {_1}) невідомий набір (один із: {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) невідомий набір `{name}` (high, medium, low або збережений: див. flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) невідомий набір `{name}` (див. flattener.presets.list) @@ -5270,6 +5309,7 @@ lighting Light Світло Preview (1 inch on the page) Попередній перегляд (1 дюйм на сторінці) Set as Default Встановити за замовчуванням out from a highlighted edge to place its dimension | назовні від підсвіченого краю, щоб розмістити його розмір | + two points, then move and click to place an aligned, horizontal or vertical dimension | по двох точках, потім перемістіть і клацніть, щоб розмістити вирівняний, горизонтальний або вертикальний розмір | cancels | Double-click the tool for options скасовує | Подвійне клацання по інструменту відкриває параметри Linear Лінійний Angular Кутовий @@ -5302,14 +5342,17 @@ lighting Light Світло @msg Invalid drawing scale Неприпустимий масштаб креслення @msg Invalid real scale Неприпустимий реальний масштаб @msg Measured anchor no longer exists Виміряна опорна точка більше не існує +@msg Invalid measured point Недійсна виміряна точка @msg Measured segment no longer exists Виміряний сегмент більше не існує @msg Non-finite dimension Розмір не є скінченним числом +@msg Only linear dimensions are horizontal or vertical Лише лінійні розміри бувають горизонтальними або вертикальними @msg Scale Text Attributes: selected type has no scale to bake Масштабувати атрибути тексту: у вибраного тексту немає масштабу для застосування @msg Scale must be drawing:real, for example 1:10 Масштаб має бути у вигляді креслення:реальність, наприклад 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Співвідношення масштабу має бути від 1:1000000 до 1000000:1 @msg Second measured segment no longer exists Другий виміряний сегмент більше не існує @msg Unknown dimension mode Невідомий режим розміру @msg Unknown dimension option {k} Невідомий параметр розміру {k} +@msg Unknown dimension orientation Невідома орієнтація розміру @msg Unknown dimension style Невідомий стиль розміру @msg Unknown unit Невідома одиниця # Revolve cap description @@ -5681,6 +5724,12 @@ axis Y Axis Вісь Y Flag Прапор Crosshair Приціл Checkpoint Контрольна точка + Inventory Icons Піктограми інвентарю + Sword Меч + Shield Щит + Potion Зілля + Key Ключ + Gem Самоцвіт Open Symbol Library Відкрити бібліотеку символів Save Symbol Library Зберегти бібліотеку символів Save Symbol Library… Зберегти бібліотеку символів… @@ -6334,3 +6383,31 @@ breakText Glyphs Гліфи No Suggestions Немає варіантів Edit Custom Dictionary Редагувати словник користувача Entry: Запис: +# Script Console + Script Console Консоль скриптів + Clear Script Console Очистити консоль скриптів + Copy Script Console Копіювати консоль скриптів + Copy All Копіювати все + Copy Selected Копіювати виділене + Finished Завершено + Ended with an error Завершено з помилкою + Out of fuel Вичерпано ліміт інструкцій + Ended at a host limit Завершено на ліміті хоста + Ended at a limit Завершено на ліміті + Stopped Зупинено + Ended by an internal fault Завершено через внутрішню помилку + time unavailable час недоступний + {ms} ms {ms} мс + {time}, {calls} {time}, {calls} + slowest: {commands} найповільніші: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} виклик хоста|{n} виклики хоста|{n} викликів хоста +@plural {n} earlier line dropped|{n} earlier lines dropped {n} попередній рядок відкинуто|{n} попередні рядки відкинуто|{n} попередніх рядків відкинуто +@plural {n} line cut|{n} lines cut {n} рядок обрізано|{n} рядки обрізано|{n} рядків обрізано +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` і `last` мають бути номерами рядків, які зберігає консоль, причому `first` не пізніше `last` + +# Deferred plug-in effects + Refresh Deferred Effects Оновити відкладені ефекти + Deferred Effects Відкладені ефекти +@msg no plug-in effect is deferred немає відкладених ефектів модулів +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Відкрито з {n} відкладеним ефектом модуля. Ефект › Оновити відкладені ефекти виконає його.|Відкрито з {n} відкладеними ефектами модулів. Ефект › Оновити відкладені ефекти виконає їх.|Відкрито з {n} відкладеними ефектами модулів. Ефект › Оновити відкладені ефекти виконає їх. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4c9dac833c..d458c348ee 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -312,6 +312,7 @@ font-technology Variable Biến thiên Axis: Trục: Back Sau Background Color: Màu nền: + Guide Label: Nhãn đường căn: Show Center Mark Hiện dấu tâm Show Cross Hairs Hiện đường chữ thập Show Video Safe Areas Hiện vùng an toàn video @@ -1475,6 +1476,7 @@ file-filter Swatch libraries Thư viện mẫu màu file-filter Flattener presets Thiết lập sẵn làm phẳng file-filter PDF presets Thiết lập sẵn PDF file-filter Print presets Thiết lập sẵn in +file-filter Preferences Tùy chọn file-filter Export presets Cài đặt sẵn xuất file-filter SVG Compressed SVG nén file-filter PDF-compatible .ai .ai tương thích PDF @@ -2203,6 +2205,7 @@ digits Hindi Hindi Lock Grid Khóa lưới Lock Guides Khóa đường căn Lock Guides by Default Khóa đường căn theo mặc định + Artboard Guides with Cmd/Ctrl + Ruler Drag Đường căn bảng vẽ với Cmd/Ctrl + kéo từ thước Lock Others Khóa các mục khác Lock Slices Khóa lát cắt Lock Station Point Khóa điểm trạm @@ -3125,6 +3128,12 @@ mark-style Japanese Kiểu Nhật Reset OpenType Features Đặt lại tính năng OpenType Reset Panel Đặt lại bảng Reset Preferences Đặt lại tùy chọn + Export Preferences… Xuất tùy chọn… + Import Preferences… Nhập tùy chọn… + Save the applied preferences to a JSON file Lưu các tùy chọn đang áp dụng vào tệp JSON + Apply the preferences in a file Export Preferences saved Áp dụng các tùy chọn trong tệp do Xuất tùy chọn lưu + Export Preferences Xuất tùy chọn + Import Preferences Nhập tùy chọn Search Preferences Tìm trong tùy chọn No settings found Không tìm thấy cài đặt Reset Profiles Đặt lại hồ sơ màu @@ -3158,6 +3167,8 @@ mark-style Japanese Kiểu Nhật Responsive Đáp ứng Restore Khôi phục Restore every preference to its default (applied on OK) Khôi phục tất cả tùy chọn về mặc định (áp dụng khi nhấn OK) + Reset all preferences to their defaults? Đặt lại tất cả tùy chọn về mặc định? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Giá trị mặc định được áp dụng khi bạn nhấn OK trong Tùy chọn. Hủy ở đó giữ nguyên các tùy chọn hiện tại của bạn. Restore Recovered Documents Khôi phục tài liệu đã phục hồi Restored documents open unsaved: save them to keep them. Tài liệu đã khôi phục mở ở trạng thái chưa lưu: hãy lưu để giữ lại. Restrict printing, editing and other tasks Hạn chế in, chỉnh sửa và các tác vụ khác @@ -3506,6 +3517,13 @@ mark-style Japanese Kiểu Nhật Quest Outline Nhiệm vụ Coin Shine Xu Boss Alert Trùm + Status Effects Hiệu ứng trạng thái + Poison Tint Độc + Freeze Edge Đóng băng + Burn Aura Bỏng + Stun Pulse Choáng + Stealth Fade Ẩn thân + Shield Buff Khiên Shape Hình dạng Shape Builder Tạo hình dạng Shape Builder Regions Vùng Tạo hình dạng @@ -3941,6 +3959,8 @@ mark-style Japanese Kiểu Nhật Copies per Sheet (as many as fit, in a grid) Nhiều bản sao trên một tờ (xếp vừa bao nhiêu in bấy nhiêu, theo lưới) Gutter: Khoảng cách: Tint Tông màu + Fill Tint Tông màu tô + Stroke Tint Tông màu nét Tints Sắc pha Tints and Shades Sắc pha và bóng Tips Mẹo @@ -4472,6 +4492,7 @@ theme Appearance Giao diện @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis phải là "vertical", "horizontal" hoặc góc theo độ, không phải `{v}` @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black hoặc màu như "#ff8800" @msg bad color {v} màu không hợp lệ {v} +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` là null, tên một màu lớp hoặc #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio phải là một số từ 0,1 đến 10 @msg the Color Picker is not open Bộ chọn màu chưa được mở @msg the Simplify slider is not open Thanh trượt Đơn giản hóa chưa được mở @@ -4523,6 +4544,7 @@ theme Appearance Giao diện Stop Script Dừng tập lệnh Show External Script Warning Hiện cảnh báo tập lệnh bên ngoài A Script Is Running Một tập lệnh đang chạy + Script Alert Thông báo của tập lệnh A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. Do not show this warning again Không hiện lại cảnh báo này Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại. @@ -4536,6 +4558,9 @@ theme Appearance Giao diện @msg the script is too large to run tập lệnh quá lớn để chạy @msg a drag or an undo group is open; finish it before running a script đang có thao tác kéo hoặc nhóm hoàn tác; hãy hoàn thành trước khi chạy tập lệnh @msg the script left a document that cannot be kept tập lệnh để lại một tài liệu không thể giữ +@msg the script is no longer in the Scripts folder tập lệnh không còn trong thư mục Scripts + Some scripts were not listed Một số tập lệnh không được liệt kê + The Scripts folder cannot be read Không thể đọc thư mục Scripts @msg the script's run is no longer available lần chạy tập lệnh không còn khả dụng @msg a failed command changed undo steps that could not be put back, so the script was stopped một lệnh thất bại đã thay đổi các bước hoàn tác không thể khôi phục, nên tập lệnh đã bị dừng @msg a recovery copy could not be written, so the script was not run không thể ghi bản sao khôi phục nên tập lệnh không được chạy @@ -5159,6 +5184,20 @@ theme Appearance Giao diện @msg missing `{path}` thiếu `{path}` @msg `{path}` must be {expected}, not {got} `{path}` phải là {expected}, không phải {got} @msg unknown preference `{key}` tùy chọn không xác định `{key}` +@msg Preferences imported. Đã nhập tùy chọn. +@msg not a preferences file: {e} không phải tệp tùy chọn: {e} +@msg not a preferences file: no JSON object không phải tệp tùy chọn: không có đối tượng JSON +@msg not a preferences file (format `{format}`) không phải tệp tùy chọn (định dạng `{format}`) +@msg not a preferences file: no `format` không phải tệp tùy chọn: thiếu `format` +@msg not a preferences file: no `version` không phải tệp tùy chọn: thiếu `version` +@msg not a preferences file: no `prefs` không phải tệp tùy chọn: thiếu `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) tệp được lưu bằng phiên bản VectorCraft mới hơn (phiên bản {v}) +@msg the file holds no preferences tệp không chứa tùy chọn nào +@msg `{key}` names a folder, which preferences files leave out `{key}` chỉ định một thư mục, và tệp tùy chọn không chứa thư mục +@msg the file is larger than 1 MB tệp lớn hơn 1 MB +@msg give `path` or `data` hãy cung cấp `path` hoặc `data` +@msg `{key}` must be an object `{key}` phải là một đối tượng +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` chạy riêng, không phải là một bước trong lô @msg unknown preset (one of {_1}) thiết lập sẵn không xác định (một trong {_1}) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) thiết lập sẵn không xác định `{name}` (high, medium, low hoặc thiết lập đã lưu: xem flattener.presets.list) @msg unknown preset `{name}` (see flattener.presets.list) thiết lập sẵn không xác định `{name}` (xem flattener.presets.list) @@ -5273,6 +5312,7 @@ theme Appearance Giao diện Preview (1 inch on the page) Xem trước (1 inch trên trang) Set as Default Đặt làm mặc định out from a highlighted edge to place its dimension | ra ngoài từ một cạnh được tô sáng để đặt kích thước của nó | + two points, then move and click to place an aligned, horizontal or vertical dimension | hai điểm, rồi di chuyển và bấm để đặt kích thước căn theo hai điểm, nằm ngang hoặc thẳng đứng | cancels | Double-click the tool for options để hủy | Nhấp đúp vào công cụ để mở tùy chọn Linear Tuyến tính Angular Góc @@ -5303,14 +5343,17 @@ theme Appearance Giao diện @msg Invalid drawing scale Tỷ lệ bản vẽ không hợp lệ @msg Invalid real scale Tỷ lệ thực không hợp lệ @msg Measured anchor no longer exists Điểm neo được đo không còn tồn tại +@msg Invalid measured point Điểm được đo không hợp lệ @msg Measured segment no longer exists Đoạn được đo không còn tồn tại @msg Non-finite dimension Kích thước không phải là số hữu hạn +@msg Only linear dimensions are horizontal or vertical Chỉ kích thước tuyến tính mới nằm ngang hoặc thẳng đứng @msg Scale Text Attributes: selected type has no scale to bake Tỷ lệ thuộc tính văn bản: văn bản được chọn không có tỷ lệ để áp dụng @msg Scale must be drawing:real, for example 1:10 Tỷ lệ phải có dạng bản vẽ:thực tế, ví dụ 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 Tỷ lệ phải nằm trong khoảng 1:1000000 đến 1000000:1 @msg Second measured segment no longer exists Đoạn được đo thứ hai không còn tồn tại @msg Unknown dimension mode Chế độ kích thước không xác định @msg Unknown dimension option {k} Tùy chọn kích thước không xác định {k} +@msg Unknown dimension orientation Hướng kích thước không xác định @msg Unknown dimension style Kiểu kích thước không xác định @msg Unknown unit Đơn vị không xác định # Revolve cap description @@ -5682,6 +5725,12 @@ axis Y Axis Trục Y Flag Cờ Crosshair Tâm ngắm Checkpoint Điểm kiểm tra + Inventory Icons Biểu tượng túi đồ + Sword Kiếm + Shield Khiên + Potion Thuốc + Key Chìa khóa + Gem Ngọc Open Symbol Library Mở thư viện ký hiệu Save Symbol Library Lưu thư viện ký hiệu Save Symbol Library… Lưu thư viện ký hiệu… @@ -6335,3 +6384,31 @@ breakText Glyphs Glyph No Suggestions Không có gợi ý Edit Custom Dictionary Chỉnh sửa từ điển tùy chỉnh Entry: Mục nhập: +# Script Console + Script Console Bảng điều khiển tập lệnh + Clear Script Console Xóa bảng điều khiển tập lệnh + Copy Script Console Sao chép bảng điều khiển tập lệnh + Copy All Sao chép tất cả + Copy Selected Sao chép mục đã chọn + Finished Đã xong + Ended with an error Kết thúc do lỗi + Out of fuel Đã hết giới hạn lệnh + Ended at a host limit Kết thúc ở giới hạn của máy chủ + Ended at a limit Kết thúc ở giới hạn + Stopped Đã dừng + Ended by an internal fault Kết thúc do lỗi nội bộ + time unavailable không có thời gian + {ms} ms {ms} ms + {time}, {calls} {time}, {calls} + slowest: {commands} chậm nhất: {commands} + {dropped}, {cut} {dropped}, {cut} +@plural {n} host call|{n} host calls {n} lệnh gọi máy chủ +@plural {n} earlier line dropped|{n} earlier lines dropped đã bỏ {n} dòng cũ +@plural {n} line cut|{n} lines cut đã cắt {n} dòng +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` và `last` phải là số thứ tự của các dòng mà bảng điều khiển đang giữ, `first` đứng trước `last` + +# Deferred plug-in effects + Refresh Deferred Effects Làm mới hiệu ứng bị hoãn + Deferred Effects Hiệu ứng bị hoãn +@msg no plug-in effect is deferred không có hiệu ứng plug-in nào bị hoãn +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Đã mở với {n} hiệu ứng plug-in bị hoãn. Hiệu ứng › Làm mới hiệu ứng bị hoãn sẽ chạy chúng. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c62b176687..028bd60571 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -235,6 +235,7 @@ antiAlias Sharp 锐利 Average… 平均… Axis: 轴: Background Color: 背景颜色: + Guide Label: 参考线标签: Show Center Mark 显示中心标记 Show Cross Hairs 显示十字线 Show Video Safe Areas 显示视频安全区域 @@ -1216,6 +1217,7 @@ file-filter Swatch libraries 色板库 file-filter Flattener presets 拼合预设 file-filter PDF presets PDF 预设 file-filter Print presets 打印预设 +file-filter Preferences 首选项 file-filter Export presets 导出预设 file-filter SVG Compressed 压缩 SVG file-filter PDF-compatible .ai PDF 兼容 .ai @@ -1806,6 +1808,7 @@ file-filter Templates 模板 Lock Grid 锁定网格 Lock Guides 锁定参考线 Lock Guides by Default 默认锁定参考线 + Artboard Guides with Cmd/Ctrl + Ruler Drag 按住 Cmd/Ctrl 从标尺拖动创建画板参考线 Lock Slices 锁定切片 Lock Station Point 锁定基准点 Lossless (lossy WebP isn't available yet) 无失真 (尚未提供有失真的 WebP) @@ -2718,6 +2721,12 @@ digits Malayalam 马拉雅拉姆数字 Reset OpenType Features 重置 OpenType 特性 Reset Panel 重置面板 Reset Preferences 重置首选项 + Export Preferences… 导出首选项… + Import Preferences… 导入首选项… + Save the applied preferences to a JSON file 将已应用的首选项保存到 JSON 文件 + Apply the preferences in a file Export Preferences saved 应用“导出首选项”所保存文件中的首选项 + Export Preferences 导出首选项 + Import Preferences 导入首选项 Search Preferences 搜索首选项 No settings found 未找到设置 Reset Profiles 重置配置文件 @@ -2740,6 +2749,8 @@ digits Malayalam 马拉雅拉姆数字 Responsive 响应式 Restore 恢复 Restore every preference to its default (applied on OK) 把所有首选项恢复为默认值 (点击确定后应用) + Reset all preferences to their defaults? 将所有首选项重置为默认值? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 在首选项中点击确定后才会应用默认值。在那里点击取消会保留当前首选项。 Restore Recovered Documents 恢复已恢复的文档 Restored documents open unsaved: save them to keep them. 恢复的文档处于未存储状态:请存储以保留。 Restrict printing, editing and other tasks 限制打印、编辑及其他操作 @@ -3012,6 +3023,13 @@ digits Malayalam 马拉雅拉姆数字 Quest Outline 任务 Coin Shine 金币 Boss Alert 首领 + Status Effects 状态效果 + Poison Tint 中毒 + Freeze Edge 冰冻 + Burn Aura 灼烧 + Stun Pulse 眩晕 + Stealth Fade 隐身 + Shield Buff 护盾 Shape 形状 Shape Builder 形状生成器 Shape Builder Regions 形状生成器区域 @@ -3427,6 +3445,8 @@ digits Malayalam 马拉雅拉姆数字 Tiles are numbered across, then down; leave the range empty for every tile. 拼贴先由左至右再由上至下编号;范围留空表示全部拼贴。 Copies per Sheet (as many as fit, in a grid) 每张纸印多份 (尽量排满,按网格排列) Tint 色调 + Fill Tint 填色色调 + Stroke Tint 描边色调 Tip extends past the end point 箭头超出端点 Tip on the end point 箭头位于端点 Title Case 词首大写 @@ -4148,6 +4168,20 @@ imageTrace Outline 轮廓 @msg `{key}` must be between {min} and {max} (got {x}) `{key}` 必须介于 {min} 和 {max} 之间 (实际为 {x}) @msg `{key}` must be one of {_1} `{key}` 必须是 {_1} 之一 @msg unknown preference `{key}` 未知首选项 `{key}` +@msg Preferences imported. 已导入首选项。 +@msg not a preferences file: {e} 不是首选项文件:{e} +@msg not a preferences file: no JSON object 不是首选项文件:没有 JSON 对象 +@msg not a preferences file (format `{format}`) 不是首选项文件(格式 `{format}`) +@msg not a preferences file: no `format` 不是首选项文件:没有 `format` +@msg not a preferences file: no `version` 不是首选项文件:没有 `version` +@msg not a preferences file: no `prefs` 不是首选项文件:没有 `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) 该文件由更新版本的 VectorCraft 保存(版本 {v}) +@msg the file holds no preferences 该文件不包含首选项 +@msg `{key}` names a folder, which preferences files leave out `{key}` 指定的是文件夹,首选项文件不包含文件夹 +@msg the file is larger than 1 MB 文件大于 1 MB +@msg give `path` or `data` 请提供 `path` 或 `data` +@msg `{key}` must be an object `{key}` 必须是对象 +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` 需单独运行,不能作为批处理步骤 @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 数据恢复没有可保存副本的位置:请设置“首选项 → 文件处理 → 数据恢复 → 文件夹” (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} 数据恢复无法将副本保存到 {path}:{e} @msg Plug-ins can't be loaded from {path}: {e} 无法从 {path} 载入增效工具:{e} @@ -4372,6 +4406,7 @@ imageTrace Outline 轮廓 @msg {label}… {label}… @msg no blend options 没有混合选项 @msg bad color {v} 颜色 {v} 无效 +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` 应为 null、图层颜色名称或 #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio 必须是 0.1 到 10 之间的数字 @msg the Color Picker is not open 拾色器未打开 @msg the Simplify slider is not open 简化滑块未打开 @@ -4543,6 +4578,7 @@ imageTrace Outline 轮廓 Stop Script 停止脚本 Show External Script Warning 显示外部脚本警告 A Script Is Running 脚本正在运行 + Script Alert 脚本提示 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 Do not show this warning again 不再显示此警告 Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 @@ -4556,6 +4592,9 @@ imageTrace Outline 轮廓 @msg the script is too large to run 脚本过大,无法运行 @msg a drag or an undo group is open; finish it before running a script 拖动或撤销组尚未结束;请在运行脚本前完成 @msg the script left a document that cannot be kept 脚本留下了无法保留的文档 +@msg the script is no longer in the Scripts folder 脚本已不在 Scripts 文件夹中 + Some scripts were not listed 部分脚本未列出 + The Scripts folder cannot be read 无法读取 Scripts 文件夹 @msg the script's run is no longer available 脚本运行已不可用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失败的命令更改了无法恢复的撤销步骤,因此脚本已停止 @msg a recovery copy could not be written, so the script was not run 无法写入恢复副本,因此未运行脚本 @@ -4754,14 +4793,17 @@ imageTrace Outline 轮廓 @msg Invalid drawing scale 图纸比例无效 @msg Invalid real scale 实际比例无效 @msg Measured anchor no longer exists 测量锚点已不存在 +@msg Invalid measured point 测量点无效 @msg Measured segment no longer exists 测量线段已不存在 @msg Non-finite dimension 尺寸标注不是有限值 +@msg Only linear dimensions are horizontal or vertical 只有线性尺寸可以是水平或垂直的 @msg Scale Text Attributes: selected type has no scale to bake 缩放文本属性:所选文本没有可应用的缩放 @msg Scale must be drawing:real, for example 1:10 比例必须为 图纸:实际,例如 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 比例必须介于 1:1000000 和 1000000:1 之间 @msg Second measured segment no longer exists 第二条测量线段已不存在 @msg Unknown dimension mode 未知的尺寸标注模式 @msg Unknown dimension option {k} 未知的尺寸标注选项 {k} +@msg Unknown dimension orientation 未知的尺寸标注方向 @msg span must be "object" or "selection", got {v} span 必须是 "object" 或 "selection",实际为 {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" 放置的是 `gradient`,而不是色板 @msg span: "selection" places a gradient: give `gradient` span: "selection" 放置渐变:请给出 `gradient` @@ -5558,6 +5600,7 @@ lighting Light 光源 Preview (1 inch on the page) 预览(页面上 1 英寸) Set as Default 设为默认 out from a highlighted edge to place its dimension | 从高亮的边向外拖动以放置其尺寸 | + two points, then move and click to place an aligned, horizontal or vertical dimension | 两个点,然后移动并单击以放置对齐、水平或垂直尺寸 | cancels | Double-click the tool for options 取消 | 双击工具打开选项 Linear 线性 Angular 角度 @@ -5922,6 +5965,12 @@ axis Y Axis Y 轴 Flag 旗帜 Crosshair 准星 Checkpoint 检查点 + Inventory Icons 物品栏图标 + Sword 剑 + Shield 盾 + Potion 药水 + Key 钥匙 + Gem 宝石 Open Symbol Library 打开符号库 Save Symbol Library 保存符号库 Save Symbol Library… 保存符号库… @@ -6571,3 +6620,31 @@ breakText Glyphs 字形 @msg side is left or right, not `{s}` side 应为 left 或 right,而不是 `{s}` Edit Custom Dictionary 编辑自定义词典 Entry: 条目: +# Script Console + Script Console 脚本控制台 + Clear Script Console 清除脚本控制台 + Copy Script Console 复制脚本控制台 + Copy All 全部复制 + Copy Selected 复制所选内容 + Finished 已完成 + Ended with an error 因错误结束 + Out of fuel 已用尽指令上限 + Ended at a host limit 在宿主限制处结束 + Ended at a limit 在限制处结束 + Stopped 已停止 + Ended by an internal fault 因内部错误结束 + time unavailable 时间不可用 + {ms} ms {ms} 毫秒 + {time}, {calls} {time},{calls} + slowest: {commands} 最慢的命令:{commands} + {dropped}, {cut} {dropped},{cut} +@plural {n} host call|{n} host calls 宿主调用 {n} 次 +@plural {n} earlier line dropped|{n} earlier lines dropped 已丢弃 {n} 行较早内容 +@plural {n} line cut|{n} lines cut 已截断 {n} 行 +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必须是控制台保留的行号,且 `first` 不能在 `last` 之后 + +# Deferred plug-in effects + Refresh Deferred Effects 刷新延迟的效果 + Deferred Effects 延迟的效果 +@msg no plug-in effect is deferred 没有延迟的增效工具效果 +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. 打开时延迟了 {n} 个增效工具效果。效果 › 刷新延迟的效果可运行它们。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0b3a21250c..7cb218f99f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -248,6 +248,7 @@ font-technology Variable 可變 Average… 平均… Axis: 軸: Background Color: 背景顏色: + Guide Label: 參考線標籤: Show Center Mark 顯示中心標記 Show Cross Hairs 顯示十字線 Show Video Safe Areas 顯示視訊安全區域 @@ -1242,6 +1243,7 @@ file-filter Swatch libraries 色票資料庫 file-filter Flattener presets 平面化預設集 file-filter PDF presets PDF 預設集 file-filter Print presets 列印預設集 +file-filter Preferences 偏好設定 file-filter Export presets 轉存預設集 file-filter SVG Compressed 壓縮 SVG file-filter PDF-compatible .ai PDF 相容 .ai @@ -1982,6 +1984,20 @@ file-filter Templates 範本 @msg `{key}` must be between {min} and {max} (got {x}) `{key}` 必須介於 {min} 和 {max} 之間 (收到 {x}) @msg `{key}` must be one of {_1} `{key}` 必須是 {_1} 其中之一 @msg unknown preference `{key}` 未知的偏好設定 `{key}` +@msg Preferences imported. 已匯入偏好設定。 +@msg not a preferences file: {e} 不是偏好設定檔案:{e} +@msg not a preferences file: no JSON object 不是偏好設定檔案:沒有 JSON 物件 +@msg not a preferences file (format `{format}`) 不是偏好設定檔案(格式 `{format}`) +@msg not a preferences file: no `format` 不是偏好設定檔案:沒有 `format` +@msg not a preferences file: no `version` 不是偏好設定檔案:沒有 `version` +@msg not a preferences file: no `prefs` 不是偏好設定檔案:沒有 `prefs` +@msg the file was saved by a newer version of VectorCraft (version {v}) 此檔案由較新版本的 VectorCraft 儲存(版本 {v}) +@msg the file holds no preferences 此檔案不含偏好設定 +@msg `{key}` names a folder, which preferences files leave out `{key}` 指定的是資料夾,偏好設定檔案不含資料夾 +@msg the file is larger than 1 MB 檔案大於 1 MB +@msg give `path` or `data` 請提供 `path` 或 `data` +@msg `{key}` must be an object `{key}` 必須是物件 +@msg `prefs.import` runs on its own, not as a batch step `prefs.import` 須單獨執行,不能作為批次步驟 @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 「資料復原」沒有可存放拷貝的位置:請設定「偏好設定 → 檔案處理 → 資料復原 → 資料夾」 (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} 「資料復原」無法將拷貝存放到 {path}:{e} @msg Plug-ins can't be loaded from {path}: {e} 無法從 {path} 載入增效模組:{e} @@ -2209,6 +2225,7 @@ file-filter Templates 範本 @msg {label}… {label}… @msg no blend options 沒有漸變選項 @msg bad color {v} 顏色 {v} 無效 +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` 應為 null、圖層顏色名稱或 #rrggbb @msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio 必須是 0.1 到 10 之間的數字 @msg the Color Picker is not open 「顏色選擇器」未開啟 @msg the Simplify slider is not open 「簡化」滑桿未開啟 @@ -2380,6 +2397,7 @@ file-filter Templates 範本 Stop Script 停止指令碼 Show External Script Warning 顯示外部指令碼警告 A Script Is Running 指令碼正在執行 + Script Alert 指令碼提示 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 Do not show this warning again 不再顯示此警告 Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 @@ -2393,6 +2411,9 @@ file-filter Templates 範本 @msg the script is too large to run 指令碼過大,無法執行 @msg a drag or an undo group is open; finish it before running a script 拖曳或還原群組尚未結束;請在執行指令碼前完成 @msg the script left a document that cannot be kept 指令碼留下了無法保留的文件 +@msg the script is no longer in the Scripts folder 指令碼已不在 Scripts 資料夾中 + Some scripts were not listed 部分指令碼未列出 + The Scripts folder cannot be read 無法讀取 Scripts 資料夾 @msg the script's run is no longer available 指令碼執行已無法使用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗的命令變更了無法還原的復原步驟,因此指令碼已停止 @msg a recovery copy could not be written, so the script was not run 無法寫入復原副本,因此未執行指令碼 @@ -2589,14 +2610,17 @@ file-filter Templates 範本 @msg Invalid drawing scale 圖紙比例無效 @msg Invalid real scale 實際比例無效 @msg Measured anchor no longer exists 測量的錨點已不存在 +@msg Invalid measured point 測量點無效 @msg Measured segment no longer exists 測量的線段已不存在 @msg Non-finite dimension 尺寸標註不是有限值 +@msg Only linear dimensions are horizontal or vertical 只有線性尺寸可以是水平或垂直的 @msg Scale Text Attributes: selected type has no scale to bake 縮放文字屬性:所選文字沒有可套用的縮放 @msg Scale must be drawing:real, for example 1:10 比例必須為 圖紙:實際,例如 1:10 @msg Scale ratio must be between 1:1000000 and 1000000:1 比例必須介於 1:1000000 和 1000000:1 之間 @msg Second measured segment no longer exists 第二條測量線段已不存在 @msg Unknown dimension mode 未知的尺寸標註模式 @msg Unknown dimension option {k} 未知的尺寸標註選項 {k} +@msg Unknown dimension orientation 未知的尺寸標註方向 @msg span must be "object" or "selection", got {v} span 必須是 "object" 或 "selection",收到 {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" 放置的是 `gradient`,而非色票 @msg span: "selection" places a gradient: give `gradient` span: "selection" 會放置漸層:請提供 `gradient` @@ -2828,6 +2852,7 @@ file-filter Templates 範本 Lock Grid 鎖定格點 Lock Guides 鎖定參考線 Lock Guides by Default 預設鎖定參考線 + Artboard Guides with Cmd/Ctrl + Ruler Drag 按住 Cmd/Ctrl 從尺標拖曳建立工作區域參考線 Lock Others 鎖定其他 Lock Slices 鎖定切片 Lock Station Point 鎖定基準點 @@ -3774,6 +3799,12 @@ digits Malayalam 馬來亞拉姆數字 Reset OpenType Features 重設 OpenType 功能 Reset Panel 重設面板 Reset Preferences 重設偏好設定 + Export Preferences… 匯出偏好設定… + Import Preferences… 匯入偏好設定… + Save the applied preferences to a JSON file 將已套用的偏好設定儲存為 JSON 檔案 + Apply the preferences in a file Export Preferences saved 套用「匯出偏好設定」所儲存檔案中的偏好設定 + Export Preferences 匯出偏好設定 + Import Preferences 匯入偏好設定 Search Preferences 搜尋偏好設定 No settings found 找不到設定 Reset Profiles 重設描述檔 @@ -3797,6 +3828,8 @@ digits Malayalam 馬來亞拉姆數字 Responsive 回應式 Restore 還原 Restore every preference to its default (applied on OK) 將所有偏好設定還原為預設值 (按下確定後套用) + Reset all preferences to their defaults? 要將所有偏好設定重設為預設值嗎? + The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 在偏好設定中按下確定後才會套用預設值。在那裡按下取消會保留目前的偏好設定。 Restore Recovered Documents 還原找回的文件 Restored documents open unsaved: save them to keep them. 還原的文件會以未儲存狀態開啟:請儲存以保留。 Restrict printing, editing and other tasks 限制列印、編輯及其他操作 @@ -4102,6 +4135,13 @@ digits Malayalam 馬來亞拉姆數字 Quest Outline 任務 Coin Shine 金幣 Boss Alert 首領 + Status Effects 狀態效果 + Poison Tint 中毒 + Freeze Edge 冰凍 + Burn Aura 灼燒 + Stun Pulse 暈眩 + Stealth Fade 隱身 + Shield Buff 護盾 Shape 形狀 Shape Builder 形狀建立 Shape Builder Regions 形狀建立區域 @@ -4521,6 +4561,8 @@ digits Malayalam 馬來亞拉姆數字 Copies per Sheet (as many as fit, in a grid) 每張紙印多份 (盡量排滿,以格點排列) Gutter: 間距: Tint 色調 + Fill Tint 填色色調 + Stroke Tint 筆畫色調 Tip extends past the end point 尖端延伸超過終點 Tip on the end point 尖端位於終點 Title Case 標題式大小寫 @@ -5381,6 +5423,7 @@ lighting Light 光源 Preview (1 inch on the page) 預覽(頁面上 1 英寸) Set as Default 設為預設 out from a highlighted edge to place its dimension | 從醒目提示的邊緣向外拖曳以放置其尺寸 | + two points, then move and click to place an aligned, horizontal or vertical dimension | 兩個點,然後移動並按一下以放置對齊、水平或垂直尺寸 | cancels | Double-click the tool for options 取消 | 按兩下工具開啟選項 Linear 線性 Angular 角度 @@ -5719,6 +5762,12 @@ axis Y Axis Y 軸 Flag 旗幟 Crosshair 準星 Checkpoint 檢查點 + Inventory Icons 物品欄圖示 + Sword 劍 + Shield 盾 + Potion 藥水 + Key 鑰匙 + Gem 寶石 Open Symbol Library 開啟符號資料庫 Save Symbol Library 儲存符號資料庫 Save Symbol Library… 儲存符號資料庫… @@ -6369,3 +6418,31 @@ breakText Glyphs 字符 @msg side is left or right, not `{s}` side 應為 left 或 right,而不是 `{s}` Edit Custom Dictionary 編輯自訂字典 Entry: 項目: +# Script Console + Script Console 指令碼主控台 + Clear Script Console 清除指令碼主控台 + Copy Script Console 複製指令碼主控台 + Copy All 全部複製 + Copy Selected 複製所選內容 + Finished 已完成 + Ended with an error 因錯誤結束 + Out of fuel 已用盡指令上限 + Ended at a host limit 在主機限制處結束 + Ended at a limit 在限制處結束 + Stopped 已停止 + Ended by an internal fault 因內部錯誤結束 + time unavailable 時間無法取得 + {ms} ms {ms} 毫秒 + {time}, {calls} {time},{calls} + slowest: {commands} 最慢的命令:{commands} + {dropped}, {cut} {dropped},{cut} +@plural {n} host call|{n} host calls 主機呼叫 {n} 次 +@plural {n} earlier line dropped|{n} earlier lines dropped 已捨棄 {n} 行較早內容 +@plural {n} line cut|{n} lines cut 已截斷 {n} 行 +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` 和 `last` 必須是主控台保留的行號,且 `first` 不能在 `last` 之後 + +# Deferred plug-in effects + Refresh Deferred Effects 重新整理延後的效果 + Deferred Effects 延後的效果 +@msg no plug-in effect is deferred 沒有延後的增效模組效果 +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. 開啟時延後了 {n} 個增效模組效果。效果 › 重新整理延後的效果可執行它們。 diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index e9860e99a7..cfbdaaadba 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -132,6 +132,7 @@ const FILE_TYPES: &[(&str, &[&str])] = &[ ("Composite fonts", vectorcraft_engine::cmd::compositefonts::EXTS), ("CSS", &["css"]), ("PostScript", &["ps"]), + ("Preferences", &["json"]), ]; /// The file type a save panel shows for a file with extension `ext`: its format's, else its diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 932520b184..644125b545 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -66,6 +66,7 @@ pub mod recovery; pub mod render_worker; pub mod screen_color; pub mod script_runs; +pub mod scripts_menu; mod scrub; pub mod shortcut_editor; pub mod shortcuts; diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index cbc1536fc3..3f34af13a3 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -23,6 +23,7 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { ctx.data_mut(|d| d.insert_temp::(field_key, field)); } let mut clicked: Option<(String, Value)> = None; + let mut file_open = false; let tree = menu_tree_named(app.session.prefs.font_names_in_english); // No application menu in the window (as in Illustrator): the bar starts at File on every // platform. The VectorCraft menu stays in the tree: the native Mac bar takes it from there. @@ -37,11 +38,21 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { let text = egui::RichText::new(tl!(title)).size(13.0).color(t.text); let resp = ui.add(egui::Button::new(text)); egui::Popup::menu(&resp).show(|ui| menu_body(app, ui, items, &mut clicked)); + if *title == "File" { + file_open = egui::Popup::is_id_open(ui.ctx(), egui::Popup::default_response_id(&resp)); + } titles.push(resp); } (ui.cursor().min.x, switch_on_hover(ui.ctx(), &titles)) }) .inner; + // The File menu opening reads the Scripts folder again, for File › Scripts. + let file_key = egui::Id::unique("menu-bar-file-open"); + let file_was_open = ctx.data(|d| d.get_temp::(file_key)).unwrap_or(false); + ctx.data_mut(|d| d.insert_temp(file_key, file_open)); + if file_open && !file_was_open { + crate::scripts_menu::refresh(app, Some(&ctx)); + } // Whether a top-level menu is open: the docking renderer lowers the floating panels' OS windows // while one is, or the menu would open under them. ctx.data_mut(|d| d.insert_temp(menu_open_id(), open)); diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 5d203fe875..815a00d6f9 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -1,6 +1,7 @@ use super::context::context_items; use super::invoke::click_target; use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut, spelling_item_label, unlock_item_label}; +use super::slots::{recent_readable, recent_slot}; use super::state::{shortcut_of, shown_state}; use super::tree::menu_tree_named; use super::{Entry, Item, Serialize, Value, VectorcraftApp}; @@ -33,8 +34,11 @@ pub fn entry<'a>(app: &VectorcraftApp, it: &'a Item) -> Option> { Some(match it { Item::Sep => Entry::Sep, Item::Header(h) => Entry::Header(t(h)), - // A plug-in's submenu shows its name as it is, as its items do. - Item::Sub(label, children) if super::labels::holds_plugin_commands(children) => Entry::Sub(label, children), + // A plug-in's submenu shows its name as it is, as its items do, and so does a subfolder of + // the Scripts folder. + Item::Sub(label, children) if super::labels::holds_plugin_commands(children) || crate::scripts_menu::is_folder(children) => { + Entry::Sub(label, children) + } Item::Sub(label, children) => Entry::Sub(t(label), children), Item::Todo(label, sc) => Entry::Item(Row { command: None, @@ -127,6 +131,13 @@ fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Ve for it in items { match it { Item::Cmd(l, id, p) => { + if *id == crate::scripts_menu::COMMAND && !crate::scripts_menu::readable(p) { + continue; + } + // The other rows keep their ids: `file.openRecent3` still opens the third file. + if id.starts_with("file.openRecent") && recent_slot(app, id).is_some_and(|path| !recent_readable(path)) { + continue; + } let Some((enabled, _)) = shown_state(app, id, p) else { continue }; out.push(MenuEntry { path: path.clone(), diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index c37a8268c2..ab530b803c 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -2,11 +2,12 @@ use super::state::{SUBJECT_COMMANDS, enabled, has_subject, waits_for_ime}; use super::{Value, VectorcraftApp, json}; /// What a menu click runs: items whose label ends with "…" and that carry default params open a -/// generic parameter dialog (fields = the defaults) instead of running immediately. +/// generic parameter dialog (fields = the defaults) instead of running immediately. A script of the +/// Scripts folder runs, whatever its name ends with. pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { let dialog = label.ends_with('…') && p.as_object().is_some_and(|o| !o.is_empty()) - && !matches!(id, "effect.dialog" | "window.panel" | "window.brightness" | "view.screenMode" | "plugin.dialog"); + && !matches!(id, "effect.dialog" | "window.panel" | "window.brightness" | "view.screenMode" | "plugin.dialog" | crate::scripts_menu::COMMAND); if dialog { return ("ui.paramDialog".into(), json!({"command": id, "label": label.trim_end_matches('…'), "params": p})); } diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 148368a279..408e5f077a 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -123,8 +123,8 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option /// Does the menu item `id` show a name that is user, file or system data rather than an interface /// label: a recent file, a saved view, a font, a user library or preset, a custom workspace, a -/// plug-in, an SVG filter? Such names are shown as they are, never translated (a workspace the user calls -/// "Layers" stays "Layers"). +/// plug-in, an SVG filter, a script of the Scripts folder? Such names are shown as they are, never +/// translated (a workspace the user calls "Layers" stays "Layers"). pub(super) fn shows_a_name(id: &str, label: &str) -> bool { const SLOTS: [&str; 8] = [ "file.openRecent", @@ -138,7 +138,10 @@ pub(super) fn shows_a_name(id: &str, label: &str) -> bool { ]; SLOTS.iter().any(|s| id.starts_with(s)) || saved_selection_slot(id).is_some() - || matches!(id, "text.setStyle" | "plugin.dialog" | "file.openWith" | "window.toolbar.custom" | "svgFilter.apply") + || matches!( + id, + "text.setStyle" | "plugin.dialog" | "file.openWith" | "window.toolbar.custom" | "svgFilter.apply" | crate::scripts_menu::COMMAND + ) || vectorcraft_engine::cmd::plugin::is_command_id(id) || (id == "window.workspace" && !crate::workspaces::is_builtin(label)) || (matches!(id, "effect.apply" | "effect.dialog") && vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label)) @@ -328,12 +331,12 @@ pub(crate) fn holds_plugin_commands(children: &[Item]) -> bool { /// Every English string the menus, the command palette, the panel registry, the toolbar and the /// Preferences dialog can show: what a complete language catalog has to cover. Names that are user -/// data (fonts, recent files, saved views, libraries, installed plug-ins), the point sizes and the -/// view angles are left out. +/// data (fonts, recent files, saved views, libraries, installed plug-ins, the scripts and subfolders +/// of the Scripts folder), the point sizes and the view angles are left out. pub fn menu_strings() -> std::collections::BTreeSet { use std::collections::BTreeSet; fn user_data(id: &str, params: &Value) -> bool { - hidden_when_disabled(id) || id.starts_with("type.recentFont") || lists_plugin(id, params) + hidden_when_disabled(id) || id.starts_with("type.recentFont") || lists_plugin(id, params) || id == crate::scripts_menu::COMMAND } fn walk(items: &[Item], under: &str, out: &mut BTreeSet) { for it in items { @@ -354,8 +357,8 @@ pub fn menu_strings() -> std::collections::BTreeSet { Item::Todo(l, _) | Item::Header(l) => { out.insert(l.to_string()); } - // A plug-in's submenu is named after the plug-in. - Item::Sub(_, children) if holds_plugin_commands(children) => walk(children, under, out), + // A plug-in's submenu is named after the plug-in, and a subfolder's after the folder. + Item::Sub(_, children) if holds_plugin_commands(children) || crate::scripts_menu::is_folder(children) => walk(children, under, out), Item::Sub(l, children) => { out.insert(l.to_string()); // Type › Font lists the installed families: names, not UI text. @@ -375,6 +378,7 @@ pub fn menu_strings() -> std::collections::BTreeSet { out.extend(crate::native_menu::MAC_LABELS.iter().map(|s| s.to_string())); out.extend(DYNAMIC_LABELS.iter().map(|s| s.to_string())); out.extend(CONTEXT_LABELS.iter().map(|s| s.to_string())); + out.extend(crate::scripts_menu::LABELS.iter().map(|s| s.to_string())); out.extend(UI_COMMANDS.iter().map(|c| c.1.to_string())); for c in vectorcraft_engine::cmd::command_specs() { out.insert(c.label.to_string()); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 98d4da9895..1223e1e426 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1,6 +1,6 @@ use super::bar::home_key; use super::invoke::menu_dialog; -use super::slots::{recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; +use super::slots::{recent_readable, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; use super::state::{checked, selected_image}; use super::ui_commands::UI_COMMANDS; use super::{Brightness, Face, SaveMode, Value, VectorcraftApp, io, json, next_zoom}; @@ -137,7 +137,7 @@ fn run_ui_part1(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(io::hide_exports(app)), "file.cancelOpen" => Ok(crate::opening::cancel_all(app)), "file.openInBackground" => Ok(crate::opening::hide_all(app)), - id if id.starts_with("file.openRecent") => match recent_slot(app, id).cloned() { + id if id.starts_with("file.openRecent") => match recent_slot(app, id).filter(|path| recent_readable(path)).cloned() { Some(path) => io::open_reporting(app, &path), None => Err("no such recent file".into()), }, @@ -164,7 +164,7 @@ fn run_ui_part2(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(json!(io::recent_files(app))), + "file.recentFiles" => Ok(json!(io::recent_files(app).iter().filter(|path| recent_readable(path)).collect::>())), "file.place" => crate::place::run(app, p), "file.place.queue" => crate::place::queue(app, p), "file.export.svg" if p.as_object().is_none_or(|o| o.is_empty()) => { @@ -771,6 +771,7 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::trace_presets::open(app, p), "ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p), + "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), "window.graphicStyleLibrary" => crate::panels::graphic_styles::open_library(app, p), "ui.libraryPanel" => crate::panels::library_panel::command(app, p), "ui.libraryPanel.locate" => crate::panels::library_panel::locate(app, p), @@ -974,6 +975,7 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(crate::trace_runs::hide_all(app)), "ui.checkScript" => crate::dialogs::script_check::command(app, p), "ui.runScript" => crate::dialogs::script_run::command(app, p), + crate::scripts_menu::COMMAND => crate::scripts_menu::run(app, p), "ui.perspectiveGridDialog" => crate::dialogs::perspective_grid::open(app), "ui.perspectivePresetsDialog" => { crate::dialogs::perspective_presets::open(app, s("selected").as_deref()); diff --git a/crates/ui-egui/src/menus/slots.rs b/crates/ui-egui/src/menus/slots.rs index 2dee19dcff..5bd3bfb006 100644 --- a/crates/ui-egui/src/menus/slots.rs +++ b/crates/ui-egui/src/menus/slots.rs @@ -51,6 +51,14 @@ pub(super) fn recent_slot<'a>(app: &'a VectorcraftApp, id: &str) -> Option<&'a S io::recent_files(app).get(n.checked_sub(1)?) } +/// May the request being served read recent file `path`? Under an automation read root (a control +/// client's request), a recent file outside the root is left out of `ui.menu.list` and +/// `file.recentFiles`, and its `file.openRecentN` slot answers as an empty one, as a listed script +/// outside the root is left out ([`crate::scripts_menu::readable`]). +pub(super) fn recent_readable(path: &str) -> bool { + vectorcraft_engine::file_access::check_read(path).is_ok() +} + /// View → Perspective Grid → One/Two/Three Point Perspective: the saved-preset slots of each type. pub(super) const PERSPECTIVE_SLOTS: [[&str; crate::dialogs::perspective_presets::SLOTS]; 3] = [ [ diff --git a/crates/ui-egui/src/menus/submenus.rs b/crates/ui-egui/src/menus/submenus.rs index 9e8a7ac650..469c40e7c7 100644 --- a/crates/ui-egui/src/menus/submenus.rs +++ b/crates/ui-egui/src/menus/submenus.rs @@ -136,6 +136,7 @@ pub(super) fn effect_menu() -> Vec { c("Last Effect…", "effect.last"), Sep, c("Document Raster Effects Settings…", "document.rasterEffectsSettings"), + c("Refresh Deferred Effects", "effect.refreshDeferred"), Sep, Item::Header("Vector Effects"), ]; diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index a0e4935610..bcb51b133a 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -130,6 +130,57 @@ fn hovering_another_title_switches_the_open_menu() { assert_eq!(open_titles(&ctx, &t), vec![0], "a still pointer leaves the open menu alone"); } +#[test] +fn opening_the_file_menu_reads_the_scripts_folder_again() { + let dir = std::env::temp_dir().join(format!("vc-menu-bar-scripts-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut session = vectorcraft_engine::Session::new(); + session.attach_scripts_dir(dir.clone()); + let mut app = VectorcraftApp::new(session, crate::Services::default()); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + // The scripts File › Scripts lists. + let listed = || { + let (_, file) = menu_tree().into_iter().find(|(title, _)| *title == "File").unwrap(); + let scripts = file.iter().find_map(|item| match item { + Item::Sub("Scripts", items) => Some(items.clone()), + _ => None, + }); + scripts + .unwrap() + .iter() + .filter_map(|item| if let Item::Cmd(label, crate::scripts_menu::COMMAND, _) = item { Some(*label) } else { None }) + .collect::>() + }; + // One frame of the bar, then the listing a read it started gave. + let frame = |app: &mut VectorcraftApp| { + let titles = bar_frame(app, &ctx, vec![]); + crate::scripts_menu::wait(); + titles + }; + std::fs::write(dir.join("a.js"), "").unwrap(); + frame(&mut app); + let titles = frame(&mut app); + assert!(listed().is_empty(), "the bar reads nothing while its menus are closed"); + egui::Popup::open_id(&ctx, titles[0].1); + frame(&mut app); + assert_eq!(listed(), ["a"]); + // While File stays open the folder is not read again. + std::fs::write(dir.join("b.js"), "").unwrap(); + frame(&mut app); + assert_eq!(listed(), ["a"]); + // Nor when another menu opens; the next time File opens it is. + egui::Popup::open_id(&ctx, titles[1].1); + let t = frame(&mut app); + assert_eq!((open_titles(&ctx, &t), listed()), (vec![1], vec!["a"])); + egui::Popup::open_id(&ctx, titles[0].1); + frame(&mut app); + assert_eq!(listed(), ["a", "b"]); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_popup_covering_a_title_does_not_switch_menus() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 97651d0740..947093aba3 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -62,7 +62,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Export Selection…", "file.exportSelection"), Sep, c("Package…", "ui.packageDialog"), - sub("Scripts", vec![c("Check Script…", "ui.checkScript"), c("Other Script…", "ui.runScript")]), + sub("Scripts", crate::scripts_menu::items()), Sep, c("Document Setup…", "file.documentSetup"), sub( @@ -664,6 +664,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { panel("Pathfinder", "pathfinder"), panel("Pattern Options", "patternOptions"), panel("Properties", "properties"), + panel("Script Console", crate::panels::script_console::ID), panel("Separations Preview", "separations"), panel("Stroke", "stroke"), panel("SVG Interactivity", crate::panels::svg_interactivity::ID), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fb78fc2075..a96f13e67c 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -137,7 +137,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{folder?} Type › Find Font's Find in Folder…: asks for a folder (or takes folder), then opens Missing Fonts looking there for the files of the fonts the active document misses (text.findFontFiles). Disabled where there is no folder picker (the web)", ), - ("file.recentFiles", "Recent Files", "", "{} → [path…] most recent first"), + ("file.recentFiles", "Recent Files", "", "{} → [path…] most recent first; under an automation read root, only the files inside it"), ( "file.export.svg", "Export As SVG…", @@ -976,6 +976,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.copyScriptConsole", + "Copy Script Console", + "", + "{first?, last?: numbers of lines the Script Console holds, both or neither} copy those lines of the Script Console to the clipboard as the panel shows them, each with its run's number and script name; without them every line, after a line counting the lines it dropped and cut when it dropped or cut any, which n does not count (Script Console panel: Copy Selected, Copy All; script.console gives the lines) → {lines: n}", + ), ( "window.graphicStyleLibrary", "Graphic Style Library", @@ -1526,6 +1532,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+F12", "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", ), + ( + crate::scripts_menu::COMMAND, + "Run Script", + "", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (the script is checked again, then script.run runs it by its path, so its #include lines and $.evalFile read beside it), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + ), ( "ui.checkScript", "Check Script…", diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 8d1b7ee083..56baee51aa 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -590,7 +590,7 @@ pub fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { /// What the menus' rows depend on, cheaply (no allocation): commands run, the active document, /// its revision (edits, selection and view changes), history and clipboard, the language, -/// shortcuts, plug-ins, an open file dialog and the fonts (Type › Font lists the loaded fonts +/// shortcuts, plug-ins, the Scripts folder's listing, an open file dialog and the fonts (Type › Font lists the loaded fonts /// until the installed ones are scanned, then all of them, #5483). `input` forces a change on frames with a click or /// a key press, which covers what the hash doesn't list (panels shown, a tool picked). While an /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's @@ -608,7 +608,7 @@ fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { } (app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h); app.file_dialog_open().hash(&mut h); - (crate::i18n::current().code(), menus::plugin_revision()).hash(&mut h); + (crate::i18n::current().code(), menus::plugin_revision(), crate::scripts_menu::revision()).hash(&mut h); crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed).hash(&mut h); let fonts = vectorcraft_text::FontDb::global(); (fonts.generation(), fonts.installed_fonts_ready()).hash(&mut h); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index e895bef6c6..d5bf7b6098 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -17,8 +17,9 @@ pub fn items() -> Vec<(String, String, String)> { let label = if path.is_empty() { c.label.to_string() } else { format!("{path} › {}", c.label) }; items.push((label, c.id.to_string(), menus::shortcut_of(c.id).unwrap_or("").to_string())); } - // `plugin.dialog` runs nothing without an id: [`build`] lists each filter instead. - for c in menus::UI_COMMANDS.iter().filter(|c| c.0 != "plugin.dialog") { + // `plugin.dialog` runs nothing without an id: [`build`] lists each filter instead. A script of + // the Scripts folder runs from File › Scripts, by its path. + for c in menus::UI_COMMANDS.iter().filter(|c| c.0 != "plugin.dialog" && c.0 != crate::scripts_menu::COMMAND) { items.push((c.1.to_string(), c.0.to_string(), menus::shortcut_of(c.0).unwrap_or("").to_string())); } for tool in vectorcraft_tools::catalog::all_tools() { diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 2282633eb4..1106406bc0 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -37,6 +37,7 @@ pub mod paragraph; pub mod pathfinder; pub mod pattern_options; pub mod properties; +pub mod script_console; pub mod separations; pub mod stroke; pub mod svg_interactivity; @@ -183,6 +184,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { asset_export::ID => asset_export::show(app, ui), css_properties::ID => css_properties::show(app, ui), three_d::ID => three_d::show(app, ui), + script_console::ID => script_console::show(app, ui), crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), crate::addons::color::ID => crate::addons::color::show(app, ui), crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), @@ -238,6 +240,7 @@ pub fn panel_menu_items(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) -> bool asset_export::ID => asset_export::menu(app, ui), css_properties::ID => css_properties::menu(app, ui), variables::ID => variables::menu(app, ui), + script_console::ID => script_console::menu(app, ui), "actions" => actions::menu(app, ui), id if library_panel::parse(id).is_some() => library_panel::menu(app, ui, id), _ => return false, @@ -675,6 +678,8 @@ mod tests_long_popups; #[cfg(test)] mod tests_maskview; #[cfg(test)] +mod tests_script_console; +#[cfg(test)] mod tests_stroke; #[cfg(test)] mod tests_strokedepth; diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 12fd3155e7..27bae8fcf4 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -1,4 +1,7 @@ -use super::super::tests_long_popups::{PopupWindow, assert_last_row_scrolls_into_view, assert_short_list_does_not_scroll, fx_menu_ends}; +use super::super::tests_long_popups::{ + PopupWindow, assert_last_row_scrolls_into_view, assert_popup_stays_put, assert_rows_stay_on_one_line, assert_short_list_does_not_scroll, + fx_menu_ends, +}; use super::*; /// A selected rectangle, for the fill row's swatch picker and the Add Effect button. @@ -63,6 +66,20 @@ fn a_short_swatch_picker_does_not_scroll() { assert_eq!(window.clickable(TILE), tiles, "a list that fits does not scroll"); } +/// The Add New Effect popup keeps each group's name on one line when its list scrolls: the scroll +/// bar's column widens the popup instead of narrowing the rows. +#[test] +fn the_add_effect_popup_keeps_its_rows_on_one_line_when_it_scrolls() { + let mut groups: Vec = vec![]; + for effect in vectorcraft_effects::effect_catalog() { + let group = effect.menu.get(1).copied().unwrap_or("Other").to_string(); + if !groups.contains(&group) { + groups.push(group); + } + } + assert_rows_stay_on_one_line(&mut app_with_a_selected_rectangle(), draw_bottom_bar, fx_button, &groups, "Distort & Transform", 120.0); +} + /// The Add New Effect button: the third of the bottom bar's 24 pt buttons. fn fx_button(window: &PopupWindow) -> egui::Pos2 { window.clickable(vec2(24.0, 24.0))[2].center() @@ -81,6 +98,36 @@ fn the_add_effect_popup_scrolls_inside_a_short_window() { assert_short_list_does_not_scroll(&mut app_with_a_selected_rectangle(), draw_bottom_bar, fx_button, &first, &last); } +/// The Add New Effect popup opened from a button `below` pt above the bottom of a window `height` +/// pt tall stays at one place on every frame, inside the window. +fn assert_add_effect_popup_stays_put(height: f32, below: f32) -> Rect { + let (first, _) = fx_menu_ends(); + let draw = move |app: &mut VectorcraftApp, ui: &mut Ui| { + ui.add_space((height - below - 24.0).max(0.0)); + draw_bottom_bar(app, ui); + }; + assert_popup_stays_put(&mut app_with_a_selected_rectangle(), height, draw, fx_button, &first) +} + +/// Opened from a button near the bottom of a short window, the Add New Effect popup stays at one +/// place instead of being drawn above and below the button on alternate frames. +#[test] +fn the_add_effect_popup_stays_put_near_the_bottom_of_a_short_window() { + for height in [200.0, 300.0, 400.0, 600.0] { + let row = assert_add_effect_popup_stays_put(height, 8.0); + assert!(row.bottom() < height - 32.0, "in a {height} pt window the popup opens above the button: {row:?}"); + } +} + +/// Opened from a button near the top of a window, the popup opens below it and stays there. +#[test] +fn the_add_effect_popup_stays_put_below_a_button_near_the_top() { + for height in [200.0, 400.0, 900.0] { + let row = assert_add_effect_popup_stays_put(height, height - 32.0); + assert!(row.top() > 24.0, "in a {height} pt window the popup opens below the button: {row:?}"); + } +} + /// Duplicating rows highlights the copies, each right above its original, as the Layers panel /// does: the active row's copy becomes active, the anchor's copy the anchor. #[test] diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 7e797cead5..1586943c07 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1,4 +1,6 @@ -use super::super::tests_long_popups::{PopupWindow, assert_last_row_scrolls_into_view, assert_short_list_does_not_scroll}; +use super::super::tests_long_popups::{ + PopupWindow, assert_last_row_scrolls_into_view, assert_rows_stay_on_one_line, assert_short_list_does_not_scroll, +}; use super::*; use crate::panels::library_panel; use egui::{Event, PointerButton, Pos2, Rect, vec2}; @@ -66,6 +68,20 @@ fn a_long_tracing_preset_list_scrolls_inside_a_short_window() { assert_last_row_scrolls_into_view(&mut app, 200.0, draw, tracing_presets_arrow, &first, "Saved 29"); } +/// The list of presets keeps each name on one line when it scrolls: the scroll bar's column widens +/// the list instead of narrowing the rows. +#[test] +fn a_long_tracing_preset_list_keeps_its_rows_on_one_line() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| trace_button(app, ui, TRACE_BUTTON_W); + for n in 0..30 { + app.session.execute("imageTrace.presets.save", &json!({"name": format!("Saved {n}"), "preset": "Default"})).unwrap(); + } + let presets = app.session.execute("imageTrace.presets", &json!({})).unwrap(); + let names: Vec = presets["presets"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap().to_string()).collect(); + assert_rows_stay_on_one_line(&mut app, draw, tracing_presets_arrow, &names, "Black and White Logo", 120.0); +} + #[test] fn a_large_image_traces_and_the_status_bar_says_it_is_slower() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/script_console.rs b/crates/ui-egui/src/panels/script_console.rs new file mode 100644 index 0000000000..78540b2115 --- /dev/null +++ b/crates/ui-egui/src/panels/script_console.rs @@ -0,0 +1,195 @@ +//! Script Console panel (Window › Script Console): the lines of this session's script runs +//! (`script.console`), each marked with its run's number and its script's name: a start, the +//! script's `$.write` and `$.writeln` output and `vc.log` entries, its uncaught error, an end and a +//! report of its time and host calls. The panel lays out only the rows in view. A click selects a +//! line and Shift-click a range. Clear runs `script.console.clear`; Copy Selected and Copy All run +//! `ui.copyScriptConsole`. Closing the panel only hides it: runs go on writing to the console. + +use egui::{Sense, Ui, vec2}; +use serde_json::{Value, json}; +use vectorcraft_engine::script::console::{Console, ConsoleLine, Ending, Entry}; + +use crate::VectorcraftApp; +use crate::theme::Tokens; + +pub const ID: &str = "scriptConsole"; +/// Panel state: the selected lines, by their numbers ([`Console::first_number`]), first and last. +const SELECTION: &str = "script-console-selection"; +/// Panel state: how many rows the last frame laid out. +pub(crate) const DRAWN: &str = "script-console-drawn"; +const ROW_HEIGHT: f32 = 16.0; + +/// How a run ended, in the UI language. +fn ending_label(e: Ending) -> &'static str { + match e { + Ending::Finished => tl!("Finished"), + Ending::Error => tl!("Ended with an error"), + Ending::Fuel => tl!("Out of fuel"), + Ending::HostLimit => tl!("Ended at a host limit"), + Ending::Limit => tl!("Ended at a limit"), + Ending::Stopped => tl!("Stopped"), + Ending::Internal => tl!("Ended by an internal fault"), + } +} + +/// A line as the panel shows it, in the UI language: its run's number, its script and its text. +pub(crate) fn shown(line: &ConsoleLine) -> String { + let text = match &line.entry { + Entry::Start => "▶".to_string(), + Entry::Output(t) | Entry::Log(t) | Entry::Error(t) => t.clone(), + Entry::End(e) => format!("■ {}", ending_label(*e)), + Entry::Report { ms, host_calls, slowest } => { + let time = ms.map_or_else(|| tl!("time unavailable").to_string(), millis); + let calls = crate::i18n::tn(*host_calls, "{n} host call", "{n} host calls"); + let mut s = crate::i18n::fmt(tl!("{time}, {calls}"), &[("time", &time), ("calls", &calls)]); + if !slowest.is_empty() { + let list: Vec = slowest.iter().map(|c| format!("{} ×{} {}", c.id, c.calls, millis(c.total_ms))).collect(); + s.push_str("; "); + s.push_str(&crate::i18n::fmt(tl!("slowest: {commands}"), &[("commands", &list.join(", "))])); + } + s + } + }; + format!("#{} {}: {}", line.run, line.name, text) +} + +/// A time in milliseconds, in the UI language. +fn millis(ms: u64) -> String { + crate::i18n::fmt(tl!("{ms} ms"), &[("ms", &ms.to_string())]) +} + +/// The notice of the lines the console dropped and cut, or `None` when it has done neither. +fn notice(c: &Console) -> Option { + (c.dropped_lines() > 0 || c.truncated_lines() > 0).then(|| { + let dropped = crate::i18n::tn(c.dropped_lines(), "{n} earlier line dropped", "{n} earlier lines dropped"); + let cut = crate::i18n::tn(c.truncated_lines(), "{n} line cut", "{n} lines cut"); + crate::i18n::fmt(tl!("{dropped}, {cut}"), &[("dropped", &dropped), ("cut", &cut)]) + }) +} + +/// `ui.copyScriptConsole {first?, last?}`: copy the console's lines numbered `first` to `last` +/// (both kept lines; default every line, with the notice of dropped and cut lines first when the +/// console dropped or cut any) to the clipboard, as the panel shows them → `{lines: n}`, where `n` +/// does not count the notice. +pub(crate) fn copy(app: &mut VectorcraftApp, p: &Value) -> Result { + let c = app.session.script_console(); + let start = c.first_number(); + let end = start + c.lines().len() as u64; + let (first, last) = (p.get("first"), p.get("last")); + let mut text: Vec = Vec::new(); + let (from, to) = if first.is_none() && last.is_none() { + text.extend(notice(c)); + (start, end) + } else { + let held = |v: Option<&Value>| v.and_then(Value::as_u64).filter(|n| (start..end).contains(n)); + match (held(first), held(last)) { + (Some(a), Some(b)) if a <= b => (a, b + 1), + _ => return Err("`first` and `last` must be numbers of lines the console holds, first before last".to_string()), + } + }; + let picked = c.lines().iter().skip((from - start) as usize).take((to - from) as usize); + let lines = picked.map(shown).collect::>(); + let n = lines.len(); + text.extend(lines); + app.clipboard_out = Some(text.join("\n")); + Ok(json!({"lines": n})) +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); + let c = app.session.script_console(); + let start = c.first_number(); + let count = c.lines().len(); + let mut selection: Option<(u64, u64)> = super::pstate(ui.ctx(), SELECTION); + // A selection whose lines were dropped or cleared is gone. + if selection.is_some_and(|(a, b)| a < start || b >= start + count as u64) { + selection = None; + } + if let Some(n) = notice(c) { + crate::widgets::dim_label(ui, &n); + } + let mut clicked: Option<(u64, bool)> = None; + let mut drawn = 0usize; + let height = crate::widgets::panel_list_height(ui, 260.0, 0.0); + crate::widgets::list_box(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + egui::ScrollArea::vertical().id_salt("script-console").max_height(height).stick_to_bottom(true).auto_shrink([false, true]).show_rows( + ui, + ROW_HEIGHT, + count, + |ui, range| { + drawn = range.len(); + for (i, line) in c.lines().range(range.clone()).enumerate() { + let number = start + (range.start + i) as u64; + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); + if selection.is_some_and(|(a, b)| (a..=b).contains(&number)) { + ui.painter().rect_filled(r, 0.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover); + } + let color = match line.entry { + Entry::Error(_) => t.error, + Entry::Start | Entry::End(_) | Entry::Report { .. } => t.text_dim, + Entry::Output(_) | Entry::Log(_) => t.text, + }; + let text = shown(line); + ui.painter().with_clip_rect(r).text( + r.left_center() + vec2(4.0, 0.0), + egui::Align2::LEFT_CENTER, + &text, + egui::FontId::monospace(11.5), + color, + ); + let resp = resp.on_hover_text(&text); + if resp.clicked() { + clicked = Some((number, ui.input(|i| i.modifiers.shift))); + } + } + }, + ); + }); + super::set_pstate(ui.ctx(), DRAWN, drawn); + if let Some((number, shift)) = clicked { + selection = Some(match (selection, shift) { + (Some((a, b)), true) => (a.min(number), b.max(number)), + _ => (number, number), + }); + } + super::set_pstate(ui.ctx(), SELECTION, selection); + crate::widgets::bottom_bar(ui, |ui| { + if ui.add_enabled(count > 0, egui::Button::new(tl!("Clear"))).clicked() { + run(app, "script.console.clear", json!({})); + } + if ui.add_enabled(selection.is_some(), egui::Button::new(tl!("Copy Selected"))).clicked() + && let Some((first, last)) = selection + { + run(app, "ui.copyScriptConsole", json!({"first": first, "last": last})); + } + if ui.add_enabled(count > 0, egui::Button::new(tl!("Copy All"))).clicked() { + run(app, "ui.copyScriptConsole", json!({})); + } + }); +} + +/// The panel menu: Clear, Copy Selected and Copy All. +pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { + let count = app.session.script_console().lines().len(); + let selection: Option<(u64, u64)> = super::pstate(ui.ctx(), SELECTION); + if crate::widgets::menu_item(ui, tl!("Clear"), count > 0, false) { + run(app, "script.console.clear", json!({})); + } + if crate::widgets::menu_item(ui, tl!("Copy Selected"), selection.is_some(), false) + && let Some((first, last)) = selection + { + run(app, "ui.copyScriptConsole", json!({"first": first, "last": last})); + } + if crate::widgets::menu_item(ui, tl!("Copy All"), count > 0, false) { + run(app, "ui.copyScriptConsole", json!({})); + } +} + +fn run(app: &mut VectorcraftApp, id: &str, params: Value) { + if let Err(e) = app.run(id, params) { + app.ui.status = e; + } +} diff --git a/crates/ui-egui/src/panels/tests_long_popups.rs b/crates/ui-egui/src/panels/tests_long_popups.rs index 8597ea995f..c562d3540f 100644 --- a/crates/ui-egui/src/panels/tests_long_popups.rs +++ b/crates/ui-egui/src/panels/tests_long_popups.rs @@ -1,4 +1,5 @@ -//! A headless window for checking that a panel's popup with no fixed length stays inside the window. +//! A headless window for checking that a panel's popup with no fixed length stays inside the window, +//! and the tests of menus built on `widgets::menu_scroll` that no panel draws. use egui::{Event, PointerButton, Pos2, Rect, Ui, vec2}; @@ -20,6 +21,7 @@ type Draw<'a> = Box; pub(super) struct PopupWindow<'a> { ctx: egui::Context, time: f64, + width: f32, height: f32, draw: Draw<'a>, texts: Vec<(String, Rect)>, @@ -29,7 +31,7 @@ impl<'a> PopupWindow<'a> { pub(super) fn new(app: &mut VectorcraftApp, height: f32, draw: impl FnMut(&mut VectorcraftApp, &mut Ui) + 'a) -> Self { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); - let mut window = Self { ctx, time: 0.0, height, draw: Box::new(draw), texts: vec![] }; + let mut window = Self { ctx, time: 0.0, width: WIDTH, height, draw: Box::new(draw), texts: vec![] }; window.frames(app, 2); window } @@ -37,7 +39,7 @@ impl<'a> PopupWindow<'a> { /// One frame with `events`. fn frame(&mut self, app: &mut VectorcraftApp, events: Vec) { self.time += 1.0 / 60.0; - let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(WIDTH, self.height))); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, self.height))); let input = egui::RawInput { time: Some(self.time), screen_rect, events, ..Default::default() }; let draw = &mut self.draw; let mut out = self.ctx.run_ui(input, |ui| draw(app, ui)); @@ -45,6 +47,12 @@ impl<'a> PopupWindow<'a> { self.texts = crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()); } + /// Makes the window `width` pt wide and draws the frames that takes. + pub(super) fn resize(&mut self, app: &mut VectorcraftApp, width: f32) { + self.width = width; + self.frames(app, OPEN_FRAMES); + } + fn frames(&mut self, app: &mut VectorcraftApp, count: usize) { for _ in 0..count { self.frame(app, vec![]); @@ -57,6 +65,14 @@ impl<'a> PopupWindow<'a> { self.texts.iter().rfind(|(text, _)| text.trim() == wanted).map(|(_, rect)| *rect) } + /// The rect of the popup drawn on top: the last shown area in the foreground. + pub(super) fn popup(&self) -> Option { + self.ctx.memory(|m| { + let top = m.layer_ids().filter(|layer| layer.order == egui::Order::Foreground && m.areas().is_visible(layer)).last()?; + m.area_rect(top.id) + }) + } + /// The rects of the last frame's clickable widgets `size` across, in the order they were drawn. pub(super) fn clickable(&self, size: egui::Vec2) -> Vec { self.ctx.viewport(|vp| { @@ -80,9 +96,14 @@ impl<'a> PopupWindow<'a> { /// Turns the wheel far down with the pointer at `over`, and lets the scrolling finish. pub(super) fn wheel_down(&mut self, app: &mut VectorcraftApp, over: Pos2) { + self.wheel(app, over, 5000.0); + } + + /// Turns the wheel `down` pt down with the pointer at `over`, and lets the scrolling finish. + pub(super) fn wheel(&mut self, app: &mut VectorcraftApp, over: Pos2, down: f32) { let wheel = Event::MouseWheel { unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, -5000.0), + delta: vec2(0.0, -down), phase: egui::TouchPhase::Move, modifiers: Default::default(), source: egui::MouseWheelSource::Unknown, @@ -92,6 +113,70 @@ impl<'a> PopupWindow<'a> { } } +/// The frames a popup is watched for after it opens. +const STEADY_FRAMES: usize = 12; + +/// In a window `height` pt tall, the popup of the button `pick` finds draws its row `first` at the +/// same place on every frame it is shown, from the click on, inside the window. With the pointer on +/// that row, the row's submenu opens and every text of both stays in place too. Returns where the +/// row is drawn. +pub(super) fn assert_popup_stays_put( + app: &mut VectorcraftApp, + height: f32, + draw: impl FnMut(&mut VectorcraftApp, &mut Ui), + pick: impl FnOnce(&PopupWindow) -> Pos2, + first: &str, +) -> Rect { + let opened = Opened { with: PointerButton::Primary, first, hover: first }; + assert_popup_opened_stays_put(app, height, draw, pick, opened).0 +} + +/// How a popup is opened and checked: the mouse button `with` opens it, `first` is its first row, +/// and the pointer then moves onto the row `hover` to open its submenu. +struct Opened<'s> { + with: PointerButton, + first: &'s str, + hover: &'s str, +} + +/// [`assert_popup_stays_put`] for a popup opened as `opened` says. Returns where the first row is +/// drawn and where every text is drawn with the submenu open. +fn assert_popup_opened_stays_put( + app: &mut VectorcraftApp, + height: f32, + draw: impl FnMut(&mut VectorcraftApp, &mut Ui), + pick: impl FnOnce(&PopupWindow) -> Pos2, + opened: Opened, +) -> (Rect, Vec<(String, Rect)>) { + let Opened { with, first, hover } = opened; + let mut window = PopupWindow::new(app, height, draw); + let at = pick(&window); + let button = |pressed| Event::PointerButton { pos: at, button: with, pressed, modifiers: Default::default() }; + window.frame(app, vec![Event::PointerMoved(at), button(true)]); + window.frame(app, vec![button(false)]); + let mut seen = vec![]; + for _ in 0..STEADY_FRAMES { + seen.extend(window.text(first).map(|row| row.min)); + window.frame(app, vec![]); + } + let row = window.text(first).unwrap_or_else(|| panic!("the popup's first row, {first}")); + seen.push(row.min); + assert!(seen.iter().all(|seen| *seen == row.min), "{first} is drawn at one place on every frame: {seen:?}"); + assert!(row.top() >= 0.0 && row.bottom() <= height, "{first} at {row:?} is inside the {height} pt window"); + let popup_texts = window.texts.clone(); + let over = window.text(hover).unwrap_or_else(|| panic!("the popup's row {hover}")); + window.frame(app, vec![Event::PointerMoved(over.center())]); + window.frames(app, OPEN_FRAMES); + let places = |window: &PopupWindow| window.texts.iter().map(|(text, rect)| (text.clone(), rect.min)).collect::>(); + let shown = places(&window); + assert!(shown.iter().any(|(text, _)| !popup_texts.iter().any(|(old, _)| old == text)), "the pointer on {hover} opens its submenu"); + for _ in 0..STEADY_FRAMES { + window.frame(app, vec![]); + assert_eq!(places(&window), shown, "the popup and its submenu stay in place"); + } + (row, window.texts.clone()) +} + /// The Add Effect popup's first and last rows with no plug-ins: the effect catalog's groups, in order. pub(super) fn fx_menu_ends() -> (String, String) { let mut groups: Vec<&str> = vec![]; @@ -124,6 +209,80 @@ pub(super) fn assert_last_row_scrolls_into_view( assert!(row.bottom() <= height, "{last} at {row:?} is inside the {height} pt window"); } +/// In windows 200, 400 and 900 pt tall, the popup of the button `pick` finds draws each of its rows +/// `rows` that are in view on one line, as tall as the row with the shortest name, and left of the +/// scroll bar's column, whether or not its list scrolls. The row `widest` is drawn the widest; the +/// wheel brings it into view when the popup opens without it. The popup and that row keep their +/// place and size while the popup stays open. After the 200 pt window becomes `narrow` pt wide, +/// the popup and its rows in view stay inside the window. +pub(super) fn assert_rows_stay_on_one_line( + app: &mut VectorcraftApp, + mut draw: impl FnMut(&mut VectorcraftApp, &mut Ui), + pick: impl Fn(&PopupWindow) -> Pos2, + rows: &[String], + widest: &str, + narrow: f32, +) { + let bar = crate::widgets::list_scroll_style().allocated_width(); + let in_view = + |window: &PopupWindow| -> Vec<(String, Rect)> { rows.iter().filter_map(|row| window.text(row).map(|rect| (row.clone(), rect))).collect() }; + let assert_inside = |window: &PopupWindow, drawn: &[(String, Rect)], name: &str| { + let popup = window.popup().unwrap_or_else(|| panic!("the popup is open in the {name} window")); + for (row, rect) in drawn { + assert!( + rect.left() >= popup.left() && rect.right() <= popup.right() - bar, + "{row} at {rect:?} is drawn left of the scroll bar's column in the popup at {popup:?} in the {name} window" + ); + } + popup + }; + for height in [200.0, 400.0, TALL] { + let mut window = PopupWindow::new(app, height, |app, ui| draw(app, ui)); + let button = pick(&window); + window.click(app, button); + for _ in 0..rows.len() { + if window.text(widest).is_some() { + break; + } + let drawn = in_view(&window); + let Some((_, middle)) = drawn.get(drawn.len() / 2) else { break }; + window.wheel(app, middle.center(), 20.0); + } + let opened = window.text(widest).unwrap_or_else(|| panic!("the popup's row {widest} is in view in the {height} pt window")); + let drawn = in_view(&window); + assert!(drawn.len() >= 3, "the popup's rows are in view in the {height} pt window: {drawn:?}"); + let Some((shortest, line)) = drawn.iter().min_by_key(|(row, _)| row.chars().count()) else { panic!("no rows in view") }; + let line = line.height(); + for (row, rect) in &drawn { + assert!( + rect.height() <= line + 0.5, + "{row} at {rect:?} is drawn on one line, as tall as {shortest} ({line} pt), in the {height} pt window" + ); + } + for (row, rect) in &drawn { + assert!(rect.width() <= opened.width() + 0.5, "{widest} is drawn as wide as {row} at {rect:?} or wider in the {height} pt window"); + } + let popup = assert_inside(&window, &drawn, &format!("{height} pt")); + // The popup's size settles within a frame of opening; after that it stays the same. + window.frames(app, 30); + let settled = window.popup(); + assert!( + settled.is_some_and(|settled| (settled.width() - popup.width()).abs() <= 0.5 && settled.min == popup.min), + "the popup at {settled:?} stays where it opened, at {popup:?}, in the {height} pt window" + ); + window.frames(app, 300); + assert_eq!(window.text(widest), Some(opened), "{widest} keeps its place and size while the popup stays open in the {height} pt window"); + assert_eq!(window.popup(), settled, "the popup keeps its place and size while it stays open in the {height} pt window"); + if height == 200.0 { + window.resize(app, narrow); + let drawn = in_view(&window); + assert!(!drawn.is_empty(), "the popup's rows are in view in the {narrow} pt wide window"); + let popup = assert_inside(&window, &drawn, &format!("{narrow} pt wide")); + assert!(popup.left() >= 0.0, "the popup at {popup:?} starts inside the {narrow} pt wide window"); + } + } +} + /// In a tall window the popup of the button `pick` finds shows its rows `first` to `last` without /// scrolling, and the wheel moves neither. pub(super) fn assert_short_list_does_not_scroll( @@ -145,3 +304,111 @@ pub(super) fn assert_short_list_does_not_scroll( window.wheel_down(app, before.0.center()); assert_eq!(shown(&window), before, "a list that fits does not scroll"); } + +/// Rows in each list of [`long_menu`]: more than any window in these tests holds. +const LONG: usize = 40; + +/// A menu of rows `Row 0`, `Row 1`…, each a submenu of as many items. +fn long_menu(ui: &mut Ui) { + menu_of(ui, LONG); +} + +/// A menu of `rows` rows `Row 0`, `Row 1`…, each a submenu of [`LONG`] items. +fn menu_of(ui: &mut Ui, rows: usize) { + crate::widgets::menu_scroll(ui, |ui| { + for row in 0..rows { + ui.menu_button(format!("Row {row}"), |ui| { + crate::widgets::menu_scroll(ui, |ui| { + for item in 0..LONG { + let _ = ui.button(format!("Item {row}.{item}")); + } + }) + }); + } + }); +} + +/// A blank document, for windows that draw no panel. +fn app() -> VectorcraftApp { + VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()) +} + +/// A long menu opened from a button `y` pt down a window stays at one place on every frame, and so +/// does its submenu, whether it opens below the button, above it, or in a window shorter than it. +#[test] +fn a_long_menu_stays_put_wherever_its_button_is() { + for height in [160.0, 300.0, 600.0] { + for y in [4.0, height / 2.0 - 12.0, height - 28.0] { + let draw = move |_: &mut VectorcraftApp, ui: &mut Ui| { + ui.add_space(y); + let button = ui.button("Open"); + egui::Popup::menu(&button).show(long_menu); + }; + let open = |window: &PopupWindow| window.text("Open").expect("the button").center(); + assert_popup_stays_put(&mut app(), height, draw, open, "Row 0"); + } + } +} + +/// A long context menu opened near the top, the middle or the bottom of a short window stays at +/// one place on every frame, and so does its submenu. +#[test] +fn a_long_context_menu_stays_put_wherever_it_opens() { + for height in [160.0, 300.0, 600.0] { + for y in [4.0, height / 2.0, height - 4.0] { + let draw = |_: &mut VectorcraftApp, ui: &mut Ui| { + let area = ui.interact(ui.max_rect(), egui::Id::unique("context-area"), egui::Sense::click()); + area.context_menu(long_menu); + }; + let at = move |_: &PopupWindow| Pos2::new(20.0, y); + let opened = Opened { with: PointerButton::Secondary, first: "Row 0", hover: "Row 0" }; + assert_popup_opened_stays_put(&mut app(), height, draw, at, opened); + } + } +} + +/// The long submenu of a row near the top of a window opens down from the row's top, and its list +/// reaches down to the window's bottom less the menu gap. +#[test] +fn a_long_submenu_of_a_high_row_reaches_down_to_the_window_bottom() { + for height in [300.0, 600.0] { + let draw = |_: &mut VectorcraftApp, ui: &mut Ui| { + ui.add_space(4.0); + let button = ui.button("Open"); + egui::Popup::menu(&button).show(|ui| menu_of(ui, 6)); + }; + let open = |window: &PopupWindow| window.text("Open").expect("the button").center(); + let mut app = app(); + let mut window = PopupWindow::new(&mut app, height, draw); + let at = open(&window); + window.click(&mut app, at); + let row = window.text("Row 0").expect("the menu's first row"); + window.frame(&mut app, vec![Event::PointerMoved(row.center())]); + window.frames(&mut app, OPEN_FRAMES); + let item = window.text("Item 0.0").expect("the submenu's first item"); + let areas = window.ctx.memory(|m| m.layer_ids().filter_map(|layer| m.area_rect(layer.id)).collect::>()); + let submenu = areas.into_iter().filter(|rect| rect.contains(item.center())).min_by(|a, b| a.area().total_cmp(&b.area())); + let submenu = submenu.expect("the submenu's area"); + assert!(item.top() < row.bottom(), "the submenu opens down from {row:?}: {item:?}"); + assert!((height - 12.0..=height).contains(&submenu.bottom()), "in a {height} pt window the submenu reaches its bottom: {submenu:?}"); + } +} + +/// The submenu of a row near the bottom of a window opens up from the row and stays at one place +/// on every frame. +#[test] +fn a_long_submenu_of_a_low_row_opens_up_and_stays_put() { + for height in [300.0, 600.0] { + let draw = move |_: &mut VectorcraftApp, ui: &mut Ui| { + ui.add_space(height - 28.0); + let button = ui.button("Open"); + egui::Popup::menu(&button).show(|ui| menu_of(ui, 6)); + }; + let open = |window: &PopupWindow| window.text("Open").expect("the button").center(); + let opened = Opened { with: PointerButton::Primary, first: "Row 0", hover: "Row 5" }; + let (_, texts) = assert_popup_opened_stays_put(&mut app(), height, draw, open, opened); + let at = |wanted: &str| texts.iter().rfind(|(text, _)| text.trim() == wanted).map(|(_, rect)| *rect); + let (row, item) = (at("Row 5").expect("the row"), at("Item 5.0").expect("the submenu's first item")); + assert!(item.top() < row.top() - 100.0, "in a {height} pt window the submenu opens up from {row:?}: {item:?}"); + } +} diff --git a/crates/ui-egui/src/panels/tests_script_console.rs b/crates/ui-egui/src/panels/tests_script_console.rs new file mode 100644 index 0000000000..c1fbcc4da9 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_script_console.rs @@ -0,0 +1,143 @@ +//! The Script Console panel drawn headless: a full console lays out only the rows in view, output +//! goes on while the panel is hidden, Clear works during a run, and Copy Selected and Copy All +//! through `ui.copyScriptConsole`. + +use serde_json::json; +use vectorcraft_engine::Session; + +use super::pstate; +use super::script_console::{DRAWN, ID, show, shown}; +use crate::tests_labels::painted_text; +use crate::{Services, VectorcraftApp, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({})).unwrap(); + app +} + +/// Runs `source` to its end, a frame at a time, as the app does. +fn run(app: &mut VectorcraftApp, source: &str) { + app.session.script_frames = true; + app.run("script.run", json!({"source": source, "name": "c.js"})).unwrap(); + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + script_runs::poll(app); + } + panic!("the script did not end"); +} + +#[test] +fn a_full_console_lays_out_only_the_rows_in_view() { + let mut app = app(); + run(&mut app, "for (var i = 0; i < 3000; i++) $.writeln('line ' + i)"); + assert_eq!(app.session.script_console().lines().len(), vectorcraft_engine::script::console::MAX_CONSOLE_LINES); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut drawn = 0; + for _ in 0..2 { + ctx.run_ui(egui::RawInput::default(), |ui| { + show(&mut app, ui); + drawn = pstate::(ui.ctx(), DRAWN); + }) + .textures_delta + .clear(); + } + assert!(drawn > 0 && drawn < 40, "{drawn} rows laid out"); + let text = painted_text(&mut app, show); + assert!(text.contains("#1 c.js: line 2999"), "the newest line is in view: {text}"); + assert!(text.contains("lines dropped"), "the panel says lines were dropped: {text}"); +} + +#[test] +fn output_goes_on_while_the_panel_is_hidden_and_shows_when_it_opens() { + let mut app = app(); + assert!(crate::state::rail_panel(ID).is_some()); + run(&mut app, "$.writeln('hidden'); vc.log({n: 1}); throw new Error('late')"); + app.run("window.panel", json!({"panel": ID})).unwrap(); + let text = painted_text(&mut app, show); + for want in ["#1 c.js: ▶", "#1 c.js: hidden", "#1 c.js: {\"n\":1}", "#1 c.js: c.js:1:", "#1 c.js: ■ Ended with an error", "host calls"] { + assert!(text.contains(want), "{want} in {text}"); + } +} + +#[test] +fn clear_works_during_a_run_and_the_run_goes_on_writing() { + let mut app = app(); + app.session.script_frames = true; + app.run("script.run", json!({"source": "$.writeln('before'); while (true) {}", "name": "c.js"})).unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_running()); + assert_eq!(app.run("script.console.clear", json!({})).unwrap()["cleared"], 2); + app.run("script.stop", json!({})).unwrap(); + script_runs::poll(&mut app); + assert!(!app.session.script_running()); + let text = painted_text(&mut app, show); + assert!(!text.contains("before") && text.contains("■ Stopped"), "{text}"); +} + +#[test] +fn copy_all_and_copy_selected_put_the_lines_on_the_clipboard() { + let mut app = app(); + run(&mut app, "$.writeln('one'); $.writeln('two'); $.writeln('three')"); + assert_eq!(app.run("ui.copyScriptConsole", json!({})).unwrap()["lines"], 6); + let all = app.clipboard_out.take().unwrap(); + assert!(all.starts_with("#1 c.js: ▶\n#1 c.js: one\n#1 c.js: two\n"), "{all}"); + assert_eq!(app.run("ui.copyScriptConsole", json!({"first": 2, "last": 3})).unwrap()["lines"], 2); + assert_eq!(app.clipboard_out.take().as_deref(), Some("#1 c.js: two\n#1 c.js: three")); + for bad in [json!({"first": 3, "last": 2}), json!({"first": 1}), json!({"first": 0, "last": 99}), json!({"first": "1", "last": 2})] { + assert!(app.run("ui.copyScriptConsole", bad.clone()).is_err(), "{bad}"); + } + assert!(app.clipboard_out.is_none(), "a refused copy copies nothing"); + run(&mut app, "for (var i = 0; i < 2100; i++) $.writeln(i)"); + app.run("ui.copyScriptConsole", json!({})).unwrap(); + let all = app.clipboard_out.take().unwrap(); + assert!(all.lines().next().is_some_and(|l| l.contains("lines dropped")), "Copy All starts with the notice: {}", &all[..80]); +} + +/// A report line reads in English as `script.console` gives it: "time unavailable" for a run +/// without a clock, one host call in the singular, and the slowest commands. +#[test] +fn a_report_line_reads_as_script_console_gives_it() { + use vectorcraft_engine::script::console::{ConsoleLine, Entry, Slow}; + let slow = vec![Slow { id: "a.b".into(), calls: 2, total_ms: 7, max_ms: 4 }, Slow { id: "c".into(), calls: 1, total_ms: 1, max_ms: 1 }]; + for ms in [None, Some(0), Some(12)] { + for host_calls in [0, 1, 2] { + for slowest in [vec![], slow.clone()] { + let entry = Entry::Report { ms, host_calls, slowest }; + let want = format!("#3 c.js: {}", entry.text()); + assert_eq!(shown(&ConsoleLine { run: 3, name: "c.js".into(), entry }), want); + } + } + } + let line = |ms, host_calls| shown(&ConsoleLine { run: 1, name: "c.js".into(), entry: Entry::Report { ms, host_calls, slowest: vec![] } }); + assert_eq!(line(None, 1), "#1 c.js: time unavailable, 1 host call"); + assert_eq!(line(Some(0), 2), "#1 c.js: 0 ms, 2 host calls"); +} + +/// The notice counts the lines dropped and the lines cut each in its own form, a count of one in +/// the singular; Copy All starts with it. +#[test] +fn the_notice_counts_one_line_in_the_singular() { + for (dropped, cut, want) in [ + (1, 0, "1 earlier line dropped, 0 lines cut"), + (0, 1, "0 earlier lines dropped, 1 line cut"), + (1, 2, "1 earlier line dropped, 2 lines cut"), + (2, 1, "2 earlier lines dropped, 1 line cut"), + (2, 2, "2 earlier lines dropped, 2 lines cut"), + ] { + let mut app = app(); + // A run adds a start, an end and a report line to its output lines. + let lines = if dropped > 0 { vectorcraft_engine::script::console::MAX_CONSOLE_LINES - 3 + dropped } else { cut + 1 }; + let source = format!("var big = 'x'; while (big.length < 5000) big += big; for (var i = 0; i < {lines}; i++) $.writeln(i < {cut} ? big : i)"); + run(&mut app, &source); + let c = app.session.script_console(); + assert_eq!((c.dropped_lines(), c.truncated_lines()), (dropped as u64, cut as u64)); + app.run("ui.copyScriptConsole", json!({})).unwrap(); + let all = app.clipboard_out.take().unwrap(); + assert_eq!(all.lines().next(), Some(want)); + assert!(painted_text(&mut app, show).contains(want)); + } +} diff --git a/crates/ui-egui/src/panels/tests_symbol_libraries.rs b/crates/ui-egui/src/panels/tests_symbol_libraries.rs index 7dee49df2b..a6c1cb4cb5 100644 --- a/crates/ui-egui/src/panels/tests_symbol_libraries.rs +++ b/crates/ui-egui/src/panels/tests_symbol_libraries.rs @@ -113,7 +113,7 @@ fn the_window_menu_and_the_symbols_panel_open_symbol_libraries() { let under = |e: &crate::menus::MenuEntry| e.path == ["Window", "Symbol Libraries"]; let opened: Vec<_> = entries.iter().filter(|e| under(e) && e.command.as_deref() == Some("window.symbolLibrary")).map(|e| e.params["library"].clone()).collect(); - assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames"), json!("map-markers")]); + assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames"), json!("map-markers"), json!("inventory-icons")]); let has = |cmd: &str| entries.iter().find(|e| under(e) && e.command.as_deref() == Some(cmd)).map(|e| e.enabled); assert_eq!(has("window.symbolLibrary.other"), Some(true)); assert_eq!(has("ui.saveSymbolLibrary"), Some(false), "no symbols to save yet"); diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index fad2d45e7a..c9662109ad 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -19,6 +19,9 @@ pub const UI_FIELDS: &[(&str, &str, &str)] = &[ ("__taskBar", "General", "Enable Contextual Task Bar"), ]; +/// The Units ▸ General value Reset Preferences put in the dialog, while it is still the field's value. +const RESET_UNITS: &str = "__resetUnits"; + /// Whether User Interface shows VectorCraft Title Bar on Every Desktop (`appTitleBar`): Linux and the /// BSDs, where the desktop may draw the window's frame. macOS and Windows never read it. const APP_TITLE_BAR_SHOWN: bool = cfg!(not(any(target_arch = "wasm32", target_os = "macos", target_os = "windows"))); @@ -194,12 +197,21 @@ fn found_paint(ui: &mut egui::Ui, d: &mut Dialog, mark: Option<(egui::layers::Sh } } +/// `field` of the Preferences dialog `d` is about to be `value` (a frame's edit or `ui.dialog.set`): +/// choosing another General unit after Reset Preferences makes OK set the document's units again. +pub(crate) fn note_set(d: &mut Dialog, field: &str, value: &Value) { + if field == "unitsGeneral" && d.fields.get(RESET_UNITS).is_some_and(|v| v != value) { + d.fields.remove(RESET_UNITS); + } +} + /// OK: validate and apply every preference in the dialog (nothing changes on error). pub fn confirm(app: &mut VectorcraftApp) -> Result { let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); - app.run("prefs.set", json!({ "values": values }))?; + let document_units = d.fields.get(RESET_UNITS).is_none_or(|v| values.get("unitsGeneral") != Some(v)); + app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?; if touch_ws.is_some() { crate::workspaces::sync_touch_workspace(app, app.touch_screen); } @@ -388,6 +400,21 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); }); ui.add_space(14.0); + ui.horizontal(|ui| { + if widgets::secondary_button(ui, tl!("Export Preferences…")).on_hover_text(tl!("Save the applied preferences to a JSON file")).clicked() + { + export_preferences(app, &mut d); + } + // Not on the web, which has no open dialog that returns a file here. + if crate::picks::can(app, &crate::picks::PickRequest::Open(crate::FilePick::default())) + && widgets::secondary_button(ui, tl!("Import Preferences…")) + .on_hover_text(tl!("Apply the preferences in a file Export Preferences saved")) + .clicked() + { + import_preferences(app, &mut d); + } + }); + ui.add_space(8.0); ui.horizontal(|ui| { if widgets::secondary_button(ui, tl!("Reset Preferences")) .on_hover_text(tl!("Restore every preference to its default (applied on OK)")) @@ -414,10 +441,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); }); }); - if reset { - for (k, v) in Prefs::default().to_json().as_object().cloned().unwrap_or_default() { - d.fields.insert(k, v); - } + if let Some(v) = d.fields.get("unitsGeneral").cloned() { + note_set(&mut d, "unitsGeneral", &v); } // The setting a search went to stays highlighted until another category is shown. let found = d.str("__found"); @@ -430,9 +455,23 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { app.ui.dialog = None; } else if ok && let Err(e) = confirm(app) { app.status(e); + } else if reset && !ok { + crate::dialogs::confirm::ask_reset_prefs(app); } } +/// Reset Preferences, once its question is confirmed: every preference in the Preferences dialog +/// `d` takes its default value. The category, the search and the UI-only rows stay as they were; +/// nothing is applied until OK, which leaves the open document's units alone unless Units › +/// General is changed after the reset. +pub(crate) fn reset_fields(d: &mut Dialog) { + for (k, v) in Prefs::default().to_json().as_object().cloned().unwrap_or_default() { + d.fields.insert(k, v); + } + // OK resets the Units ▸ General preference and leaves the open document's units alone. + d.fields.insert(RESET_UNITS.into(), d.fields.get("unitsGeneral").cloned().unwrap_or(Value::Null)); +} + fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, cat: &str) { let t = Tokens::get(ui.ctx()); let mut section = ""; @@ -647,6 +686,67 @@ fn choose_folder(app: &mut VectorcraftApp, d: &mut Dialog, key: &'static str) { } } +/// The file name Export Preferences… suggests. +const PREFS_FILE_NAME: &str = "VectorCraft Preferences.json"; + +/// Export Preferences…: the applied preferences (`prefs.export`) go to a file picked in a save +/// dialog (the web downloads it). Changes in the dialog not yet applied with OK are not in it. +fn export_preferences(app: &mut VectorcraftApp, d: &mut Dialog) { + let r = + crate::picks::in_app_dialog(app, d, |app, _| crate::io::save_command_output_named(app, "prefs.export", PREFS_FILE_NAME, json!({})).map(drop)); + if let Err(e) = r + && e != "cancelled" + { + app.status(e); + } +} + +/// Import Preferences…: the preferences in a file picked in an open dialog are applied +/// (`prefs.import`), and the dialog shows them. On an error nothing changes and the status bar +/// says why. +fn import_preferences(app: &mut VectorcraftApp, d: &mut Dialog) { + let r = crate::picks::in_app_dialog(app, d, |app, d| { + let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Preferences", &["json"])], ..Default::default() }; + let Some(path) = crate::picks::open(app, &pick) else { return Ok(()) }; + app.run("prefs.import", json!({ "path": path }))?; + show_prefs(d, &app.session.prefs.to_json()); + app.status("Preferences imported."); + Ok(()) + }); + if let Err(e) = r { + app.status(e); + } +} + +/// After `prefs.import`: the preferences are saved with the UI state, Enable Touch Workspace takes +/// effect when the import changed it from `touch_workspace`, and an open Preferences dialog shows +/// the imported values. +pub(crate) fn imported(app: &mut VectorcraftApp, touch_workspace: bool) { + snapshot(app); + app.prefs_changed = true; + if app.session.prefs.touch_workspace != touch_workspace { + crate::workspaces::sync_touch_workspace(app, app.touch_screen); + } + let prefs = app.session.prefs.to_json(); + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == "preferences") { + show_prefs(d, &prefs); + } +} + +/// The Preferences dialog `d` shows the preferences `prefs` in place of its working copy. Units › +/// General shows the preference, and OK then leaves the open document's units alone unless the +/// field is changed. +fn show_prefs(d: &mut Dialog, prefs: &Value) { + for (k, v) in prefs.as_object().into_iter().flatten() { + if d.fields.contains_key(k) { + d.fields.insert(k.clone(), v.clone()); + } + } + if let Some(v) = d.fields.get("unitsGeneral").cloned() { + d.fields.insert(RESET_UNITS.into(), v); + } +} + /// Is one of the dialog's Units (General, Stroke, Type, East Asian Type) Picas? fn picas_in_use(d: &Dialog) -> bool { ["unitsGeneral", "unitsStroke", "unitsType", "unitsAsianType"].iter().any(|k| d.str(k) == vectorcraft_doc::Unit::Picas.key()) diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 93b84f488d..95fa8085fd 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -273,6 +273,110 @@ fn preferences_ok_changes_the_guide_lock_only_with_the_option() { assert!(!a.session.guides_locked(), "the option went off"); } +/// Click the Preferences dialog's button `label` with the pointer. +fn click_button(app: &mut VectorcraftApp, label: &str) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, events: Vec| { + // A window takes a sizing frame and fades in: each frame is a quarter second on. + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), egui::Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v + }; + frame(app, vec![]); + let texts = frame(app, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![press(true)]); + frame(app, vec![press(false)]); +} + +/// Click Reset Preferences and answer its question with OK: Preferences again, its working copy +/// at the defaults. +fn reset_preferences(app: &mut VectorcraftApp) { + click_button(app, "Reset Preferences"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::confirm::RESET_PREFS)); + crate::dialogs::confirm(app).unwrap(); +} + +/// Reset Preferences then OK resets the preferences, General included, and leaves the open +/// document's units, with no undo step in the document. +#[test] +fn reset_preferences_then_ok_leaves_the_documents_units() { + let mut a = app(); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + a.run("document.setUnits", json!({"units": "Millimeters"})).unwrap(); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 5})).unwrap(); + let undo = a.session.active().unwrap().history.undo.len(); + open(&mut a, Some("General")); + reset_preferences(&mut a); + let d = a.ui.dialog.as_ref().expect("Reset leaves the dialog open"); + assert_eq!(d.fields["keyboardIncrement"], Prefs::default().to_json()["keyboardIncrement"], "the working copy holds the defaults"); + assert_eq!(d.fields["unitsGeneral"], json!("points")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.keyboard_increment, Prefs::default().keyboard_increment); + assert_eq!(a.session.prefs.units_general, Prefs::default().units_general); + let st = a.session.active().unwrap(); + assert_eq!(st.doc.units, vectorcraft_doc::Unit::Millimeters); + assert_eq!(st.history.undo.len(), undo, "no undo step"); +} + +/// After Reset Preferences, choosing a General unit in the dialog still sets the document's units +/// on OK, Points included once another unit was chosen in between. With no document open, Reset +/// Preferences resets General to its default. +#[test] +fn reset_preferences_keeps_an_edit_of_general_units() { + let mut a = app(); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + a.run("document.setUnits", json!({"units": "Millimeters"})).unwrap(); + open(&mut a, Some("General")); + reset_preferences(&mut a); + a.ui.dialog.as_mut().unwrap().fields.insert("unitsGeneral".into(), json!("inches")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.active().unwrap().doc.units, vectorcraft_doc::Unit::Inches); + assert_eq!(a.session.prefs.units_general, "inches"); + + // Between frames, as `ui.dialog.set` sets fields. + a.run("document.setUnits", json!({"units": "Millimeters"})).unwrap(); + open(&mut a, Some("General")); + reset_preferences(&mut a); + for u in ["inches", "points"] { + crate::dialogs::set_field(a.ui.dialog.as_mut().unwrap(), "unitsGeneral".into(), json!(u)); + } + confirm(&mut a).unwrap(); + assert_eq!(a.session.active().unwrap().doc.units, vectorcraft_doc::Unit::Points); + + // Through a frame of the dialog. + a.run("document.setUnits", json!({"units": "Millimeters"})).unwrap(); + open(&mut a, Some("General")); + reset_preferences(&mut a); + a.ui.dialog.as_mut().unwrap().fields.insert("unitsGeneral".into(), json!("inches")); + click_button(&mut a, "General"); + a.ui.dialog.as_mut().unwrap().fields.insert("unitsGeneral".into(), json!("points")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.active().unwrap().doc.units, vectorcraft_doc::Unit::Points); + + let mut b = app(); + b.run("prefs.set", json!({"key": "unitsGeneral", "value": "Millimeters"})).unwrap(); + open(&mut b, Some("General")); + reset_preferences(&mut b); + confirm(&mut b).unwrap(); + assert_eq!(b.session.prefs.units_general, Prefs::default().units_general); +} + #[test] fn old_pref_files_keep_their_brightness() { let mut a = app(); @@ -690,6 +794,111 @@ fn escape_clears_the_search_then_closes_the_dialog() { assert!(a.ui.dialog.is_none(), "Escape in the empty field closes the dialog"); } +/// One frame of the open dialog as the app draws it, keys first, a quarter second after the last +/// (a window takes a sizing frame and fades in). → The texts it painted, with their rectangles. +fn dialog_frame(a: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, egui::Rect)> { + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + crate::shortcuts::handle(a, ui.ctx()); + crate::dialogs::show(a, ui.ctx()); + }); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), egui::Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v +} + +/// Click the text `label` in the open dialog with the pointer. +fn click_text(a: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + dialog_frame(a, ctx, vec![]); + let texts = dialog_frame(a, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(a, ctx, vec![egui::Event::PointerMoved(at)]); + dialog_frame(a, ctx, vec![press(true)]); + dialog_frame(a, ctx, vec![press(false)]); +} + +/// Preferences with an edited Keyboard Increment, the Units category and a search, over a stored +/// Keyboard Increment of 5. +fn edited_preferences() -> VectorcraftApp { + let mut a = app(); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 5})).unwrap(); + open(&mut a, Some("Units")); + let d = a.ui.dialog.as_mut().unwrap(); + d.fields.insert("keyboardIncrement".into(), json!(7)); + d.fields.insert("__search".into(), json!("grid")); + a +} + +/// Reset Preferences asks first, over Preferences. Escape, or Cancel, shows Preferences again as it +/// was: its edits, category and search kept, and nothing applied. +#[test] +fn reset_preferences_asks_first_and_cancel_returns_to_preferences() { + let mut a = edited_preferences(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for way_back in ["Escape", "Cancel"] { + click_text(&mut a, &ctx, "Reset Preferences"); + let d = a.ui.dialog.clone().expect("a question is open"); + assert_eq!(d.kind, crate::dialogs::confirm::RESET_PREFS, "Reset Preferences asks first"); + let under = crate::dialogs::parent(&d).expect("the question is over Preferences"); + assert_eq!((under.kind.as_str(), under.fields["keyboardIncrement"].clone()), ("preferences", json!(7)), "Preferences is unchanged"); + dialog_frame(&mut a, &ctx, vec![]); + let shown: Vec = dialog_frame(&mut a, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(shown.iter().any(|t| t == "Reset all preferences to their defaults?"), "{shown:?}"); + if way_back == "Escape" { + dialog_frame(&mut a, &ctx, key_press(egui::Key::Escape, egui::Modifiers::NONE)); + } else { + click_text(&mut a, &ctx, "Cancel"); + } + let d = a.ui.dialog.as_ref().unwrap_or_else(|| panic!("{way_back}: Preferences is open again")); + assert_eq!(d.kind, "preferences", "{way_back}"); + assert_eq!(d.fields["keyboardIncrement"], json!(7), "{way_back}: the edit is kept"); + assert_eq!((d.str("__category").as_str(), d.str("__search").as_str()), ("Units", "grid"), "{way_back}: category and search kept"); + assert_eq!(a.session.prefs.keyboard_increment, 5.0, "{way_back}: nothing applied"); + } +} + +/// OK on the question shows Preferences again with every preference at its default, its category +/// and search kept; nothing is applied until OK in Preferences, and Preferences' Cancel keeps the +/// stored preferences. +#[test] +fn confirming_reset_fills_preferences_and_applies_nothing_until_ok() { + let mut a = edited_preferences(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let default = Prefs::default().to_json()["keyboardIncrement"].clone(); + click_text(&mut a, &ctx, "Reset Preferences"); + click_text(&mut a, &ctx, "OK"); + let d = a.ui.dialog.as_ref().expect("Preferences is open again"); + assert_eq!(d.kind, "preferences"); + assert_eq!(d.fields["keyboardIncrement"], default, "the working copy holds the defaults"); + assert_eq!((d.str("__category").as_str(), d.str("__search").as_str()), ("Units", "grid")); + assert_eq!(a.session.prefs.keyboard_increment, 5.0, "nothing applied yet"); + click_text(&mut a, &ctx, "Cancel"); + assert!(a.ui.dialog.is_none()); + assert_eq!(a.session.prefs.keyboard_increment, 5.0, "Cancel in Preferences keeps the preferences"); + + // `ui.dialog.confirm` answers the question as OK does; OK in Preferences then applies the defaults. + let mut a = edited_preferences(); + click_text(&mut a, &ctx, "Reset Preferences"); + crate::dialogs::confirm(&mut a).unwrap(); + assert_eq!(a.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("preferences")); + crate::dialogs::confirm(&mut a).unwrap(); + assert!(a.ui.dialog.is_none()); + assert_eq!(a.session.prefs.keyboard_increment, Prefs::default().keyboard_increment); +} + /// Units › Numbers Without Units Are Points (#394): the preference reaches the fields when it /// changes, and its checkbox is dimmed unless a unit is Picas. #[test] @@ -834,6 +1043,105 @@ fn temp_folder(name: &str) -> std::path::PathBuf { dir } +/// An app whose save and open dialogs answer `path`, and that writes and reads real files. +fn app_with_file_dialogs(path: &str) -> VectorcraftApp { + let mut a = app(); + let (save, open) = (path.to_string(), path.to_string()); + a.services.pick_save = Some(Box::new(move |_: &crate::FilePick| Some(save.clone()))); + a.services.pick_open = Some(Box::new(move |_: &crate::FilePick| Some(open.clone()))); + a.services.write = Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))); + a.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + a +} + +/// Export Preferences… saves the applied preferences to a file, and Import Preferences… applies +/// them again: the dialog shows them, OK keeps them, and the open document's units stay as they +/// are. +#[test] +fn export_and_import_preferences_buttons_round_trip() { + let dir = temp_folder("prefs-file"); + let path = dir.join("VectorCraft Preferences.json").to_string_lossy().into_owned(); + let mut a = app_with_file_dialogs(&path); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + a.run("document.setUnits", json!({"units": "Millimeters"})).unwrap(); + let values = json!({"keyboardIncrement": 5, "uiAccent": "green", "unitsGeneral": "inches"}); + a.run("prefs.set", json!({"values": values, "documentUnits": false})).unwrap(); + let saved = a.session.prefs.to_json(); + open(&mut a, Some("General")); + click_button(&mut a, "Export Preferences…"); + let file: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(file["format"], "vectorcraft-preferences"); + assert_eq!(file["prefs"]["uiAccent"], "green"); + + a.ui.dialog = None; + a.run("prefs.reset", json!({})).unwrap(); + let undo = a.session.active().unwrap().history.undo.len(); + open(&mut a, Some("General")); + a.ui.dialog.as_mut().unwrap().fields.insert("keyboardIncrement".into(), json!(9)); + click_button(&mut a, "Import Preferences…"); + assert_eq!(a.ui.status, "Preferences imported."); + assert_eq!(a.session.prefs.to_json(), saved, "the exported preferences are applied"); + assert_eq!(a.ui.engine_prefs, saved, "and saved with the UI state"); + let d = a.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!((d.fields["keyboardIncrement"].clone(), d.fields["unitsGeneral"].clone()), (json!(5.0), json!("inches")), "the dialog shows them"); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json(), saved); + let st = a.session.active().unwrap(); + assert_eq!(st.doc.units, vectorcraft_doc::Unit::Millimeters, "the document's units stay"); + assert_eq!(st.history.undo.len(), undo, "no undo step"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file Import Preferences… can't use changes nothing, the dialog's edits included, and the +/// status bar says why. +#[test] +fn import_preferences_of_a_bad_file_changes_nothing() { + let dir = temp_folder("prefs-bad-file"); + let path = dir.join("newer.json"); + std::fs::write(&path, r#"{"format": "vectorcraft-preferences", "version": 2, "prefs": {"uiAccent": "pink"}}"#).unwrap(); + let mut a = app_with_file_dialogs(&path.to_string_lossy()); + let before = a.session.prefs.to_json(); + open(&mut a, Some("General")); + a.ui.dialog.as_mut().unwrap().fields.insert("keyboardIncrement".into(), json!(9)); + click_button(&mut a, "Import Preferences…"); + assert!(a.ui.status.contains("newer version of VectorCraft"), "{}", a.ui.status); + assert_eq!(a.session.prefs.to_json(), before); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields["keyboardIncrement"], json!(9), "the dialog keeps its edits"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `prefs.import` from a script or MCP while Preferences is open: the dialog shows the imported +/// values. Import Preferences… shows only where the host has an open dialog (not on the web). +#[test] +fn prefs_import_refreshes_an_open_preferences_dialog() { + let mut a = app(); + open(&mut a, Some("General")); + let data = json!({"format": "vectorcraft-preferences", "version": 1, "prefs": {"keyboardIncrement": 7}}).to_string(); + a.run("prefs.import", json!({ "data": data })).unwrap(); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields["keyboardIncrement"], json!(7.0)); + assert_eq!(a.ui.engine_prefs["keyboardIncrement"], json!(7.0)); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Export Preferences…") && !text.contains("Import Preferences…"), "{text}"); + a.services.pick_open = Some(Box::new(|_: &crate::FilePick| None)); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Import Preferences…"), "{text}"); +} + +/// An import that turns Enable Touch Workspace on or off switches the workspace on a touch screen, +/// as OK in Preferences does. +#[test] +fn prefs_import_of_touch_workspace_switches_the_workspace() { + let mut a = app(); + a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap(); + a.touch_screen = true; + a.ui.workspace = "Typography".into(); + let file = |on: bool| json!({"format": "vectorcraft-preferences", "version": 1, "prefs": {"touchWorkspace": on}}).to_string(); + a.run("prefs.import", json!({ "data": file(true) })).unwrap(); + assert_eq!(a.ui.workspace, crate::workspaces::TOUCH); + a.run("prefs.import", json!({ "data": file(false) })).unwrap(); + assert_eq!(a.ui.workspace, "Typography"); +} + /// File Handling › Data Recovery › Folder has a Choose… button where the host has a folder /// picker, and none where it has not (the web). #[test] diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index bf764e0e4b..40478e36ed 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -24,6 +24,9 @@ pub struct Job { /// The automation roots in force where the job was made: the render reads linked files under /// them, as it would on that thread. pub scope: ScopeHandle, + /// The document's deferred live-effect plug-in stages and first-view budget: the render runs + /// inside their view ([`vectorcraft_plugins::deferred::Deferrals::view`]). + pub effects: vectorcraft_plugins::deferred::Deferrals, /// The render may copy pixels from the worker's last frame ([`crate::canvas::render_job`]). /// Off: it renders the whole frame. pub may_copy: bool, @@ -71,7 +74,7 @@ impl Worker { job = newer; } let t0 = crate::now_ms(); - let frame = job.scope.clone().run(|| crate::canvas::render_job(&mut r, &mut kept, &job)); + let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(&mut r, &mut kept, &job))); let ms = crate::now_ms() - t0; let done = Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused }; if done_tx.send(done).is_err() { diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 042e24cd31..02c2229741 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,6 +1,7 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar -//! shows it with a Stop button; a run that has added a great deal waits for the person's answer. +//! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with +//! `alert`, `confirm` or `prompt`, waits for the person's answer. use serde_json::json; @@ -14,21 +15,24 @@ pub fn poll(app: &mut VectorcraftApp) { if !app.session.script_running() { return; } - if app.session.script_waiting() { - if app.ui.dialog.is_none() { - app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); - } + script_run::settle_close(app); + if ask(app) { return; } let name = app.session.script_name().unwrap_or_default(); let cursor_settings = (app.session.caps_lock, app.session.prefs.use_precise_cursors); - let Some(result) = app.session.script_pump() else { return }; + let Some(result) = app.session.script_pump() else { + // The app draws no more frames while the run waits: its question opens in this one. + ask(app); + return; + }; if cursor_settings != (app.session.caps_lock, app.session.prefs.use_precise_cursors) { app.canvas.hover_cursor = None; } if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND) { app.ui.dialog = None; } + script_run::settle_close(app); match result { Ok(_) => app.status(format!("Ran {name}")), Err(e) => failed(app, e.to_string()), @@ -36,6 +40,29 @@ pub fn poll(app: &mut VectorcraftApp) { app.sync_views(); } +/// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the +/// question about its growth. Closes the script's dialog when the run no longer waits at it. +/// → true while the run waits. +fn ask(app: &mut VectorcraftApp) -> bool { + if let Some(dialog) = app.session.script_dialog() { + if app.ui.dialog.is_none() { + script_run::open_notice(app, &dialog); + } + return true; + } + // A run asked to stop no longer waits at its dialog. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::NOTICE_KIND) { + app.ui.dialog = None; + } + if app.session.script_waiting() { + if app.ui.dialog.is_none() { + app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); + } + return true; + } + false +} + /// Shows why a run ended without its changes. A stopped run that wrote no file says only that it /// was stopped; any other failure shows its error, which names the files left written. pub(crate) fn failed(app: &mut VectorcraftApp, error: String) { diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs new file mode 100644 index 0000000000..9c890d5c39 --- /dev/null +++ b/crates/ui-egui/src/scripts_menu.rs @@ -0,0 +1,255 @@ +//! File › Scripts: the scripts of the Scripts folder next to the settings +//! ([`vectorcraft_engine::Session::attach_scripts_dir`]), each `.js` or `.jsx` file by its name +//! without the extension and each subfolder as a submenu, above Check Script… and Other Script…. +//! +//! The folder is read on another thread ([`vectorcraft_engine::script::folder::list`]: names only, +//! within its limits), one read at a time: when the app starts, each time its window becomes the +//! active one, and each time the File menu of the window's menu bar opens ([`refresh`]). The menus show the last finished +//! listing ([`items`]), so a script added to the folder is listed without a restart. +//! +//! `ui.runInstalledScript {path}` runs a listed script (`script.run`) without the warning Other +//! Script… shows: the file was put in the folder to be run from the menu. The path is one a +//! listing gave; a file that is no longer a plain script under the folder is not run. + +use std::path::Path; +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::sync::{Arc, Mutex, MutexGuard}; + +use serde_json::{Value, json}; +use vectorcraft_engine::script::folder::{Entry, Listing}; + +use crate::VectorcraftApp; +use crate::menus::Item; + +/// The command a listed script's menu item runs. +pub const COMMAND: &str = "ui.runInstalledScript"; +/// The menu's note under a listing that may lack scripts. +pub const TRUNCATED: &str = "Some scripts were not listed"; +/// The menu's note when the folder is there and cannot be read. +pub const UNREADABLE: &str = "The Scripts folder cannot be read"; +/// The notes, for the catalogs ([`crate::menus::menu_strings`]). +pub const LABELS: &[&str] = &[TRUNCATED, UNREADABLE]; + +#[derive(Default)] +struct State { + /// The last finished listing. + listing: Arc, + /// How many finished listings differed from the one before. + revision: u64, + /// The listing being read on another thread. + reading: Option>, + /// Another read was asked for while one was under way; [`poll`] starts it when that one ends. + pending: bool, + /// A first read was asked for. + started: bool, + /// The window was the active one at the last [`poll`]. + focused: bool, +} + +/// The listing the menus show. One per process in the app; one per thread in unit tests, which run +/// in parallel threads, each with its own folder. +fn state() -> MutexGuard<'static, State> { + #[cfg(not(test))] + let state: &'static Mutex = { + static S: std::sync::OnceLock> = std::sync::OnceLock::new(); + S.get_or_init(Default::default) + }; + #[cfg(test)] + let state: &'static Mutex = { + thread_local!(static S: &'static Mutex = Box::leak(Box::default())); + S.with(|s| *s) + }; + state.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The most different names the menu shows in one session. Each is kept for the rest of the +/// session (menu items hold `&'static str` labels), at most 128 characters each. +pub const MAX_NAMES: usize = 16_384; + +/// Leak-once interning of the names the menu shows; `None` for a new name once [`MAX_NAMES`] are +/// kept, so renaming scripts over and over keeps the memory bounded. +pub(crate) fn intern(s: &str) -> Option<&'static str> { + #[cfg(not(test))] + let set: &'static Mutex> = { + static SET: std::sync::OnceLock>> = std::sync::OnceLock::new(); + SET.get_or_init(Default::default) + }; + #[cfg(test)] + let set: &'static Mutex> = { + thread_local!(static SET: &'static Mutex> = Box::leak(Box::default())); + SET.with(|s| *s) + }; + let mut set = set.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(v) = set.get(s) { + return Some(v); + } + if set.len() >= MAX_NAMES { + return None; + } + let v: &'static str = Box::leak(s.to_string().into_boxed_str()); + set.insert(v); + Some(v) +} + +/// Changes whenever the menus' listing changes (the macOS menu bar follows it). +pub fn revision() -> u64 { + state().revision +} + +/// Read the Scripts folder again on another thread, unless the session has no folder (the web, and +/// a run without preferences). While a read is under way, another read starts when it ends +/// ([`poll`]). `ctx` is asked to draw when the read ends. +pub fn refresh(app: &VectorcraftApp, ctx: Option<&egui::Context>) { + let Some(root) = app.session.scripts_dir().map(Path::to_path_buf) else { return }; + let mut state = state(); + if state.reading.is_some() { + state.pending = true; + return; + } + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = ctx.cloned(); + let spawned = std::thread::Builder::new().name("vectorcraft-scripts".into()).spawn(move || { + // The app's own folder, read for the person at the keyboard. + let listing = vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&root)); + if tx.send(listing).is_ok() + && let Some(ctx) = ctx + { + ctx.request_repaint(); + } + }); + if spawned.is_ok() { + state.reading = Some(rx); + } +} + +/// Once per iteration: start a read on the first one and when the window becomes the active one, +/// take in a read that ended, and then start a read asked for while it was under way. +pub fn poll(app: &VectorcraftApp, ctx: &egui::Context) { + let focused = ctx.input(|i| i.focused); + let start = { + let mut state = state(); + let start = !state.started || (focused && !state.focused); + (state.started, state.focused) = (true, focused); + start + }; + if start { + refresh(app, Some(ctx)); + } + take(false); + let again = { + let mut state = state(); + let again = state.pending && state.reading.is_none(); + if again { + state.pending = false; + } + again + }; + if again { + refresh(app, Some(ctx)); + } +} + +/// Take in the read under way: when it has ended, or with `wait` once it ends. +fn take(wait: bool) { + let mut state = state(); + let Some(reading) = &state.reading else { return }; + let listing = if wait { reading.recv().map_err(|_| TryRecvError::Disconnected) } else { reading.try_recv() }; + match listing { + Ok(listing) => { + if *state.listing != listing { + state.listing = Arc::new(listing); + state.revision += 1; + } + state.reading = None; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => state.reading = None, + } +} + +/// Wait for the read under way and take it in. +#[cfg(test)] +pub(crate) fn wait() { + take(true); +} + +/// Wait for the read under way to end and leave its listing to be taken in, so the read is under +/// way until the next [`poll`]. +#[cfg(test)] +pub(crate) fn end_untaken() { + let mut state = state(); + let Some(reading) = &state.reading else { return }; + let (tx, rx) = std::sync::mpsc::channel(); + if let Ok(listing) = reading.recv() { + let _ = tx.send(listing); + } + state.reading = Some(rx); +} + +/// File › Scripts' items: the listed scripts and subfolders, a note when some may be missing or +/// the folder cannot be read, then Check Script… and Other Script…. +pub fn items() -> Vec { + // A row whose name is past [`MAX_NAMES`] is left out (`dropped`). + fn level(entries: &[Entry], dropped: &mut bool) -> Vec { + let mut items = Vec::with_capacity(entries.len()); + for e in entries { + let item = match e { + Entry::Script { label, path } => intern(label).map(|l| Item::Cmd(l, COMMAND, json!({ "path": path.to_string_lossy() }))), + Entry::Folder { label, entries } => { + let inner = level(entries, dropped); + intern(label).filter(|_| !inner.is_empty()).map(|l| Item::Sub(l, inner)) + } + }; + match item { + Some(item) => items.push(item), + None => *dropped = true, + } + } + items + } + let listing = state().listing.clone(); + let mut dropped = false; + let mut items = level(&listing.entries, &mut dropped); + if listing.truncated || dropped { + items.push(Item::Header(TRUNCATED)); + } + if listing.unreadable { + items.push(Item::Header(UNREADABLE)); + } + if !items.is_empty() { + items.push(Item::Sep); + } + items.extend([Item::Cmd("Check Script…", "ui.checkScript", Value::Null), Item::Cmd("Other Script…", "ui.runScript", Value::Null)]); + items +} + +/// Is `children` a subfolder's submenu, named after the folder? Its first item is a listed script +/// or another subfolder, and it has no Other Script…, which only File › Scripts itself has. +pub fn is_folder(children: &[Item]) -> bool { + let listed = match children.first() { + Some(Item::Cmd(_, id, _)) => *id == COMMAND, + Some(Item::Sub(_, inner)) => is_folder(inner), + _ => false, + }; + listed && !children.iter().any(|c| matches!(c, Item::Cmd(_, "ui.runScript", _))) +} + +/// May the request being served read the listed script `p` names? Under an automation read root +/// (a control client's request), a script outside the root is left out of `ui.menu.list`, as +/// `script.listInstalled` refuses to list the folder there. +pub fn readable(p: &Value) -> bool { + p.get("path").and_then(Value::as_str).is_some_and(|path| vectorcraft_engine::file_access::check_read(path).is_ok()) +} + +/// `ui.runInstalledScript {path}`: run the listed script at `path`. A script that is no longer in +/// the folder is not run, and the folder is read again. The script runs from its file, so its +/// `#include` lines and `$.evalFile` read beside it. +pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { + let path = p.get("path").and_then(Value::as_str).ok_or("missing `path`")?; + app.session.installed_script(path).map_err(|e| { + let ctx = app.ui_ctx.clone(); + refresh(app, ctx.as_ref()); + e.to_string() + })?; + app.run("script.run", json!({ "path": path })) +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index dfe85768cf..59553120c8 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -208,6 +208,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::panels::css_properties::ID, "CSS Properties", "globe"), (crate::panels::three_d::ID, "3D and Materials", "dc-cube"), (crate::panels::variables::ID, "Variables", "chart-column"), + (crate::panels::script_console::ID, "Script Console", "message-circle"), (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 261a250542..07d88595d7 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -39,7 +39,9 @@ mod saveext; mod screenmode; mod screenshots; mod script_check; +mod script_dialogs; mod script_run; +mod scripts_menu; mod scrub; mod selectall; mod selectescape; diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index c66cc7cd5a..50c57db650 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -304,6 +304,62 @@ fn frames_with_injected_input_are_confined() { let _ = std::fs::remove_dir_all(base); } +/// Every File › Open Recent Files row `ui.menu.list` returns, disabled ones included: (id, label), +/// the label of a disabled row starting "(disabled) ". +fn recent_rows(entries: &Value) -> Vec<(String, String)> { + let rows = entries.as_array().map(Vec::as_slice).unwrap_or_default(); + rows.iter() + .filter(|e| e["command"].as_str().is_some_and(|c| c.starts_with("file.openRecent"))) + .map(|e| { + let label = e["label"].as_str().unwrap_or_default(); + let label = if e["enabled"] == true { label.to_string() } else { format!("(disabled) {label}") }; + (e["command"].as_str().unwrap_or_default().to_string(), label) + }) + .collect() +} + +#[test] +fn recent_files_outside_the_read_root_are_not_listed_or_opened() { + let (mut app, tx, base) = confined("recent"); + std::fs::copy(base.join("in/a.svg"), base.join("in/c.svg")).unwrap(); + let (a, b, c) = (s(base.join("in/a.svg")), s(base.join("outside/b.svg")), s(base.join("in/c.svg"))); + app.ui.recent_files = vec![a.clone(), b.clone(), c.clone()]; + let rows = |pairs: &[(&str, &str)]| pairs.iter().map(|(id, l)| (id.to_string(), l.to_string())).collect::>(); + + // The person's menu lists all three. + let person = serde_json::to_value(crate::menus::menu_entries(&app)).unwrap(); + assert_eq!(recent_rows(&person), rows(&[("file.openRecent1", "a.svg"), ("file.openRecent2", "b.svg"), ("file.openRecent3", "c.svg")])); + assert_eq!(app.run("file.recentFiles", json!({})).unwrap(), json!([a, b, c])); + + // The client's listing leaves out the second, and the third keeps its id. + let r = request(&mut app, &tx, "ui.menu.list", json!({})); + assert_eq!(recent_rows(&r["result"]), rows(&[("file.openRecent1", "a.svg"), ("file.openRecent3", "c.svg")]), "{r}"); + let r = request(&mut app, &tx, "engine.execute", json!({"command": "file.recentFiles"})); + assert_eq!(r["result"], json!([a, c]), "{r}"); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "file.openRecent2"})); + assert_eq!(r["error"], "no such recent file", "the reply names no path: {r}"); + assert!(app.session.documents().is_empty()); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "file.openRecent3"})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.session.documents().len(), 1); + assert_eq!(app.ui.recent_files, [c.clone(), a.clone(), b.clone()]); + + // A file outside the root that the person has open is still not brought forward. + app.run("file.openRecent3", json!({})).unwrap(); + assert_eq!((app.session.documents().len(), &app.ui.recent_files[0]), (2, &b)); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "file.openRecent1"})); + assert_eq!(r["error"], "no such recent file", "{r}"); + + // Rows past Number of Recent Files to Display stay out, and a write root alone lists none. + app.session.prefs.recent_files_count = 2; + let r = request(&mut app, &tx, "ui.menu.list", json!({})); + assert_eq!(recent_rows(&r["result"]), rows(&[("file.openRecent2", "c.svg")]), "{r}"); + let write_only = AutomationRoots::new(&[], &[&base.join("out")]).unwrap(); + let listed = vectorcraft_engine::file_access::confine(write_only.as_ref(), || serde_json::to_value(crate::menus::menu_entries(&app)).unwrap()); + assert!(recent_rows(&listed).is_empty(), "{listed}"); + let _ = std::fs::remove_dir_all(base); +} + /// Hidden logic-only ticks between the injection and its UI pass must not drain another step: /// one step per settled pass, not per hidden tick. #[test] diff --git a/crates/ui-egui/src/tests/rotateview.rs b/crates/ui-egui/src/tests/rotateview.rs index 2f98a3f3b1..dbdb0283fd 100644 --- a/crates/ui-egui/src/tests/rotateview.rs +++ b/crates/ui-egui/src/tests/rotateview.rs @@ -535,6 +535,23 @@ fn escape_that_ends_a_path_being_drawn_keeps_the_rotation() { } } +/// A path that is no longer selected is not being drawn: the next Escape resets the view. +#[test] +fn escape_after_deselecting_the_path_resets_the_view() { + for tool in ["pen", "smartPen", "curvature"] { + let mut w = Window::new(); + w.app.select_tool(tool); + let c = w.app.canvas_rect.unwrap().center(); + w.click(0.0, egui::PointerButton::Primary, c); + w.click(0.1, egui::PointerButton::Primary, c + egui::vec2(60.0, 10.0)); + assert!(w.app.session.tool_ends_on_escape(w.app.view_info()), "{tool}: a path is being drawn"); + w.app.run("select.none", json!({})).unwrap(); + assert!(!w.app.session.tool_ends_on_escape(w.app.view_info()), "{tool}: the path is not selected"); + w.escape(0.2); + assert_eq!(w.rotation(), 0.0, "{tool}: one Escape resets the view"); + } +} + /// In isolation mode, an Escape that ends the Pen's path ends only the path: the next Escape leaves /// isolation mode, and the one after it resets the view. #[test] diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs new file mode 100644 index 0000000000..b3750001a4 --- /dev/null +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -0,0 +1,282 @@ +//! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons, +//! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers +//! given by a run with nobody to ask. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use crate::dialogs::script_run::{CLOSE_KIND, NOTICE_KIND}; +use crate::{VectorcraftApp, dialogs, menus, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + app +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10});"; + +fn start(app: &mut VectorcraftApp, source: &str) { + menus::run_ui_command(app, "ui.runScript", &json!({"source": source, "name": "d.js"})).unwrap().unwrap(); +} + +/// Polls the run until it ends, or until its dialog is open (true). +fn until_dialog(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == NOTICE_KIND) { + return true; + } + } + panic!("the script neither ended nor opened a dialog"); +} + +fn answer(app: &mut VectorcraftApp, answer: &str) { + app.ui.dialog.as_mut().unwrap().fields.insert("answer".into(), json!(answer)); + dialogs::confirm(app).unwrap(); +} + +thread_local! { + // One context per test, so frames follow one another as in the app. + static CTX: egui::Context = { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + }; +} + +/// One headless frame of the dialog layer and the shortcuts, in a window of `size`. Each key pressed +/// in it is let go in a second frame, as a person lets go of it. +fn frame(app: &mut VectorcraftApp, events: Vec, size: egui::Vec2) { + let ctx = CTX.with(Clone::clone); + let released: Vec = events + .iter() + .filter_map(|e| match e { + egui::Event::Key { key, physical_key, modifiers, pressed: true, .. } => { + Some(egui::Event::Key { key: *key, physical_key: *physical_key, pressed: false, repeat: false, modifiers: *modifiers }) + } + _ => None, + }) + .collect(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)); + let pressed = !released.is_empty(); + for events in std::iter::once(events).chain(pressed.then_some(released)) { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + dialogs::show(app, ui.ctx()); + }); + out.textures_delta.clear(); + } +} + +fn key(k: egui::Key) -> egui::Event { + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() } +} + +const WINDOW: egui::Vec2 = egui::vec2(1200.0, 800.0); + +fn log(app: &VectorcraftApp) -> Value { + app.session.script_report().unwrap()["log"].clone() +} + +#[test] +fn alert_waits_and_stop_rolls_back_first_dialog() { + for stop_with_escape in [false, true] { + let mut app = app(); + start(&mut app, &format!("{DRAW} while (1) {{ alert('x'); }}")); + assert!(until_dialog(&mut app)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["kind"].as_str(), d.fields["message"].as_str(), d.fields["title"].clone()), (Some("alert"), Some("x"), Value::Null)); + for _ in 0..5 { + script_runs::poll(&mut app); + } + assert!(app.session.script_running(), "the run waits at the dialog"); + assert_eq!(objects(&app), 0); + if stop_with_escape { + frame(&mut app, vec![key(egui::Key::Escape)], WINDOW); + } else { + answer(&mut app, "stop"); + } + assert!(app.ui.dialog.is_none()); + assert!(!until_dialog(&mut app)); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); + assert_eq!(app.session.script_report().unwrap()["dialogs"][0]["answer"], "stop"); + } +} + +#[test] +fn confirm_enter_uses_no_as_default() { + for (no_as_default, want) in [(true, false), (false, true)] { + let mut app = app(); + start(&mut app, &format!("vc.log(confirm('Go?', {no_as_default}));")); + assert!(until_dialog(&mut app)); + frame(&mut app, vec![], WINDOW); + frame(&mut app, vec![key(egui::Key::Enter)], WINDOW); + assert!(app.ui.dialog.is_none(), "Enter answers the dialog: noAsDflt {no_as_default}"); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!([want]), "noAsDflt {no_as_default}"); + } + let mut app = app(); + start(&mut app, "vc.log(confirm('Go?'));"); + assert!(until_dialog(&mut app)); + frame(&mut app, vec![key(egui::Key::Escape)], WINDOW); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!([false]), "Escape is No"); +} + +#[test] +fn prompt_ok_and_cancel_return_values() { + let mut app = app(); + start(&mut app, "vc.log(prompt('Name', 'pre', 'Ask')); vc.log(prompt('Again', 'x'));"); + assert!(until_dialog(&mut app)); + assert_eq!(dialogs::script_run::notice_heading(app.ui.dialog.as_ref().unwrap()), "Ask"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["value"], "pre"); + app.ui.dialog.as_mut().unwrap().fields.insert("value".into(), json!("typed")); + dialogs::confirm(&mut app).unwrap(); + assert!(until_dialog(&mut app)); + dialogs::cancel(&mut app); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!(["typed", null])); + let mut app = self::app(); + start(&mut app, "vc.log(prompt('Name', ''));"); + assert!(until_dialog(&mut app)); + let e = { + app.ui.dialog.as_mut().unwrap().fields.insert("answer".into(), json!("yes")); + dialogs::confirm(&mut app).unwrap_err() + }; + assert!(e.contains("ok, cancel, stop"), "{e}"); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, NOTICE_KIND, "a wrong answer leaves the dialog open"); + answer(&mut app, "ok"); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!([""]), "OK with an empty field gives an empty string"); +} + +#[test] +fn the_dialog_opens_in_the_frame_the_run_waits() { + let mut app = app(); + start(&mut app, "alert('x');"); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(NOTICE_KIND), "no later frame is drawn while the run waits"); +} + +#[test] +fn a_prompt_text_past_the_limit_keeps_the_dialog_open() { + let mut app = app(); + start(&mut app, "vc.log(prompt('Name', ''));"); + assert!(until_dialog(&mut app)); + let long = "x".repeat(vectorcraft_engine::script::dialogs::MAX_PROMPT_BYTES + 1); + app.ui.dialog.as_mut().unwrap().fields.insert("value".into(), json!(long)); + assert!(dialogs::confirm(&mut app).is_err()); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, NOTICE_KIND, "the refused answer leaves the dialog open"); + assert!(app.session.script_dialog().is_some(), "the run still waits"); + app.ui.dialog.as_mut().unwrap().fields.insert("value".into(), json!("ok")); + answer(&mut app, "ok"); + assert!(!until_dialog(&mut app)); + assert_eq!(log(&app), json!(["ok"])); +} + +#[test] +fn dialog_wait_survives_another_modal() { + let mut app = app(); + start(&mut app, "alert('x');"); + script_runs::poll(&mut app); + app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::GROWTH_KIND, json!({}))); + let other = app.ui.dialog.clone(); + for _ in 0..3 { + script_runs::poll(&mut app); + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.clone()), other.map(|d| d.kind), "the open dialog stays"); + assert!(app.session.script_running()); + app.ui.dialog = None; + assert!(until_dialog(&mut app), "the script's dialog opens once the other one closes"); +} + +#[test] +fn close_while_notification_waits_abandons_or_resumes() { + let mut app = app(); + start(&mut app, &format!("{DRAW} vc.log(prompt('Name', ''));")); + assert!(until_dialog(&mut app)); + app.ui.dialog.as_mut().unwrap().fields.insert("value".into(), json!("half")); + dialogs::script_run::ask_to_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, CLOSE_KIND); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, CLOSE_KIND, "the run goes on waiting"); + dialogs::cancel(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.fields["value"].as_str()), (NOTICE_KIND, Some("half")), "Cancel shows the dialog again as it was"); + dialogs::script_run::ask_to_close(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); + assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); +} + +#[test] +fn close_question_ends_with_a_run_stopped_another_way() { + let mut app = app(); + start(&mut app, &format!("{DRAW} vc.log(prompt('Name', ''));")); + assert!(until_dialog(&mut app)); + dialogs::script_run::ask_to_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, CLOSE_KIND); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + script_runs::poll(&mut app); + assert!(!app.session.script_running()); + assert!(app.ui.dialog.is_none(), "the question about a run that has ended closes"); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none(), "Cancel does not show the stopped script's dialog again"); + assert_eq!(objects(&app), 0); + // Asked to stop, the run no longer waits at its dialog before its next slice ends it. + let mut app = self::app(); + start(&mut app, &format!("{DRAW} vc.log(prompt('Name', ''));")); + assert!(until_dialog(&mut app)); + dialogs::script_run::ask_to_close(&mut app); + app.run("script.stop", json!({})).unwrap(); + dialogs::script_run::settle_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, CLOSE_KIND, "the run has not ended yet"); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none(), "Cancel does not show a dialog the run no longer waits at"); +} + +#[test] +fn notification_layout_with_long_text_and_small_window() { + let mut app = app(); + let long = "word ".repeat(3_000); + start(&mut app, &format!("alert({long:?} + '\\u0007\\r\\n', 'T\\nitle', true);")); + assert!(until_dialog(&mut app)); + for _ in 0..3 { + frame(&mut app, vec![], egui::vec2(320.0, 240.0)); + } + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, NOTICE_KIND); + assert_eq!(dialogs::script_run::notice_heading(app.ui.dialog.as_ref().unwrap()), "T\u{240a}itle"); + answer(&mut app, "ok"); + assert!(!until_dialog(&mut app)); + assert_eq!(app.session.script_report().unwrap()["dialogs"][0]["errorIcon"], true); +} + +#[test] +fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() { + let source = "vc.log(confirm('a', true, 'T')); vc.log(prompt('b', 'p')); alert('c', undefined, false); vc.log('done');"; + let mut app = app(); + start(&mut app, source); + for a in ["yes", "ok", "ok"] { + assert!(until_dialog(&mut app)); + answer(&mut app, a); + } + assert!(!until_dialog(&mut app)); + let framed = app.session.script_report().unwrap().clone(); + let mut s = Session::new(); + let given = json!([{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "p"}, {"kind": "alert", "value": "ok"}]); + let headless = s.execute("script.run", &json!({"source": source, "name": "d.js", "answers": given})).unwrap(); + assert_eq!(framed["log"], headless["log"]); + assert_eq!(framed["dialogs"], headless["dialogs"]); + assert_eq!(framed["log"], json!([true, "p", "done"])); +} diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs new file mode 100644 index 0000000000..751bd528a6 --- /dev/null +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -0,0 +1,388 @@ +//! File › Scripts lists the Scripts folder: its scripts and subfolders above Check Script… and +//! Other Script…, names shown as they are, a listed script run without the warning, a script that +//! is gone, the notes, the macOS menu bar and the reads of the folder. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use crate::menus::{self, Entry, Item}; +use crate::native_menu::{self, Node}; +use crate::{VectorcraftApp, script_runs, scripts_menu}; + +/// A fresh folder for test `name`, holding an empty `Scripts` folder. +fn folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vc-scripts-menu-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("Scripts")).unwrap(); + dir +} + +/// An app with a document whose Scripts folder is `dir`'s. +fn app(dir: &std::path::Path) -> VectorcraftApp { + let mut session = Session::new(); + session.attach_scripts_dir(dir.join("Scripts")); + let mut app = VectorcraftApp::new(session, crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app +} + +/// Reads the folder again and waits for the listing. +fn read(app: &VectorcraftApp) { + scripts_menu::refresh(app, None); + scripts_menu::wait(); +} + +/// Writes the script `name` (`/` between its folders) in `dir`'s Scripts folder; returns its path +/// as a listing gives it. +fn write(dir: &std::path::Path, name: &str, text: &str) -> String { + let path = name.split('/').fold(dir.join("Scripts"), |path, part| path.join(part)); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, text).unwrap(); + path.to_string_lossy().into_owned() +} + +/// File › Scripts' items. +fn scripts() -> Vec { + let (_, file) = menus::menu_tree().into_iter().find(|(title, _)| *title == "File").unwrap(); + file.into_iter() + .find_map(|item| match item { + Item::Sub("Scripts", items) => Some(items), + _ => None, + }) + .unwrap() +} + +/// Menu items as text: a command's label, `label/[…]` for a submenu, `(text)` for a note and `-` +/// for a separator. +fn shape(items: &[Item]) -> String { + let one = |item: &Item| match item { + Item::Cmd(label, ..) | Item::Todo(label, _) => label.to_string(), + Item::Sub(label, items) => format!("{label}/[{}]", shape(items)), + Item::Header(text) => format!("({text})"), + Item::Sep => "-".to_string(), + }; + items.iter().map(one).collect::>().join(", ") +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn finish(app: &mut VectorcraftApp) { + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + script_runs::poll(app); + } + panic!("the script did not end"); +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); vc.run('shape.rectangle', {x:20,y:0,width:10,height:10});"; + +#[test] +fn the_folders_scripts_are_listed_above_check_script_and_other_script() { + let dir = folder("listed"); + let app = app(&dir); + assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "before the first listing"); + read(&app); + assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "an empty folder"); + let draw = write(&dir, "Draw Two.jsx", DRAW); + write(&dir, "Export/All Artboards.js", ""); + write(&dir, "notes.txt", ""); + read(&app); + let items = scripts(); + assert_eq!(shape(&items), "Draw Two, Export/[All Artboards], -, Check Script…, Other Script…"); + assert!(matches!(&items[0], Item::Cmd(_, scripts_menu::COMMAND, p) if *p == json!({ "path": draw })), "{:?}", items[0]); + // A script added to the folder is listed by the next read, with no restart. + write(&dir, "Added.js", ""); + assert!(shape(&scripts()).starts_with("Draw Two"), "the menus keep the last listing"); + read(&app); + assert!(shape(&scripts()).starts_with("Added, Draw Two")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_listed_script_runs_without_the_warning_as_one_undo_step() { + let dir = folder("run"); + let mut app = app(&dir); + write(&dir, "Dessin (été) #1.JSX", DRAW); + read(&app); + let items = scripts(); + let Item::Cmd(label, id, p) = &items[0] else { panic!("{:?}", items[0]) }; + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(app.session.prefs.show_external_script_warning); + let (id, p) = menus::click_target(label, id, p); + menus::invoke(&mut app, &id, p); + assert!(app.ui.dialog.is_none(), "no warning for a script of the folder"); + assert!(app.session.script_running()); + finish(&mut app); + assert_eq!(objects(&app), 2); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(app.ui.status, "Ran Dessin (été) #1.JSX"); + assert!(app.session.prefs.show_external_script_warning, "Other Script… still warns"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_script_runs_its_own_file_whatever_its_name_ends_with() { + let dir = folder("names"); + let mut app = app(&dir); + // A label that ends like a menu item that asks for its parameters first. + let dots = write(&dir, "Draw….js", DRAW); + write(&dir, "Draw.js", "vc.run('shape.rectangle', {x:0,y:0,width:1,height:1});"); + read(&app); + let items = scripts(); + assert_eq!(shape(&items[..2]), "Draw, Draw…"); + let Item::Cmd(label, id, p) = &items[1] else { panic!("{:?}", items[1]) }; + assert_eq!(menus::click_target(label, id, p), (scripts_menu::COMMAND.to_string(), json!({ "path": dots }))); + menus::run_ui_command(&mut app, id, p).unwrap().unwrap(); + finish(&mut app); + assert_eq!(objects(&app), 2, "the file the item names ran, not its neighbor"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_listed_script_reads_its_included_files_and_runs_files_beside_it() { + let dir = folder("include"); + let mut app = app(&dir); + write(&dir, "lib/two.jsxinc", DRAW); + write(&dir, "lib/one.js", "vc.run('shape.rectangle', {x:40,y:0,width:10,height:10});"); + let main = write(&dir, "Main.jsx", "#include \"lib/two.jsxinc\"\n$.evalFile('lib/one.js');\n"); + read(&app); + menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": main })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(objects(&app), 3, "{}", app.ui.status); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn script_and_folder_names_are_shown_as_they_are_in_every_language() { + let dir = folder("language"); + let app = app(&dir); + write(&dir, "Layers.js", ""); + write(&dir, "Export/Layers.jsx", ""); + read(&app); + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert!(crate::i18n::tr(de, "Layers") != "Layers" && crate::i18n::tr(de, "Export") != "Export", "German translates both words"); + crate::i18n::set_current(de); + let items = scripts(); + let labels: Vec = items + .iter() + .filter_map(|item| match menus::entry(&app, item)? { + Entry::Sub(label, _) => Some(label.to_string()), + Entry::Item(row) => Some(row.label.to_string()), + _ => None, + }) + .collect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(labels[..2], ["Export", "Layers"]); + assert_ne!(labels[2], "Check Script…", "the fixed items are translated"); + // The catalogs hold the notes, and no file or folder name. + let strings = menus::menu_strings(); + assert!(scripts_menu::LABELS.iter().all(|note| strings.contains(*note))); + assert!(strings.contains("Layers") && !strings.contains("All Artboards")); + write(&dir, "Zed/All Artboards.js", ""); + read(&app); + assert!(!menus::menu_strings().contains("All Artboards") && !menus::menu_strings().contains("Zed")); + assert!(!crate::palette::items().iter().any(|(_, id, _)| id == scripts_menu::COMMAND), "a script runs from its menu item"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_script_that_left_the_folder_is_not_run_and_the_folder_is_read_again() { + let dir = folder("gone"); + let mut app = app(&dir); + let gone = write(&dir, "gone.js", DRAW); + write(&dir, "kept.js", ""); + read(&app); + std::fs::remove_file(&gone).unwrap(); + let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": gone })).unwrap().unwrap_err(); + assert_eq!(e, "the script is no longer in the Scripts folder"); + assert!(!app.session.script_running()); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), "kept, -, Check Script…, Other Script…"); + // A file outside the folder is not one of its scripts, and a call needs a path. + let outside = dir.join("outside.js"); + std::fs::write(&outside, DRAW).unwrap(); + let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": outside.to_string_lossy() })).unwrap().unwrap_err(); + assert_eq!(e, "the script is no longer in the Scripts folder"); + assert!(menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({})).unwrap().is_err()); + assert!(menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": 3 })).unwrap().is_err()); + finish(&mut app); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_read_after_a_script_that_left_the_folder_asks_for_a_frame() { + let dir = folder("gone-frame"); + let mut app = app(&dir); + let gone = write(&dir, "gone.js", DRAW); + read(&app); + std::fs::remove_file(&gone).unwrap(); + let ctx = egui::Context::default(); + let (tx, frames) = std::sync::mpsc::channel(); + ctx.set_request_repaint_callback(move |_| { + let _ = tx.send(()); + }); + app.ui_ctx = Some(ctx); + assert!(menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": gone })).unwrap().is_err()); + // With the app's copy of the context dropped, only the read's thread can still ask for a + // frame; the channel closes without one when that thread ends without asking. + app.ui_ctx = None; + assert_eq!(frames.recv(), Ok(()), "the finished read asks for a frame so an idle window takes it in"); + scripts_menu::wait(); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { + let dir = folder("notes"); + let app = app(&dir); + for n in 0..vectorcraft_engine::script::folder::MAX_SCRIPTS + 1 { + write(&dir, &format!("s{n:04}.js"), ""); + } + read(&app); + let items = scripts(); + assert_eq!(items.len(), vectorcraft_engine::script::folder::MAX_SCRIPTS + 4); + assert_eq!(shape(&items[items.len() - 4..]), format!("({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + // A file where the folder should be. + std::fs::remove_dir_all(dir.join("Scripts")).unwrap(); + std::fs::write(dir.join("Scripts"), "").unwrap(); + read(&app); + assert_eq!(shape(&scripts()), format!("({}), -, Check Script…, Other Script…", scripts_menu::UNREADABLE)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_menu_listing_under_a_read_root_leaves_out_scripts_outside_it() { + use vectorcraft_engine::file_access::{AutomationRoots, confine}; + let dir = folder("read-root"); + let app = app(&dir); + let path = write(&dir, "Export/All Artboards.js", ""); + read(&app); + let scripts = || menus::menu_entries(&app).into_iter().filter(|e| e.command.as_deref() == Some(scripts_menu::COMMAND)).collect::>(); + let listed = scripts(); + assert_eq!(listed.len(), 1); + assert_eq!( + (&listed[0].path, &listed[0].label, &listed[0].params), + (&vec!["File".to_string(), "Scripts".into(), "Export".into()], &"All Artboards".to_string(), &json!({ "path": path })) + ); + let work = dir.join("work"); + std::fs::create_dir_all(&work).unwrap(); + let outside = AutomationRoots::new(&[&work], &[]).unwrap().unwrap(); + assert!(confine(Some(&outside), scripts).is_empty()); + let inside = AutomationRoots::new(&[&dir], &[]).unwrap().unwrap(); + assert_eq!(confine(Some(&inside), scripts).len(), 1); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn names_past_the_session_limit_are_left_out_with_the_note() { + let dir = folder("names-limit"); + let app = app(&dir); + write(&dir, "Kept.js", ""); + read(&app); + assert_eq!(shape(&scripts()), "Kept, -, Check Script…, Other Script…"); + // Names other listings showed fill what one session keeps. + for n in 0..scripts_menu::MAX_NAMES { + if scripts_menu::intern(&format!("renamed {n}")).is_none() { + break; + } + } + write(&dir, "New.js", ""); + write(&dir, "Folder/Inside.js", ""); + read(&app); + assert_eq!(shape(&scripts()), format!("Kept, ({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_macos_menu_bar_lists_the_same_scripts_and_follows_a_new_listing() { + let dir = folder("native"); + let app = app(&dir); + let path = write(&dir, "Export/All Artboards.js", ""); + let before = scripts_menu::revision(); + read(&app); + assert_eq!(scripts_menu::revision(), before + 1); + let bar = native_menu::from_tree(&app, &menus::menu_tree()); + let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); + let scripts = file.children.iter().find_map(|n| match n { + Node::Submenu { label, children } if label == "Scripts" => Some(children), + _ => None, + }); + let Some([Node::Submenu { label, children }, Node::Separator, Node::Item(check), Node::Item(other)]) = scripts.map(Vec::as_slice) else { + panic!("{scripts:?}") + }; + assert_eq!((label.as_str(), check.command, other.command), ("Export", Some("ui.checkScript"), Some("ui.runScript"))); + let [Node::Item(script)] = children.as_slice() else { panic!("{children:?}") }; + assert_eq!((script.label.as_str(), script.command, &script.params), ("All Artboards", Some(scripts_menu::COMMAND), &json!({ "path": path }))); + assert!(script.enabled && script.shortcut.is_none()); + // A read that finds the same scripts changes nothing the menu bar would rebuild for. + read(&app); + assert_eq!(scripts_menu::revision(), before + 1); + write(&dir, "More.jsx", ""); + read(&app); + assert_eq!(scripts_menu::revision(), before + 2); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_folder_is_read_at_the_first_frame_and_when_the_window_becomes_active() { + let dir = folder("focus"); + let app = app(&dir); + write(&dir, "first.js", ""); + let ctx = egui::Context::default(); + let frame = |focused: bool| { + let mut out = ctx.run_ui(egui::RawInput { focused, ..Default::default() }, |ui| scripts_menu::poll(&app, ui.ctx())); + out.textures_delta.clear(); + scripts_menu::wait(); + }; + let listed = || shape(&scripts()); + frame(true); + assert!(listed().starts_with("first, -"), "{}", listed()); + // While the window stays active, or stays in the background, the folder is left alone. + write(&dir, "second.js", ""); + frame(true); + frame(false); + frame(false); + assert!(listed().starts_with("first, -"), "{}", listed()); + frame(true); + assert!(listed().starts_with("first, second, -"), "{}", listed()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_read_asked_for_during_another_runs_when_that_one_ends() { + let dir = folder("pending"); + let app = app(&dir); + write(&dir, "first.js", ""); + let ctx = egui::Context::default(); + let frame = || { + let mut out = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| scripts_menu::poll(&app, ui.ctx())); + out.textures_delta.clear(); + }; + frame(); + scripts_menu::wait(); + // A read that has passed the folder when a script is added, and the File menu opening then. + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + write(&dir, "added.js", ""); + scripts_menu::refresh(&app, None); + frame(); + scripts_menu::wait(); + assert!(shape(&scripts()).starts_with("added, first, -"), "{}", shape(&scripts())); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_app_without_a_scripts_folder_keeps_the_two_fixed_items() { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + read(&app); + assert_eq!(shape(&scripts()), "Check Script…, Other Script…"); + let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": "draw.js" })).unwrap().unwrap_err(); + assert_eq!(e, "the script is no longer in the Scripts folder"); + assert_eq!(menus::UI_COMMANDS.iter().filter(|c| c.0 == scripts_menu::COMMAND).count(), 1); + let _: Value = app.run("script.listInstalled", json!({})).unwrap(); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index be2965ef3c..2dd361a7d6 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -45,13 +45,13 @@ pub use drag::{ }; #[cfg(test)] use dropdowns::combo_button_id; -#[cfg(test)] -pub(crate) use dropdowns::menu_floor; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named, field_focused_in, popover_is_open}; pub use dropdowns::{ dropdown, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, }; +#[cfg(test)] +pub(crate) use dropdowns::{menu_floor, menu_room_either}; pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_label, section_header, section_toggle, section_toggle_name, subheader}; pub(crate) use labels::{label_field, take_previous_label, text_width}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; @@ -658,6 +658,27 @@ mod menu_room_tests { assert_eq!(menu_room(100.0, 24.0, 92.0), 92.0); } + /// A popup opens below its button while that leaves the minimum height, even when the list + /// then scrolls. + #[test] + fn a_menu_opens_below_while_that_side_has_the_minimum() { + assert_eq!(menu_room_either(300.0, 800.0, 980.0), 288.0); + assert_eq!(menu_room_either(132.0, 800.0, 980.0), 120.0); + } + + /// With less than the minimum below, the list takes the room above, up to the window's height. + #[test] + fn a_menu_opens_above_when_below_is_too_short() { + assert_eq!(menu_room_either(40.0, 500.0, 980.0), 488.0); + assert_eq!(menu_room_either(40.0, 500.0, 300.0), 300.0); + } + + /// With little room on either side, the list keeps the minimum height. + #[test] + fn a_menu_keeps_the_minimum_with_little_room_either_side() { + assert_eq!(menu_room_either(40.0, 60.0, 980.0), 120.0); + } + /// The floor one window records does not reach a menu in another window of the same context. #[test] fn the_menu_floor_applies_in_the_window_that_recorded_it() { diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index d5d914b7b6..44903d6613 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -284,12 +284,25 @@ pub(crate) fn menu_floor(ctx: &egui::Context) -> f32 { ctx.data(|d| d.get_temp::(id)).unwrap_or_else(|| ctx.content_rect().bottom()) } +/// The space a menu list leaves between its end and the window's edge or bars. +const MENU_GAP: f32 = 12.0; +/// The least height a menu list is given. +const MENU_MIN_HEIGHT: f32 = 120.0; + /// The height a menu list may take: from `top` down to `floor` less a small gap, at least 120 pt, /// and never more than `tallest`, the most that fits in the window. pub fn menu_room(floor: f32, top: f32, tallest: f32) -> f32 { - const BOTTOM_GAP: f32 = 12.0; - const MIN_HEIGHT: f32 = 120.0; - (floor - top - BOTTOM_GAP).max(MIN_HEIGHT).min(tallest) + (floor - top - MENU_GAP).max(MENU_MIN_HEIGHT).min(tallest) +} + +/// The height a menu list may take when its popup can open below or above the rect it opens from: +/// `below` and `above` are the heights each side leaves for the list. The list goes below while that +/// side has room for the minimum height, otherwise on the side with more room. It gets at least +/// 120 pt and never more than `tallest`. +pub(crate) fn menu_room_either(below: f32, above: f32, tallest: f32) -> f32 { + let (below, above) = (below - MENU_GAP, above - MENU_GAP); + let room = if below >= MENU_MIN_HEIGHT { below } else { below.max(above) }; + room.max(MENU_MIN_HEIGHT).min(tallest) } /// The scroll bar of a menu's list: slim, in a column of its own beside the items, so it never @@ -298,19 +311,119 @@ pub fn list_scroll_style() -> egui::style::ScrollStyle { egui::style::ScrollStyle { bar_width: 6.0, bar_inner_margin: 2.0, ..egui::style::ScrollStyle::solid() } } +/// The widget that opened a popup and whether it is a submenu's row (`None` when none was found), +/// the frame the popup was opened in, and the frame it was last drawn in. +type Opener = (Option<(egui::Id, bool)>, u64, u64); + +/// The frames after a popup opens in which a search that found no opener runs again. +const OPENER_RETRY_FRAMES: u64 = 3; + +/// The widget that opened `popup`: a button whose popup has egui's default id, or a submenu's row, +/// found among the widgets of this frame and the previous one. Once found, later frames of the same +/// opening reuse it; a search that finds nothing runs again for the first few frames. +fn popup_opener(ctx: &egui::Context, popup: egui::Id) -> Option<(egui::Id, bool)> { + let key = popup.with("menu-scroll-opener"); + let frame = ctx.cumulative_frame_nr(); + let cached = ctx.data(|d| d.get_temp::(key)).filter(|&(_, _, seen)| seen + 1 >= frame); + let opened = cached.map_or(frame, |(_, opened, _)| opened); + let opener = match cached { + Some((found, _, _)) if found.is_some() || frame >= opened + OPENER_RETRY_FRAMES => found, + _ => { + let found = ctx.viewport(|vp| { + [&vp.this_pass, &vp.prev_pass].into_iter().flat_map(|pass| pass.widgets.layers()).flat_map(|(_, widgets)| widgets.iter()).find_map( + |w| { + let submenu = egui::containers::menu::SubMenu::id_from_widget_id(w.id) == popup; + (submenu || w.id.with("popup") == popup).then_some((w.id, submenu)) + }, + ) + }); + found.filter(|&(widget, submenu)| { + submenu || ctx.read_response(widget).is_some_and(|response| egui::Popup::default_response_id(&response) == popup) + }) + } + }; + ctx.data_mut(|d| d.insert_temp::(key, (opener, opened, frame))); + opener +} + +/// Where the popup or menu that `ui` is drawn in opens from: the rect of the button or row that +/// opened it, or the point a context menu was opened at. The flag is true for a submenu, which +/// opens beside its row: down from the row's top, or up from its bottom. While the opening widget +/// is not drawn, the rect it last had is used. A popup with an id of its own (`Popup::id`) has no +/// anchor. +fn popup_anchor(ui: &Ui) -> Option<(Rect, bool)> { + let ctx = ui.ctx(); + let popup = ui.layer_id().id; + let root = ui.stack().iter().last()?; + if !matches!(root.kind(), Some(egui::UiKind::Menu | egui::UiKind::Popup)) { + return None; + } + if let Some(at) = egui::Popup::position_of_id(ctx, popup) { + return Some((Rect::from_pos(at), false)); + } + let (widget, submenu) = popup_opener(ctx, popup)?; + let key = popup.with("menu-scroll-anchor"); + let drawn = ctx.read_response(widget).and_then(|response| egui::PopupAnchor::from(&response).rect(popup, ctx)); + let rect = match drawn { + Some(rect) => { + ctx.data_mut(|d| d.insert_temp(key, rect)); + rect + } + None => ctx.data(|d| d.get_temp::(key))?, + }; + // A submenu opens from its row grown by half the menu's margin, as egui's `SubMenu` places it. + let grow = if submenu { egui::Frame::menu(ui.style()).total_margin().sum().y * 0.5 } else { 0.0 }; + Some((rect.expand2(vec2(0.0, grow)), submenu)) +} + /// The body of a menu or popup list: as tall as its items up to the bottom bars of the window it /// opens in, and scrolling only past that, so long menus (Window, Effect, a panel's menu) stay /// reachable on small windows and in a floating panel's short OS window. Its scroll bar has a column -/// of its own, so it never covers the shortcuts or the submenu arrows (#2086, #5347). +/// of its own, so it never covers the shortcuts or the submenu arrows (#2086, #5347). When the list +/// scrolls, that column widens the popup instead of narrowing the items, so their labels stay on one +/// line. +/// +/// The list's height comes from the room below and above the button, row or point the popup opens +/// from. A popup with an id of its own measures from its own top instead. pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { - let ctx = ui.ctx(); - let tallest = (ctx.content_rect().height() - egui::Frame::popup(ui.style()).total_margin().sum().y).max(0.0); - let room = menu_room(menu_floor(ctx), ui.next_widget_position().y, tallest); + let ctx = ui.ctx().clone(); + let margins = egui::Frame::popup(ui.style()).total_margin().sum(); + let tallest = (ctx.content_rect().height() - margins.y).max(0.0); + let top = ui.next_widget_position().y; + // The rows above the list (the popup's margin, a search field) move with the popup. + let popup_top = ui.stack().iter().last().map_or(top, |root| root.max_rect.top()); + let ahead = top - popup_top; + let (floor, window_top) = (menu_floor(&ctx), ctx.content_rect().top()); + let room = if let Some((anchor, submenu)) = popup_anchor(ui) { + let (down_from, up_to) = if submenu { (anchor.top(), anchor.bottom()) } else { (anchor.bottom(), anchor.top()) }; + menu_room_either(floor - down_from - ahead, up_to - window_top - ahead, tallest) + } else { + menu_room(floor, top, tallest) + }; + // The items' width on the first frame of this showing, when the scroll area does not yet show + // its bar. Later frames lay the items out at least that wide, and the bar's column is added to + // the popup's width. The width is kept until the popup closes. + let key = ui.next_auto_id().with("menu-scroll-width"); + let frame = ctx.cumulative_frame_nr(); + let first = ctx.data(|d| d.get_temp::<(u64, f32)>(key)).filter(|(shown, _)| shown + 1 >= frame).map(|(_, width)| width); + let scroll = list_scroll_style(); + // The widest the items can be with the popup's margins and the bar's column inside the window. + let widest = (ctx.content_rect().width() - margins.x - scroll.allocated_width()).max(0.0); ui.scope(|ui| { - ui.spacing_mut().scroll = list_scroll_style(); + ui.spacing_mut().scroll = scroll; // The minimum lets the list grow past a popup's default 400 pt size; it still shrinks to // its items when they need less. - egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner + let area = egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room); + let out = area.show(ui, |ui| { + // Always the same child, so the items' ids stay the same on the frame the width changes. + let max = ui.max_rect(); + let width = first.map_or(max.width(), |first| first.min(widest).max(max.width())); + let rect = egui::Rect::from_min_size(max.min, egui::vec2(width, max.height())); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect).layout(*ui.layout()), add_contents).inner + }); + let width = first.unwrap_or(out.content_size.x); + ctx.data_mut(|d| d.insert_temp(key, (frame, width))); + out.inner }) .inner } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 02cc5c4384..96e5baffb3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -691,7 +691,8 @@ In the desktop app a Paste from the menus or the keys (`ui.key`) decodes a bitma `edit.paste*` reads it at once. File menu details: `file.openRecent1`…`file.openRecent30` open the recent files the `recentFilesCount` preference -lists (0 hides them all; `file.recentFiles` returns the listed paths), `file.reveal` shows the document's file in the +lists (0 hides them all; `file.recentFiles` returns the listed paths; under a read root, `ui.menu.list` and +`file.recentFiles` leave out the files outside it and `file.openRecentN` answers `no such recent file` for one), `file.reveal` shows the document's file in the system file manager (desktop only; answers `{path}`), and `file.newFromTemplate` without params opens a file picker in the Templates folder (preference `templatesFolder`). Older native files open as " [Converted]" (preference `appendConverted`), so their Save asks for a new `.vectorcraft` name. Native files reopen at the view they were saved diff --git a/docs/dimensions.md b/docs/dimensions.md index 1f1db9a492..6f11a29c96 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -6,11 +6,37 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers - **Linear:** hover a path segment and drag outwards: releasing places the dimension. Or click two points (anchors snap, Shift constrains to 45°), then click to place. A click within 8 pixels of an anchor of any path, in groups and compound paths too, takes that anchor, and the dimension - stays linked to it. A press on an anchor picks it when the pointer moves less than 8 pixels + stays linked to it. A point on a segment stays at its place along the segment, also when the + segment's anchors or handles are edited. Any other point is linked to the path under it, or, + with no path under it, to the path at the other end, and moves, scales, turns and reflects with + that path. Beside a path whose anchors and handles all lie on one line, such as a straight line, + the point keeps its distance along and across the path: a reflection moves it as a half turn + does, and a scale that is not uniform changes its distance across the path in proportion to the + path's length. A press on an anchor picks it when the pointer moves less than 8 pixels before the release; a longer drag drags out the dimension of the segment under the pointer. A curved segment is measured from end to end. With Smart Guides on, both points also snap into line with other objects' anchors and centres, and the second onto the construction guides through the first; the guides show while hovering, before each click. + A linear dimension is aligned, horizontal or vertical, as the + [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) + describes: after the second click, clicking again places an aligned dimension, and moving the + pointer away gives a horizontal or vertical one. Which one a pointer position gives is + VectorCraft's own rule. When the pointer is beside the two points (the nearest point of the + line through them lies between them) or on that line, the dimension is aligned. When the + pointer is past either point, the line through the points and the perpendicular through that + point divide the area beyond it into two quarters, one on each side of the line. The quarter + that contains the direction straight up or down from the point gives the horizontal distance, + and the quarter that contains the direction straight left or right gives the vertical distance. + A click within 8 pixels of the second point, or of where the pointer was for the second click, + places an aligned dimension. Two points on one horizontal or vertical line always give an + aligned dimension. A dragged segment uses the same rule with its two ends. + A horizontal or vertical dimension keeps its orientation when it or the art it measures turns, + and shows the new horizontal or vertical distance, as the help describes for rotated objects. It + shows 0 when its points lie on one line across its axis. When the line of a linked dimension + lies outside its points, the line stays on the same side of the art, as far past the outermost + point as before. An unlinked dimension that + turns has its line where the turn puts it, or, when that would put it between the points, as + far past the outermost point as before. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its @@ -32,10 +58,15 @@ position and alignment; changing one changes that dimension. **Apply to All** gi dimension in the document its style; **Set as Default** makes it the style of new dimensions. Measurements follow the art they measure through moves, scaling and anchor and handle edits, -undo and redo included. Deleting the art, or changing its number of anchors or whether it is -closed, removes its dimensions in the same undo step rather than attaching them to a different -edge. A linked dimension moved on its own stays where it was dropped (its distance from the art -changes); moved together with its art, it keeps its distance. +undo and redo included. When the art is reflected, the line of a linked linear dimension goes to +the reflected side, as far past the outermost point as before. This does not happen for art whose +anchors and handles all lie on one line, such as a straight line, which a half turn puts in the +same place as a reflection. Deleting the art, changing its number of anchors or whether it is +closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular +leaves its dimensions where they were, no longer linked, in the same undo step, rather than +attaching them to a different edge. Undo links them again. A linked dimension moved on its own +stays where it was dropped (its distance from the art changes); moved together with its art, it +keeps its distance. Native `.vectorcraft` files keep the recipes and links. SVG, PDF and bitmap output contain ordinary paths and text, so exported dimensions look the same. Ungrouping a dimension leaves its @@ -43,20 +74,38 @@ paths and text as ordinary art. Object › Expand, Object › Expand Appearance, and Object › Path › Outline Stroke turn a dimension whose art they change into a plain group of that art, also when they reach only a part of it: moving or scaling the group does not redraw it, it does not follow the art it measured, and undoing the command gives the live dimension back. The menus dim -Object › Expand… while a whole dimension is selected, because its label has appearance items; -Object › Expand Appearance and the `object.expand` command still reach it. A dimension selected with -the art it measures also becomes a plain group when Object › Expand, Object › Expand Appearance or -Object › Path › Outline Stroke changes only that art and the art no longer fits the dimension's link, -for example because its number of anchors changed. When the art keeps its id and anchor count and the -dimension's own art does not change, the dimension stays live and its label shows the new length. Pasted -dimensions keep their geometry and drop their links, so they never bind to unrelated art in another -document. +Object › Expand… while a whole dimension is selected without the art it measures, because its label +has appearance items; Object › Expand Appearance and the `object.expand` command still reach it. + +When a whole dimension is selected together with art it measures, directly or in selected groups +without fills, strokes or effects of their own, Object › Expand, Object › Expand Appearance and +Object › Path › Outline Stroke leave the dimension's lines and label as they are and change only the +other art. The menus do not dim Object › Expand… for the label of such a dimension. If the new art no +longer fits the dimension's link, for example because its number of anchors changed, the dimension +stays where it was, no longer linked, as it does when its art is deleted. Undoing the command links +it again. When the art keeps its id and anchor count, the dimension stays linked and its label shows +the new length. When the dimension is all the command would change, the command changes nothing and +reports the error it gives for a selection with nothing to change: "Expand: nothing to expand", +"Expand Appearance: the selection has a basic appearance" or "Outline Stroke: no stroked paths +selected". A selected group with fills, strokes or effects of its own changes everything it holds +when its appearance expands, its dimensions included: a geometry effect is baked into their lines +and label, which become a plain group, and a blur, feather or inner glow turns them into part of the +image that replaces the group's art. Type › Create Outlines still outlines the label of a dimension +selected with its art, which turns the dimension into a plain group. + +Pasted dimensions keep their geometry and drop their links, so they never bind to unrelated art in +another document. ## Commands - `dimension.create`: two points, or a source (segment, angle, circle, arc, points), the mode, - offset and style; returns the group id and label. -- `dimension.update`: restyle or move existing dimensions. + the orientation of a linear dimension (`aligned`, the default, `horizontal` or `vertical`), + offset and style; returns the group id and label. `offset` is the distance of the dimension + line from the first point: along the left normal of a → b for an aligned dimension, downward + for a horizontal one and leftward for a vertical one. A negative offset goes the other way. +- `dimension.update`: restyle or move existing dimensions, or change the orientation of linear + ones. A new orientation keeps the line on the side of the points it was on. An update that + changes nothing records no undo step. - `dimension.applyToAll`: every dimension takes one dimension's style, in one undo step. - `tool.select {"tool":"dimension"}` and `tool.setOption {"tool":"dimension","values":{"mode":"linear","style":{"units":"mm","scale":"1:10"}}}` diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 810d1568b9..5cad08fbf7 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (`.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -54,7 +54,7 @@ private editing data. VectorCraft: own paints with the paint before the mask's dictionary, as the writer leaves out paint that doesn't change. Type from the text document keeps auto leading as auto, each line taking the paragraph's share (Auto Leading) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)), - and the paragraph's hyphenation options and tab stops. Area type of one + and the paragraph's hyphenation options and tab stops. Stroked type keeps its stroke's cap, join and miter limit. Area type of one frame whose last lines the file sets but which don't fit here (the fallback font, or a descent past the frame's bottom) may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines, with a warning when it does. RGB in the PDF page's `ICCBased` spaces keeps the file's numbers in a `.ai` (the `uncalibrated_rgb` @@ -339,6 +339,12 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | `.ai` save (PDF-compatible editing copy and legacy) and `.ai`/EPS open: a layer's `Lb` colour index follows the file's numbering, where Magenta, Cyan and Yellow are 4, 5 and 6 and `LAYER_COLORS` has Yellow, Magenta and Cyan; Yellow, Magenta and Cyan layers no longer come out as Magenta, Cyan and Yellow, and the other 24 presets are unchanged (#6502, from the index and RGB pairs in users' files). `LAYER_COLORS` keeps its order, so `.vectorcraft` files and the Layers panel don't change. Scores and estimates unchanged. | +| 2026-11-11 | minor | `.ai` save: stroked type writes its stroke's cap, join and miter limit into the text document (keys 61, 62 and 64, as `.ai` import reads them since #6500), so they come back when the file opens again and no longer count among the attributes of type left out; a run without a stroke doesn't count them either, as they draw nothing. Tests `ai_editing::tests::type_comes_back_as_type`, `an_unstroked_run_with_a_stroke_style_loses_nothing` (follow-up to #6472) | +| 2026-11-11 | minor | `.ai` and EPS import, PDF import, SVG export and `.ai` save: type with a Horizontal Scale other than 100% and tracking or manual kerning is spaced as a `.ai`'s own page spaces it. Layout now measures tracking and manual kerning in thousandths of the em as the scale draws it (see type-parity.md, same date); they were added at the full em, so such type drifted from the page letter by letter. A `.ai`'s page writes that type's character spacing as the tracking itself in a text space as wide as the scale, which PDF scales by it (ISO 32000-1 §9.4.4). In 224 users' files (used locally, never committed), 93 render differently. Of the 25 whose render moved by more than 1% of its pixels against the page, 23 came closer. The note on the type differing from the page shows a smaller share in 5 files (11.0% to 4.4% at most) and a larger one in 2 (by 0.2 to 0.3 points). 9 more envelopes of type open live (113 to 122 of 203, none fewer in any file), and no file switched between its layers and its PDF part. PDF import: the tracking of horizontally scaled type is the file's `Tc` in thousandths of its size (it was that times the scale), the glyphs where they were (test `tests::text_placement::character_spacing_in_horizontally_scaled_type_is_the_files_tc`). SVG export writes the letter spacing in thousandths of the font size it writes (the vertical scale), so type scaled uniformly keeps its spacing in a viewer (test `text_layout::spacing_in_uniformly_scaled_type_takes_the_scale`); tracked type scaled horizontally alone still differs a little there, as before. A `.ai` saved here writes the same values as before; VectorCraft now lays them out as the file's own PDF part draws them. Scores and estimates unchanged. | +| 2026-11-11 | minor | `.ai` and EPS import: stroked type in an envelope with Distort Appearance is tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, for a stroke on its appearance or on a group round it as well as its characters'; it was mapped from its bounds with strokes, which reach as far as a miter join may at a corner. Tests `ai::envelope::tests::stroked_type_is_tried_mapped_from_its_glyphs_grown_by_half_its_stroke`, `type_with_a_character_stroke_is_tried_mapped_from_its_bounds_with_strokes`, `a_stroke_on_a_group_of_type_grows_the_box_by_half_its_weight` (part of #3179) | +| 2026-11-11 | minor | `.ai` and EPS import: a warp of type (an envelope made with a warp around type) whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the warp grid the file saves, with the same drawn-art check, budget and page comparison as #6421: where it passes, the type is editable and keeps the file's shape, and the warp's settings (style, bend) are lost. A second try is only made while more checks are left than there are envelopes of type and warped text objects still to come. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its box with strokes, where the size the file saves for it doesn't already give that box (a rule chosen by measuring real files). An envelope's grid (warp, mesh or top object) now reads its way round from all its rows and columns, not its first row alone: a mesh bent far round (its end columns leaning more than halfway over) reads the way it runs, not turned a quarter round, and a grid symmetric about its middle reads the same wherever it is on the page. Tests `tests_native::a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its_text_changes`, `a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does`, `a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art`, `a_warp_of_type_tried_again_leaves_the_next_envelope_its_check`, `ai::tests::a_mesh_envelope_bent_far_round_opens_the_way_it_runs`, `a_mesh_envelope_bent_halfway_round_opens_the_same_way_wherever_it_is` (part of #3179) | +| 2026-11-11 | minor | `.ai` and EPS import: type stroked in the text document keeps its stroke's cap, join and miter limit (keys 61, 62 and 64 of its character attributes, numbered as PostScript's `setlinecap` and `setlinejoin`: 0 butt or miter, 1 round, 2 projecting or bevel). They were left at a miter join with a limit of 10 whatever the file said, so type the file strokes with round joins, or with the usual limit of 4 or less, drew spikes at its sharp corners, some many points long. In users' files, used locally and never committed, the page strokes the type with the cap, join and miter limit these keys give; no file had a bevel join, which is read by the same numbering. A value that isn't one of theirs keeps the default, a miter limit past 500 is 500, and type without a stroke keeps the defaults. Dashes are not read: no file had dashed type to tell which keys hold them. Tests `ate::tests::a_run_keeps_its_stroke_cap_join_and_miter_limit`, `tests_native::stroked_type_keeps_its_cap_join_and_miter_limit`; scores unchanged | | 2026-11-10 | minor | `.ai` and EPS import: an envelope of type (a warp, a mesh or a top object around type) kept its drawn art, its type hidden, because the type is laid out from the text document only after the layers are read. It now waits for that: its text slots get their type, and where VectorCraft's own envelope of that type draws as the drawn art the file saves (the same check and budget as other envelopes, seen on white and on black), it opens live in the drawn art's place, its type editable in Edit Contents, and the hidden copy goes. As with other live envelopes, the layers with one are then compared with the page, which weighs the envelope as the art it draws (not as type laid out again, which the comparison allows more for), and when they don't draw as it the drawn art and the hidden type are put back. Layers used though they don't draw as the page (the editing data trusted, or the objects that differ coming in as the page's art) leave envelopes of type their drawn art and hidden type too. A `.ai` whose layers would open alone, without its PDF part, imports the PDF part to compare them with, and should they still not draw as it, or should no envelope of type open live, they open alone as before, with the envelopes' drawn art. Type in a font that isn't available, slots without type of their own (threaded, bound to a text or a visibility variable, a wrap object, type a look draws), envelopes in a symbol's or a pattern's art, and envelopes that draw differently keep their drawn art, with the note (#3179). Tests `tests_native::an_envelope_of_type_that_draws_as_its_drawn_art_opens_live`, `an_envelope_of_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_white_type_that_draws_apart_from_its_drawn_art_keeps_it`, `an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone`, `an_envelope_of_type_that_draws_apart_from_the_page_does_not_open_live`, `trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_drawn_art`, `layers_with_objects_that_come_in_as_the_page_art_leave_an_envelope_of_type_its_drawn_art`, `an_envelope_of_type_bound_to_a_visibility_variable_keeps_its_drawn_art` | | 2026-11-10 | minor | `.ai` save: a variable font's record in the text document's font set names the type's place in the font's design space (`/4`, each `fvar` axis as 16.16 fixed: the named instance's setting, or the run's own Variable Font setting) and the font's version (`/5`). Without them, type in a named instance such as Bold opened at the font's default instance in the app that opens the file. Two settings of one font are now two fonts of the set; a static font's record is unchanged. The record's form comes from the public report in #6388. Test `ai_editing::tests::variable_font_instances_name_their_design_space` (#6388) | | 2026-11-10 | minor | `.ai` and EPS import: an envelope of type, which keeps its drawn art with its type hidden, now says so in the import notes ("type in an envelope comes in as the envelope's drawn art, not as editable type"); nothing said it before, while the other envelopes that keep their drawn art have a note. The type is still not editable in the envelope (part of #3179). Test `tests_native::envelope_options_keep_the_source_text_hidden_under_its_outlined_appearance` | diff --git a/docs/gaps.md b/docs/gaps.md index ddc02a2d00..19376c4bf2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -34,6 +34,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | | 2026-11-08 | minor | #3380, deletion only: preserve gradient placement and exact surviving geometry; consume owned subpaths with a shared original-node snapshot; consolidate status/evidence and document command/helper contracts. Compound behavior and the existing M2 status entry are retained. Endpoint highlighting remains open; scores and estimates unchanged. | | 2026-11-07 | minor | #3380 (deletion only): independent surviving path objects; transformed appearance, stacking, selection, cubic handles and Undo/Redo covered by `delete_path_pieces`; compound semantics retained. Endpoint highlighting remains open; scores and estimates unchanged. | | 2026-11-06 | minor | G9: EPS import reads gradients a page paints as abutting strips as one linear gradient each (no seams); an Illustrator EPS whose page drew them that way keeps its layers. Estimate unchanged. | @@ -89,7 +90,7 @@ stage ([ROADMAP.md](../ROADMAP.md)). | 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 0 | no | [effects-parity.md](effects-parity.md) | | 9 | [G13 Illustrator 2026 (30.x) additions](#g13-illustrator-2026-30x-additions) | 13–23 | no | [target-app-parity.md](target-app-parity.md) | | 10 | [G14 Pen hardware beyond Windows pressure](#g14-pen-hardware-beyond-windows-pressure) | 4–10 | Wayland pressure | [hardware-parity.md](hardware-parity.md) | -| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 9–19 | no | [target-app-parity.md](target-app-parity.md) | +| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 7–17 | no | [target-app-parity.md](target-app-parity.md) | | 12 | [G3 3D and Materials](#g3-3d-and-materials) | 25–45 | no | [effects-parity.md](effects-parity.md) | | 13 | [G7 Views and windows](#g7-views-and-windows) | 15–25 | no | [ui-parity.md](ui-parity.md) | | 14 | [G6 Automation and scripting](#g6-automation-and-scripting) | 4–8 | no | [target-app-parity.md](target-app-parity.md) | @@ -211,19 +212,14 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi art with strokes, gradients or patterns) and type with an Art brush keep the drawn look. - **Missing:** faithful layer and group structure from the editing data in real files (#951: 109 layers instead - of 14), open speed on large files (#758), live effects, Scatter, Art, Pattern and Bristle brushes on paths, a - path's own Calligraphic brush settings, and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). A PDF-compatible `.ai` carries an editing copy of the art in the form + of 14), open speed on large files (#758), live effects, Scatter, Pattern and Bristle brushes on paths, the Art + brushes listed above as keeping the drawn look, a path's own Calligraphic or Art brush settings, and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). A PDF-compatible `.ai` carries an editing copy of the art in the form VectorCraft's reader reads (layers, groups, paths, colors, gradients, patterns, images, transparency, opacity masks, clipping, type as text and symbols), with live effects kept only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, other objects' effects other than geometry effects left out, and live objects written as their art ([file-format-parity.md](file-format-parity.md)). Save As `.ai` › Version: Legacy (version 7) writes the PostScript form from the published version 7 specification, keeping layers (names, order, visibility, lock), groups, compound paths, clipping groups, gradients and - of 14), open speed on large files (#758), live effects, Scatter, Pattern and Bristle brushes on paths, the Art - brushes listed above as keeping the drawn look, a path's own Calligraphic or Art brush settings, and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope - (undocumented): a PDF-compatible `.ai` opens in Illustrator 2018 without its layers and groups (#868). Save As - `.ai` › Version: Legacy (version 7) writes the PostScript form from the published version 7 specification - instead, keeping layers (names, order, visibility, lock), groups, compound paths, clipping groups, gradients and images, and type as editable text objects (or outlines), one artboard per file (an artboard picker chooses which); transparency, live effects and object names don't survive it (transparent images are flattened or omitted, hidden objects go to a hidden layer, are omitted or made visible), and type is set again in the @@ -622,9 +618,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi symbol static drops them; stored in the native format. Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); symbol libraries ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol - Libraries Menu open each library in a library panel of its own (three original libraries generated in code, - Basic Shapes, UI Frames with default 9-slice guides on Panel, Button and Bar, and Map Markers with Pin, - Flag, Crosshair and Checkpoint; User Defined; Other + Libraries Menu open each library in a library panel of its own (four original libraries generated in code, + Basic Shapes, UI Frames with default 9-slice guides on Panel, Button and Bar, Map Markers with Pin, + Flag, Crosshair and Checkpoint, and Inventory Icons with Sword, Shield, Potion, Key and Gem; User Defined; Other Library… reads the symbols of any document VectorCraft opens); a click adds a symbol to the document's Symbols with its Symbol Options and the resources it uses, as one undo step, and dragging one onto the canvas also places it; Save Symbols / Save Symbol Library writes the @@ -648,14 +644,15 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Direct Selection of a path, compound path or type inside a dynamic instance also takes opacity and blend (`transparency.set`) and a gradient or pattern fill or stroke (`paint.setFill` / `paint.setStroke`, Eyedropper), for that instance only; - graphic style libraries (Window › Graphic Style Libraries; seven original libraries generated in code, including - Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert; User Defined; Other + graphic style libraries (Window › Graphic Style Libraries; eight original libraries generated in code, including + Game HUD with Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine and Boss Alert, and Status Effects + with Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade and Shield Buff; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the five shipped (and further graphic-style libraries beyond the seven shipped, and further symbol libraries beyond Basic - Shapes, UI Frames and Map Markers; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; +- **Missing:** more built-in brush libraries beyond the five shipped (and further graphic-style libraries beyond the eight shipped, and further symbol libraries beyond Basic + Shapes, UI Frames, Map Markers and Inventory Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write; Global Edit of groups holding type or images, rotated copies as matches and highlighting matches before the start; 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). -- **Estimate:** 8–18 h. +- **Estimate:** 6–16 h. ## G3 3D and Materials @@ -671,6 +668,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** Selection artwork drag across visible document tabs (400 ms hover); lossless target copy, source/clipboard preservation and cancellation regressions. Cross-window dragging remains separate. +- **Done (#5239):** a double-click on a ruler adds a guide at the pointer (vertical on the top ruler, horizontal on the left one, swapped in a view turned 90°; both clicks on that ruler) through `guide.add`, unsnapped and in one undo step; no scored gap or estimate reassessed. - **Done:** custom document ruler origin (#1212): corner drag with preview, double-click reset to the active artboard, relative X/Y inputs and native save/reopen. - **Done:** View › Rulers › Change to Global / Artboard Rulers (`view.globalRulers`, Cmd+Alt+R): artboard rulers, a new document's, count from the active artboard, each artboard with its own zero point; rulers, X/Y fields and guide readouts follow the mode, which is saved with the document. Estimate unchanged. - **Done (#2849):** View › Rulers › Show Video Rulers (`view.videoRulers`): the rulers show and count the active artboard in video pixels from its top-left corner, a pixel as many points wide as the artboard's Video Ruler Pixel Aspect Ratio and one point tall ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)); Hide Video Rulers returns them to the General unit and the ruler origin. Shift-snapping a new guide to ruler ticks still uses the General unit's ticks. Estimate unchanged. @@ -689,9 +687,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the document object model for scripts, a script console, the Scripts folder and script - directives (#1183 is open). File › Scripts › Other Script… and `script.run` run JavaScript files over the - command registry. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and +- **Missing:** the document object model for scripts and the `#targetengine` and `#engine` script directives (#1183 is + open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, + File › Scripts lists the scripts of the Scripts folder, and + Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and export, and full agent control over MCP are done. - **Estimate:** 4–8 h. - **Done (2026-10-16):** the MCP server hears the client during a long call: `notifications/cancelled` stops a queued or running export (PDF pages, flattening, baking, drawing, artboards) without writing anything or changing the document, `ping` and the list methods answer at once, any other request that would wait behind a call running for two seconds or more is refused as busy (`-32003`, naming the call), and `_meta.progressToken` gets page progress (#2165, #2171, #2172). Reading the document during an export is not served (refused as busy); estimate unchanged. @@ -853,6 +852,8 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | G5: built-in Status Effects graphic style library (Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade, Shield Buff); Missing trimmed; estimate 7–17 → 6–16 h; MCP docs list UI Frames and Map Markers under Symbol libraries. | +| 2026-11-11 | minor | G5: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem; no default 9-slice); Missing trimmed; estimate 8–18 → 7–17 h. | | 2026-11-10 | minor | G4 type: Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, #4936; the Check Spelling dialog remains; scores and estimates unchanged. | | 2026-11-10 | minor | Tidy-up, no content change: in Feature submission evidence, a stray table row and two "PR #NNNN revision" notes move into Feature revisions, the three "Feature evidence last updated" lines become one, the duplicate Flyout update note goes (its row stays), and eight reconciliation rows become two. Scores and estimates unchanged. | | 2026-11-10 | minor | G5: built-in Game HUD graphic style library (Health Fill, Mana Glow, Damage Flash, Quest Outline, Coin Shine, Boss Alert); Missing trimmed; estimate 10–20 → 9–19 h. | diff --git a/docs/mcp.md b/docs/mcp.md index dac7a94b7e..7d66c7c0b3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -112,6 +112,9 @@ the suite) keep the agent to the folders you give it: export commands, Export for Screens, Package, Export for Web, print to file, `screenshot {path}`, library and preset saves to a path, the copies `links.relink {copy}` makes. - `file.list {path}` (through `run_command`) lists a folder's files and folders, held to the read roots like any read, so an agent can see what it was given (#1163). +- `file.recentFiles` and the control channel's `ui.menu.list` leave out the recent files outside the read roots. The + other File › Open Recent Files rows keep their ids (`file.openRecent3` still opens the third file), and + `file.openRecentN` for a file outside the roots ends with `no such recent file`, as an empty slot does. - Each flag may be given more than once (#3546): a path inside any of the read roots may be read, one inside any of the write roots written, so one session can read a project folder and a shared assets folder, or write to an output folder and a scratch folder, without widening a root to their common parent. A folder given twice @@ -588,13 +591,19 @@ the stored fill, or the stored stroke when no fill is stored and that stroke has outline, so these commands do not store a stroke paint or weight for a series that draws a band. Except for `paint.swap`, they still store a stroke opacity and blend mode set on a band, and the band's outline takes them. Graph designs keep their own paint. A row that had no -paint before the command and has none after it does not change what the graph stores. `paint.setFill`, +paint before the command and has none after it does not change the paint the graph stores. `paint.setFill`, `paint.setStroke`, `paint.none` and the commands that apply one paint kind to the other store the topmost row of the kind even when it is hidden, and store a stroke set on a band. `stroke.set`, `paint.editGradient` and the recolor commands do not store a series' paint. An `appearance.*` command or `graphicStyle.apply` given a series group's id, and `graphicStyle.redefine` on a series group linked to the style, edit the group's own rows, and the graph does not store them. +`text.setFormat` without `start` and `end`, on a graph or on its labels, stores the character and paragraph attributes +it sets for each kind of label it reaches (value axis numbers, category labels, legend labels), and every label of that +kind takes them when the graph is drawn again. The graph saves the paragraph attributes as `valuesPara`, +`categoriesPara` and `legendPara` in its label styles, and still sets each label's alignment for its place. The legend +leaves room for a legend label's stored indents, spacing and leading. + `effect.apply {"effect": "path.outlineObject"}` (Effect › Path › Outline Object) takes no parameters. Type that carries it is drawn, exported and expanded as its glyph outlines and stays editable type, and the effects after it reshape those outlines. On paths, compound paths and images it does not change what is drawn. @@ -836,7 +845,8 @@ page with hint tables saying where every other page's objects are), which stays `compatibility: "1.3"` writes a PDF 1.3 file, which has no transparency: a copy of the document is flattened first with `flattenerPreset` (empty: High Resolution; `high`, `medium`, `low` or a saved preset, `flattener.presets.list`) and `flattener` options over it (as `object.flattenTransparency` takes them); images with see-through pixels count as -transparency and rasterized areas are clipped to their regions. A file that would still have transparency fails the +transparency and rasterized areas are clipped to their regions. Layers the file leaves out (non-printing ones, unless +`includeNonPrinting` or `createLayers` is set) are left out of the flattening. A file that would still have transparency fails the export. PDF/X-1a and PDF/X-3 files are PDF 1.3 files too. A page with a side longer than 14,400 pt is written with a `UserUnit` (PDF 1.6): its longer side divided by 14,400, rounded up to the next thousandth, with the page's sizes and coordinates in those units, so that no side is longer than @@ -1371,7 +1381,7 @@ naming the key, and change nothing: `radius` in `shape.rectangle`; `sides` and ` in `shape.flare`; `decay` and `segments` in `shape.spiral`; `rows` and `columns` in `shape.rectangularGrid`; `concentric` and `radial` in `shape.polarGrid`; `size` and the `width`, `height` and `fitMinPercent` of `area` in `text.create`; `size` and `fitMinPercent` in `text.createInPath`; `start`, `end`, `size`, `tracking`, -`baselineShift`, `hScale`, `vScale`, `rotation` and `strokeWidth` in `text.setRangeStyle`; `start` and `end` in +`baselineShift`, `hScale`, `vScale`, `rotation` and `strokeWidth` in `text.setRangeStyle`; `strokeWidth` in `text.setStyle`; `start` and `end` in `text.editRange` and `text.getRange`; `at` in `text.startList`; `start`, `hScale`, `vScale` and `rotation` in `text.touchType`; `start` in `text.glyphAlternates` and `text.setGlyphAlternate`; `by`, `start` and `end` in `type.step`; `by` in `type.size.increase` and `type.size.decrease`; `size` in `type.ruby`; `width`, `height` @@ -1383,6 +1393,15 @@ and `amount` in `color.harmony`; `angle` in `paint.editGradient` and in the `gra `width` and `tolerance` in `livePaint.strokeEdge`. A null is read as a key left out. A gradient stop that names a swatch refuses a `tint` that is not a number with `` stop 0: `tint` must be a number ``. +`text.setStyle` refuses a `size` that is neither a number nor a length with a unit (`"12 pt"`, `"5 mm"`) with +`` `size` must be a number, not true ``, and a `tracking` that is neither a number nor a number written as a string +(`"20"`) with `` `tracking` must be a number, not false ``. It and `text.setRangeStyle` refuse a `font` or `style` that is not a string +with `` `font` must be a string ``, and a `features` list with an entry that is not a string with +`features must be a list of tags`; `text.setStyle` refuses such a `justify` too. `type.ruby` refuses a `text`, +`position` or `align` that is not a string, and `text.setPathHandle` refuses a `which` other than `in` or `out` with +`` `which` must be one of in, out ``. Each leaves the document, the selection and the undo history as they were, also +when the call gives another param it could apply. A null is read as a key left out. + A byte offset must be a whole number of at least 0. `at` in `text.startList`, and `start` and `end` in `text.editRange`, `text.getRange` and `text.setRangeStyle`, and in `type.step` and `addon.type.textTweaker` given an `id`, refuse a negative or fractional number with @@ -1540,7 +1559,7 @@ describes that menu item. Pass exactly one of `path` and `source`. A `path` must case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and `ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the -app through one global object: +app through the global object `vc`, and writes to the Script Console and runs other files through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it @@ -1549,10 +1568,105 @@ app through one global object: - `vc.document` is a snapshot of the active document, or `null` when none is open. A snapshot too large to cross throws a `RangeError`. - `vc.commands` lists the commands a script may run. -- `vc.log(value)` adds a value to the report. +- `vc.log(value)` adds a value to the report and a line to the Script Console. +- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and + `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. +- `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global + environment, so its functions and variables stay defined, and returns its last value (`undefined` for an empty + file). Its preprocessor lines are read as the script's are. `timeout` is a number of milliseconds from 0; the file + is read at once and `timeout` is not waited on. The run's fuel and limits apply to the file. An empty path, a + missing file and a refused path throw errors the script can catch. +- `$.fileName` is the file being run, which is the file `$.evalFile` is running while it runs, and is empty for a + script given as `source`. `$.includePath` is the current `#includepath` list, separated by `;`. +- `alert(message[, title, errorIcon])`, `confirm(message[, noAsDflt, title])` and `prompt(message, preset[, title])` + open a dialog, described below. `vc.api.has("dialogs")` is true. - `vc.args` is the `args` object. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. +Before any of the script runs, its preprocessor lines are read. The help page +https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and +https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/ describes `$.evalFile`, `$.fileName` +and `$.includePath`. A line counts when it starts with `#` or `//@`, after blanks only, outside strings and comments. +VectorCraft reads them by these rules of its own: + +- `#include "file"` and `//@include "file"` put the text of that file in place of the line. A value with spaces or + punctuation goes in single or double quotes. The file is looked for beside the file that includes it, then in each + `#includepath` folder in turn, then in each folder of the `JSINCLUDE` environment variable (absolute folders + separated by `;`). The included file must be a whole script on its own. A file may be included again after its + earlier inclusion has ended, and a file that includes itself, directly or through others, is an error. +- `#includepath "a;b"` sets the folders `#include` looks in, separated by `;`. A relative folder is relative to the + folder of the file that includes. A later `#includepath` replaces the list. +- `#script "name"` names the run in the report and the Script Console, unless `name` is given. A `#script` line in an + included file does not rename the run. +- `#target` takes any value and does not change how the script runs. +- `#strict on` turns on the checks the dollar-object help page gives for `$.strict`: an assignment to a read-only + property throws a `TypeError`, and so does adding a property to an object that takes no new ones. By VectorCraft's + own rules, an assignment to a property with only a getter is checked as a read-only one, and the objects that take + no new properties are those that are not extensible: objects passed to `Object.preventExtensions`, `Object.seal` or + `Object.freeze`, and the frozen `vc` and `$` objects. Other objects take new properties as before. The rest of ES5 + strict mode (`with`, undeclared variables, `this` in a plain call) is unchanged; a script asks for it with + `'use strict'`. `#strict off` turns the checks off, and they are off in a script without either line. +- The last `#strict` line of the script and the files it includes sets the checks for the whole run. Code that `eval` + and `Function` compile takes the checks of the code that compiles it. A file `$.evalFile` runs takes the checks of + its own last `#strict` line, for its code and the functions it defines, or the caller's when it has none; the + caller's code keeps its own. Any value other than `on` or `off` ends the run with `#strict takes on or off`. +- `#targetengine` and `#engine` end the run with an unsupported-directive error, and any other `#name` with an + unknown-directive error. A `//@` line with another name is a comment. +- A script run from a file reads its included files and the files `$.evalFile` runs only in that file's folder and + the folders below it. A path with a `..` name, a path that leads out of the folder through a link or a junction, a + Windows device name or stream, and a computer on the network are refused, and so is every path for a script given as + `source`. A `JSINCLUDE` folder outside the script's folder is passed over. +- A missing or refused included file ends the run before any of it runs. An error in an included file or a file `$.evalFile` + ran is reported at that file's line and column, and the report's `file` names the file. So is an error `$.evalFile` + throws for a file it cannot run, such as a syntax error, when no `catch` takes it. When a `catch` takes that error + and a later `throw` raises it again, the error is reported where that `throw` is, as any other thrown error is. + +`$` also has the other members the Dollar object page lists, besides `$.evalFile`, `$.fileName` and `$.includePath` +above. Each run +starts with its own `$`: what a script changes there lasts until the run ends. The values and rules below are +VectorCraft's own, and `vc.api.has("dollar")` is true where they are available: + +| Member | In VectorCraft | +|--------|----------------| +| `about()` | `"VectorCraft script engine "`; no window opens | +| `appEncoding` | `"UTF-8"`; setting `"UTF-8"` is accepted, any other encoding throws a `RangeError` | +| `bp()`, `colorPicker()` | throw an `Error`: scripts have no debugger and cannot show a dialog | +| `build`, `version` | VectorCraft's version | +| `buildDate` | `null` | +| `decimalPoint` | `","` for a locale whose language writes a decimal comma (such as `de`, `fr`, `ru`), otherwise `"."` | +| `engineName` | `"VectorCraft"` | +| `error` | the last `Error` object the run threw, caught or not, or `null` before one | +| `flags` | `0`, or `512` while localization is on; only `0` and `512` can be set, and setting `512` turns `$.localize` on | +| `gc()` | does nothing; the interpreter collects its own garbage | +| `getenv(name)`, `setenv(name, value)` | only `LANG`, `LC_MESSAGES`, `LC_ALL` and `OS`; `getenv` of any other name returns `null`, and `setenv` of one throws. `setenv` changes the value for the rest of the run only, never the app's environment. A value has at most 64 letters, digits and `_ . - @` | +| `global` | the global object | +| `hiresTimer` | the microseconds since the run last read it, or since the run started; `0` on the web | +| `level`, `memCache` | `0`; setting `memCache` throws | +| `line`, `stack` | the line of the code that reads it; the running code, outermost first, one a line as `name:line` (`[global]` for the script's own code, `[anonymous]` for a function without a name), at most 64 lines | +| `locale` | the interface's language as a locale such as `de` or `pt_BR` (`en` when the interface follows the system); a script can set `ll` or `ll_RR`, and `null` or `""` sets the interface's again | +| `localize` | `false`; while `true`, `String(object)` of a localization object gives its text for `$.locale` | +| `os` | `Windows`, `macOS`, `Linux`, `FreeBSD`, `Unix` or `Web`, without a version | +| `screens` | an empty array | +| `sleep(ms)` | waits from 0 to 1,000 milliseconds between two frames of the app, without stopping it from drawing; `script.stop` ends the wait; it does not wait on the web; called with more than 0 inside a getter, a conversion, a callback of a built-in function or a file `$.evalFile` runs, it throws an `Error` instead of waiting | +| `strict` | `false` | + +Members that are values (`build`, `level`, `os` and the like) cannot be changed. A wrong value for a member that can +be set throws a `TypeError` or `RangeError`. + +`localize(object, ...values)` gives the text of a localization object, an object whose property names are locales +(https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/). It looks up the +locale with the platform's suffix (`_Win`, `_Mac` or `_Unix`; none on the web), the locale, its language with the +suffix, its language, and then `en`, and returns the object itself when none of them is a string property of it. No +getter runs. `%1` is replaced by the first value, `%2` by the second and so on, each once; a number with no value stays +as it is. A string as the first argument is used as the text. + +`toSource(value)` and `value.toSource()` write `undefined`, `null`, booleans, numbers, strings, arrays and plain +objects as the text of an expression that makes the same value, such as `({"a":[1, "x"]})`. A function, a getter, a +date, a regular expression, an error, a host object such as `vc`, an array with properties besides its elements, an +object whose prototype is not `Object.prototype`, a property that is not enumerable, or an object that contains +itself throws a `TypeError`. A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216 +characters throws a `RangeError`. + The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A run that changes no document adds no undo step. The journal records each command the run finished, as it records commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app @@ -1579,7 +1693,8 @@ VectorCraft sets these limits itself: | Limit | Value | |-------|-------| -| Source text | 8 MiB | +| Source text | 8 MiB a file, 32 MiB in all | +| Included and evaluated files | 64 in all, 16 levels deep, 1,024 paths looked up | | Heap | 256 MiB (128 MiB on the web) | | Host calls | 2,000,000 | | `maxFuel`, instructions in all | 1 to 100,000,000,000; 1,000,000,000 by default | @@ -1588,13 +1703,31 @@ VectorCraft sets these limits itself: | A value crossing to or from a command | 16 MiB and 1,048,576 entries | | `args` as JSON | 1 MiB | | Log | 10,000 entries and 4 MiB | +| Script Console | 2,048 lines and 1 MiB of text; 4,096 bytes a line; 256 bytes of a script's name | +| A dialog's message, title and prompt preset | 16 KiB, 256 bytes and 16 KiB | +| `answers` | 10,000 answers and 1 MiB as JSON | +| `dialogs` in the report | 10,000 dialogs and 1 MiB as JSON | | Growth before a person is asked | 100,000 objects and 512 MiB of new document data | In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and `ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends -with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls}`. -In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. -`answers` takes only an empty object, since scripts have no prompts yet. +with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, +runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`. In +the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The +report of a failed run has the same fields after `kind`, `message`, `line`, `column`, `file` (when the error is in +another file than the script) and `fuelLeft`. + +- `runTimeMs` is the time the script ran, its commands included. Waits between frames and for a person's answer are + left out. `timingAvailable` is false on the web, where `runTimeMs` is 0. +- `hostCallCounts` is `{vcRun, documentReads, commandListReads, vcLog, consoleWrites}`. +- `slowestCommands` lists at most 5 commands as `{id, calls, totalMs, maxMs}`, the longest in all first, then by id. +- `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as + text. +- `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for + `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` + for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the + run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and + `dialogsTruncated` is true when the list stopped at its limit. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} @@ -1604,6 +1737,124 @@ In the app the reply is `{running: true, name}`, and the report appears later as vectorcraft-cli run --cmd script.run --params '{"path": "Tidy Layers.js", "args": {"margin": 12}}' ``` +The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/user-notification-dialogs/ +describes the three dialog functions. A script calls them as globals: + +- `alert(message[, title, errorIcon])` shows the message with OK, and an error icon when `errorIcon` is true. It + returns `undefined`. +- `confirm(message[, noAsDflt, title])` shows the message with Yes and No. Yes is the default button, and No is the + default when `noAsDflt` is true. It returns `true` for Yes and `false` for No. +- `prompt(message, preset[, title])` shows the message and a text field that starts with `preset`, with OK and + Cancel. It returns the field's text for OK, an empty string included, and `null` for Cancel. + +The message, the preset and a given title are read as `String(value)` gives them, and `errorIcon` and `noAsDflt` as +`Boolean(value)` gives them. A title that is left out or `undefined` is Script Alert. A call without a message, or a +`prompt` without a preset, throws a `TypeError`. A message or a prompt's preset longer than 16 KiB, or a title longer than +256 bytes, throws a `RangeError` and opens no dialog. The dialog shows line feeds, carriage returns and the two +together as line breaks, and other control characters as their Unicode Control Pictures. The title stays on one +line, with line breaks shown as Control Pictures too. + +In the app, the run waits at the call until the person answers, and spends no instructions while it waits. Enter +gives the default button's answer. Escape gives Cancel for a prompt, No for a confirm and Stop for an alert. Every +dialog also has Stop, which ends the run as `script.stop` does and puts back every document. A dialog can open only +from the script's own code: called inside a callback of a built-in function such as `Array.prototype.forEach`, a +getter, a `toString` conversion or a file `$.evalFile` runs, it throws an `Error`. The code of an `#include` file +is part of the script's own code, and its dialogs open as the script's do. Quitting while a dialog waits asks whether to stop the +script, and Cancel shows the dialog again with the text typed so far. In the app, `ui.dialog.confirm` answers the +open dialog (kind `scriptDialog`) with its `answer` field (`ok`, `yes`, `no`, `cancel` or `stop`), or with the +default button's answer when `answer` is left out. A prompt's `value` longer than 16 KiB is an error, and the +dialog stays open. + +A run with nobody to ask takes its answers from `answers`, a list of `{kind: "alert", value: "ok"}`, `{kind: +"confirm", value: true}` or `{kind: "confirm", value: false}`, and `{kind: "prompt", value: text}` or `{kind: +"prompt", value: null}` for Cancel. Each dialog takes the next answer in order, callbacks of built-in functions +included. The run ends with an error that the script cannot catch, and every document goes back, when no answer is +left, when the next answer is for another kind of dialog, or when the script ends with answers it did not use. +`script.run` refuses a list that is malformed, longer than 10,000 answers or larger than 1 MiB before the run starts, +and refuses any answers for a run in the app, where the person answers. An omitted `answers`, an empty list and an +empty object are the same. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' +``` + +Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and +`$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message` (or `name: file:line:column: message` when the error is in another +file), its end, and a report of +its time, host calls and slowest commands. Each line shows the run's number and the script's name. Line feeds, +carriage returns and the two together break lines, and other control characters show as their Unicode Control +Pictures. The console keeps at most 2,048 lines and 1 MiB of text and drops the oldest lines past that. A line longer +than 4,096 bytes, and a script's name longer than 256 bytes, is cut with `…`. When the console has dropped or cut any lines, a note at the top counts them. The panel lays out only the +rows in view. Click a line to select it and Shift-click to extend the selection. Clear, Copy Selected and Copy All are +at the bottom of the panel and in its menu. Output goes on while the panel is closed. + +- `script.console {}` returns `{lines: [{run, name, kind, text}], droppedLines, truncatedLines}`. `run` is the + run's number in the session, and `kind` is `start`, `output`, `log`, `error`, `end` or `report`. An end line's text + is `ended:`, a space, and then `finished`, `error`, `fuel`, `hostLimit`, `limit`, `stopped` or `internal`. A report + line's text is the run's time (`12 ms`, or `time unavailable` on a platform without a clock), a comma and its host + calls (`1 host call`, `2 host calls`), then `; slowest:` and the slowest commands when any were timed. The panel + shows the same text in the interface language. Every run that starts gets an end line. When a run is no longer + available, its end line is `stopped` if the run was abandoned and `internal` if the next slice found it missing, and + no report line follows. +- `script.console.clear {}` empties the console, sets its counts to zero and returns `{cleared}`. A running script + goes on writing, and `scriptReport` keeps the last run's console. +- `ui.copyScriptConsole {first?, last?}` copies lines `first` to `last` to the clipboard as the panel shows them, or + every line when both are left out. When the console has dropped or cut any lines, a copy of every line starts with a + line that counts them. Pass both or neither. It returns `{lines}`, which does not count that line. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "$.writeln(\"layers: \", 3);"}' +``` + +File › Scripts lists the scripts of the `Scripts` folder next to the preferences: `~/Library/Application +Support/VectorCraft/Scripts` on macOS, `%APPDATA%\VectorCraft\Scripts` on Windows, and +`$XDG_CONFIG_HOME/vectorcraft/Scripts` or `~/.config/vectorcraft/Scripts` on Linux and BSD. VectorCraft does not make +the folder: create it, and put `.js` or `.jsx` files in it. Each file is a menu item named after the file without its +extension, and each subfolder is a submenu that holds the scripts in it. The help page +https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html and +the page https://ai-scripting.docsforadobe.dev/introduction/executingScripts/ describe a Scripts folder listed this +way. The listed scripts come first in the menu, above Check Script… and Other Script…. Choosing one runs the file as +`script.run` runs a file, without the warning that Other Script… shows. + +The rest of this section is VectorCraft's own rules: + +- The folder is read when the app starts, each time its window becomes the active one, and, where the menus are in + the window (Windows, Linux and BSD), each time the File menu opens. A script added while VectorCraft runs is listed + after the next of these. A read takes names only, never a script's text, and runs off the UI thread, one read at a + time. +- Each level is sorted by label without regard to case, with scripts and subfolders mixed. A script whose label + another row of its folder has (`Tidy.js` beside `Tidy.jsx`, or beside a subfolder `Tidy`) shows its whole file name. +- A symbolic link or a Windows junction is never followed: a linked file or subfolder is left out, and a `Scripts` + folder that is itself a link is not read. Names that start with a dot, files and folders Windows marks hidden or + system, names that are not Unicode, names longer than 255 bytes and subfolders without a script are left out too, + and a listed script that is marked hidden or system, or lies in a folder marked so, by the time it is chosen does + not run. +- One read looks at 2,048 folder entries at most, lists 512 scripts and reads 128 subfolders, 4 levels deep, for at + most 250 ms. A label longer than 128 characters is cut, and control and bidirectional formatting characters in a + name are shown as `\u{…}` escapes. When a read stops at a limit or cannot read a subfolder, the menu keeps what it + found and shows `Some scripts were not listed`. The menu also shows that note, and leaves the rows out, when a + read finds new names after the menus have shown 16,384 different script and folder names since VectorCraft started. + When the folder is there and cannot be read, the menu shows + `The Scripts folder cannot be read`. +- A listed file is checked again when it is chosen. A file that is gone, is no longer a `.js` or `.jsx` file under + the folder, or is or lies behind a link ends with `the script is no longer in the Scripts folder`, and nothing runs. +- The web build has no Scripts folder, and neither has a run with `VECTORCRAFT_NO_PREFS` set. + +`script.listInstalled {}` returns the same listing: `{folder, scripts: [{path, label, folders}], truncated, +unreadable}`, with the scripts in menu order and `folders` the labels of the subfolders a script is in. `folder` is +`null` without a Scripts folder. `ui.runInstalledScript {path}` runs one of them by the `path` the listing gave, as +its menu item does. Under `--automation-read-root`, `script.listInstalled` lists the folder only when the folder lies +inside a read root, `ui.runInstalledScript` runs a script only when the script lies inside one, and `ui.menu.list` +leaves out the listed scripts outside the read roots. + +```json +{"name":"run_command","arguments":{"command":"script.listInstalled","params":{}}} +``` + +```sh +vectorcraft-cli run --cmd script.listInstalled --params '{}' +``` + ## Transparency and opacity masks Transparency and opacity-mask commands take `ids` (or `id`), so they need no selection. Opacity is a percentage @@ -1977,6 +2228,12 @@ Guides off, View › Snap to Point pulls it onto anchors. In the desktop app a g same way and is made where it is released over the canvas (with the Artboard tool, as an artboard guide of the active artboard), a guide dropped off the canvas onto its ruler is deleted, and hidden guides (View › Guides › Hide Guides) can't be picked. An artboard guide is picked, drawn and snapped to across its artboard only. +Preferences › Guides & Grid › Artboard Guides with Cmd/Ctrl + Ruler Drag (`cmdRulerDragArtboardGuides`, off by +default) is VectorCraft's own option. With it on, Cmd/Ctrl held when a drag leaves a ruler makes the guide an artboard +guide of the active artboard, with any tool but the Artboard tool, and with the Artboard tool a canvas guide. The key +is read when the drag starts, so letting it go during the drag keeps the kind of guide. Such an artboard guide shows, +and is made, only where it lies within the active artboard: a vertical guide between its left and right edges, a +horizontal guide between its top and bottom. Released anywhere else, it makes no guide and no undo step. ```json {"name":"run_command","arguments":{"command":"guide.add","params":{"vertical":true,"pos":100}}} @@ -1999,7 +2256,8 @@ already walks Image Trace. Short agent entry points: a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; dragging a guide on the canvas in symbol editing mode sends `nineSliceGuides` in one undo step; `type` is Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), - `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask), `symbol.replace`, + `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask; a hidden or locked instance's + art stays hidden or locked and is not selected), `symbol.replace`, `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the @@ -2602,7 +2860,8 @@ Every 3D type, `threeD.classicExtrude` and `threeD.revolve` included, also appli symbol instance, alone or in a group, and builds from the art it shows, the same way for the canvas, exports and `assets.add3D` ([three-d.md](three-d.md#clipping-groups-blends-and-symbol-instances)); like a group, it takes the effect on the object itself, not on a fill or stroke. An image, alone or in a group, is refused with "trace it first -with Object › Image Trace › Make", and nothing changes. +with Object › Image Trace › Make", and nothing changes. On a group, an opacity mask on a member, or on a group inside +it, masks that member's solids ([three-d.md](three-d.md#groups)). `threeD.extrude`: `depth` (points, 0..2000, default 50), `twist` (degrees, 0..360, 0), `taper` (1..100%, 100), `cap` (true solid, false hollow), `bevel` (`none`, `classic`, `rounded`, `cove`, `step`, `ogee`), `bevelWidth` @@ -2831,7 +3090,7 @@ as a value left out. ## Graphic style libraries Graphic style libraries are read-only sets of graphic styles generated in code (Shadows and Glows, Outlines and -Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD). `graphicStyle.libraries` lists them +Rules, Hand-Drawn, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD, Status Effects). `graphicStyle.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `graphicStyle.library {library}` returns one's styles in the `graphicStyle.list` shape (`library` is an id or a name). `graphicStyle.addFromLibrary {library, name? | names?}` copies styles into the document's Graphic Styles as one undo step (no names: the whole library); styles the @@ -2855,7 +3114,8 @@ with the same extension and bytes as one there, loads as that User Defined libra ## Symbol libraries -Symbol libraries are read-only sets of symbols: one generated in code (Basic Shapes), the `.vectorcraft` files in +Symbol libraries are read-only sets of symbols: four generated in code (Basic Shapes, UI Frames, Map Markers, +Inventory Icons), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the symbols of any document loaded with `symbol.loadLibrary`. `symbol.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `symbol.library {library}` returns one's symbols (`name`, `size`, `registration`, `exportType`; `library` is an @@ -3061,9 +3321,18 @@ one undo step. The targets split into groups of overlapping objects; groups with Each other group becomes one group of atomic regions: paths filled with the flat colour the art showed there (over white, which blend modes do not read; over nothing, keeping alpha, with `preserveAlpha: true`), plus one image where gradients, patterns, images, opacity masks or raster effects reach (clipped to those regions with `clipComplexRegions`, a rectangle without). +The image leaves out the part of such art that the clipping path of a clip group or clipping layer hides, so art under +the hidden part of a cropped picture stays as it is. Transparent art that such a clipping path hides entirely is +removed. A group that holds art from inside and outside a clipping layer goes in the place of the topmost art outside +it. When that layer prints, shows or is a template where the clipping layer differs, the clipping layer or a group +around the art has opacity, a blend mode or isolation, or the clipping path has a fill, +the group holds only the art inside the clipping layer, drawn over the fill and over the art below in the same kind of +layer as its own layers draw it (over nothing with `preserveAlpha`), and the art outside is flattened on its own. `preset` is `high`, `medium` (the default) or `low`; option keys (`balance` 0–100, `lineArtPpi`, `gradientPpi`, `textToOutlines`, `strokesToOutlines`, `clipComplexRegions`, `antiAlias`, `preserveAlpha`, `preserveOverprints`) -override it, at the top level or in `options`. `balance: 0` rasterizes everything; lower balances rasterize groups +override it, at the top level or in `options`. An image that would be larger than 64 million pixels or longer than +32,768 pixels a side at `lineArtPpi` or `gradientPpi` is made at the highest resolution that fits, so a long area is +rasterized whole. `balance: 0` rasterizes everything; lower balances rasterize groups that split into many regions. The result reports `{ids, vector, rasterized, options}`. When an image in the art can't be decoded, the image that replaces the art does not show it, and the result also carries `warning`: "an image couldn't be decoded and is missing from the picture", the note raster exports give. @@ -3093,8 +3362,16 @@ The pattern commands (`object.pattern.make`, `object.pattern.edit`, `object.patt `object.repeat.options`) reject a param of the wrong type, such as `"instances": "8"`, `"edit": "false"` or `"tileType": 2`, and change nothing. `pattern.options` also rejects an `overlap` that is not an object, and an `overlap.h` other than `left` or `right` or an `overlap.v` other than `top` or `bottom`. `object.repeat.options` rejects -a `center` that is not `[x, y]`, and `object.repeat.radial` rejects a negative `radius`. Omitting a param or giving null -keeps its default. +a `center` that is not `[x, y]`, and `object.repeat.radial` rejects a negative `radius`. In `object.pattern.make`, +`object.pattern.saveCopy`, `object.repeat.radial`, `object.repeat.grid` and `object.repeat.mirror`, omitting a param or +giving null keeps its default. In `pattern.options` and `object.repeat.options`, omitting a param or giving null keeps +the pattern's or the repeat's current value, with two exceptions. A brick `tileType` in `pattern.options` or a brick +`gridType` in `object.repeat.options` with `brickOffset` omitted or null sets the offset to 0.5. While `sizeTileToArt` +is on, each `pattern.options` call sizes the tile to the art plus `hSpacing` and `vSpacing` again and ignores `width` +and `height`, so a new `hSpacing` changes the tile's width. `pattern.options` still rejects a non-null `width` or +`height` that is not a positive number, such as `"width": 0`, and changes nothing. Without a `name`, +`object.pattern.edit` edits the pattern that fills or strokes a selected object, and `pattern.options` changes the +pattern being edited; each returns an error when there is no such pattern. `pattern.delete` requires `name`. ```json {"name":"run_command","arguments":{"command":"pattern.options","params":{"showSwatchBounds":true}}} @@ -3450,7 +3727,10 @@ holds symbol instances that `object` expands, whether only their art holds it, w `object` on), and `object.mesh.create` on a gradient-filled object colours the mesh points as the gradient paints them, with the colors Object › Expand gives them. `object.expand`, `effect.expandAppearance`, `type.createOutlines` and `object.path.outlineStroke` turn a dimension whose -art they change into a plain group of that art, in the same undo step (see [dimensions.md](dimensions.md)). +art they change into a plain group of that art, in the same undo step. `object.expand`, `effect.expandAppearance` and +`object.path.outlineStroke` leave a dimension selected with art it measures, directly or in groups without fills, +strokes or effects of their own, as it is and change only the other art; if the new art no longer fits the dimension's +link, the dimension stays where it was, no longer linked (see [dimensions.md](dimensions.md)). `object.expand` rejects a param of the wrong type, such as `"fill": "yes"`, `"gradient": 3` or `"steps": "16"`, and changes nothing. Omitting a param or giving null keeps its default. @@ -3528,7 +3808,10 @@ step. `svgFilter.apply {name, ids?|id?, item?}` applies one as the live effect ` in one undo step. The effect (`{name, xml, scale, origin}`) names the document's filter: editing the filter changes what every object that uses it draws, in the edit's one undo step, and an application after an edit takes the edited filter. Deleting a filter that objects use leaves their effects in place, still named, drawing nothing (their `xml` -empty) until a filter of that name is defined or imported again. Opened from such an effect, Apply SVG Filter shows the +empty) until a filter of that name is defined or imported again. A pasted effect that names one of the document's +filters but draws another definition keeps its own filter under a free name (`Soft 2`); pasted back into the document +it was copied from, it takes the document's filter. The free name is one that no filter of the document and no effect in +its art, brushes or graphic styles uses; when no such name keeps the filter within 64 KB, the paste is refused. Opened from such an effect, Apply SVG Filter shows the name above the list, not selectable. `effect.apply {effect: "svg.filter", params: {xml}}` takes a filter directly and names it by its `id`; an `xml` that isn't one such filter is an error. `ui.svgFilterDialog {}` opens Apply SVG Filter (New, Edit, Delete, Import…), and from the Appearance panel it edits which filter an applied effect runs; @@ -3616,6 +3899,44 @@ the canvas (coordinates out of range)". `path.setHandle`, `path.moveAnchor` and `path.insertAnchor` edit subpath 0 when `subpath` is absent or null, and refuse a `subpath` that is not a whole number of 0 or more, such as 1.5, -1 or "1" ("missing integer `subpath`"); `path.split` refuses such an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. +`path.insertAnchor` keeps the direct-selected anchors and selected segments of the path on the same points: those +after the new anchor on its subpath are numbered one higher, and a selected segment that the new anchor splits stays +selected as its two halves, with the new anchor as an end of both that moves with them. Undo restores the path and +the selection in one step. + +`path.reshape {id, x, y, dx, dy, tol?, focal?, radius?}` (a Reshape tool drag) grabs the path at `x`, `y`, adding an +anchor there unless one lies within `tol` (3 by default), and moves that point by `dx`, `dy`. +[Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) +has the Reshape tool stretch part of a path from the dragged point without losing the path's general form, with every +highlighted focal point pulling the path. Which anchors stay, how far the stretch reaches and the share of the drag each +point takes are VectorCraft's own rule. When `focal` is given (an empty list included), the grabbed point and the +anchors that `focal` lists as `[subpath, anchor]` pairs are focal points and move by the whole drag; a pair that names no anchor of the path is refused ("`focal` names [0, 7], which is +not an anchor of the path"). Anchors that are not direct-selected stay in place (on a path selected whole, or not +selected, every anchor is selected), and so do the two ends of an open path unless they are focal points. A selected +anchor between two focal points moves by the whole drag. A selected anchor between a focal point and an anchor that +stays takes `u² (3 - 2u)` of the drag, where `u` is its distance from the anchor that stays along the path's control +polygon (anchor, out handle, the next in handle, the next anchor) divided by the focal point's distance from it. A +handle takes the share on the tangent line of that curve at its anchor, so the handles of a smooth anchor stay in line +with it; a handle that is long beside that distance takes a share below 0 or above 1, and moves against the drag or +farther than the focal point. A closed subpath with every anchor selected moves whole, and a subpath with no focal +point does not move. An anchor added on a segment of a partly selected path is selected, and the other selected +anchors stay selected. With `radius`, only the grabbed point's subpath changes, whatever the selection: the anchors +within `radius` of the grabbed point along the path follow with a smooth falloff and the others stay; a negative +`radius` is refused ("`radius` must be 0 or more"), and so is `radius` given with `focal` ("`focal` and `radius` +cannot be used together"). Without `focal` (or with `focal` null) and without `radius`, the earlier rule applies, so +steps recorded before focal points play as they did: the selection does not matter, an open path stretches from the +grabbed point to its two ends as above, and on a closed path the anchors within half the diagonal of the subpath's +bounding box follow with the smooth falloff. The Reshape tool always sends `focal`. A drag of no length on an anchor +(`dx` and `dy` 0 or left out) leaves the path as it is and records no undo step. + +With the Reshape tool, a click on an anchor of a selected path makes it the focal point, and a click on a segment adds +an anchor there (one undo step) that becomes the focal point. Shift-click adds an anchor or a point on a segment to the +focal points. The rest of the tool's behavior is VectorCraft's own rule: Shift-click on a focal point removes it, and +the focal points belong to one path, so a click on another selected path starts again there. Each focal point shows a +filled anchor square in a larger hollow one. A drag from a focal point moves all of them; a drag from another point +moves that point alone as the focal point, with or without Shift (Shift keeps the drag's angle). After a drag the +focal points stay highlighted where it left them; Escape during a drag puts the path back and keeps them, and +switching to another tool clears them. These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, naming the key; the document does not change and no undo step is recorded: `t`, `dx` and `dy` in @@ -4500,7 +4821,8 @@ four: General (rulers, positions and sizes, the Info panel, dialog distances, ca (weights, dashes), Type (font size, leading, baseline shift) and East Asian Type (no field uses it yet). General is the active document's units (`document.inspect` → `units`): `document.setUnits {units}` (Document Setup) sets it for that document, and `prefs.set {key: "unitsGeneral", value}` sets it for the active document too (one undo step) and is the units -`file.new` starts in when it gets no `units`. Stroke, Type and East Asian Type are the preferences `unitsStroke`, +`file.new` starts in when it gets no `units`. With `documentUnits: false`, `prefs.set` sets only the preference and +leaves the document's units as they are; Reset Preferences followed by OK in the Preferences dialog does this. Stroke, Type and East Asian Type are the preferences `unitsStroke`, `unitsType` and `unitsAsianType`. Only `unitsAsianType` also takes `q` (Q, `Q`) and `ha` (Ha, `Ha`), each a quarter of a millimetre (0.709 pt); the other preferences, `document.setUnits` and the rulers do not list them, and it is Points by default. A length typed with a unit @@ -4525,12 +4847,33 @@ a string with a unit. Unit names: `Points`, `Picas`, `Inches`, `Millimeters`, `C settings whose label, section or category contains it, ignoring case, in the interface language or in English, or by "No settings found". Choosing a setting sets `__category` to its category, sets `__found` to its key (the row is highlighted until another category is shown) and clears `__search`. Cmd/Ctrl+F focuses the field again; Escape in the -field with text clears it, and Escape in the empty field closes the dialog. +field with text clears it, and Escape in the empty field closes the dialog. Its Reset Preferences button opens a +`resetPreferences` question (fields `message`, `detail`) over Preferences: `ui.dialog.cancel` shows Preferences again +as it was, and `ui.dialog.confirm` shows it again with every preference at its default value, applied by OK in +Preferences. `prefs.reset` resets the preferences at once, without the question. ```json {"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"unitsGeneral","value":"millimeters"}}} ``` +`prefs.export {path?}` writes the preferences as a JSON file, `{"format": "vectorcraft-preferences", "version": 1, +"prefs": {…}}`, and replies `{path, count}`; without `path` it replies `{data, count}` with the file's text. The file +holds every preference `prefs.list` lists and the `eyedropper`, `perspectiveWidget`, `pathfinder` and `glyphSnap` +groups. It leaves out the folder preferences (`fontsFolder`, `pluginsFolder`, `recoveryFolder`, `templatesFolder`) and +saved presets. An export over 1 MB, the most `prefs.import` reads, is an error and writes nothing. +`prefs.import {path | data}` applies such a file and replies `{imported}`, the number of preferences it +set. It checks every value first, as `prefs.set` does: a file over 1 MB, malformed JSON, another `format`, a newer +`version`, an empty `prefs`, 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. An import leaves the open +document's units as they are, records no undo step, and is saved with the other preferences. An open Preferences +dialog shows the imported values. `prefs.import` is refused as a `command.batch` step. The dialog's Export Preferences… and Import Preferences… buttons run the two +commands with a save or open dialog; the web build downloads the exported file and has no Import Preferences… button. +Exporting and importing preferences is an optional VectorCraft feature. + +```json +{"name":"run_command","arguments":{"command":"prefs.import","params":{"data":"{\"format\":\"vectorcraft-preferences\",\"version\":1,\"prefs\":{\"uiAccent\":\"green\"}}"}}} +``` + ## Document Setup `document.setup` with no params reports the document setup: units, the bleed ([top, bottom, left, right] in pt, drawn @@ -4732,7 +5075,7 @@ value: true}`; the Control bar's and Properties' Scale Artwork with Artboard che Artboard) makes its handle drags proportional and passes `scaleArt`, as do Properties' and the Transform panel's artboard size fields while the tool is in use. -`artboard.setProps {artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…], scaleArt?, moveArt?, …}` sets several +`artboard.setProps {artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…], scaleArt?, moveArt?, …}` sets several artboards in one undo step, each with its own fields; the other params apply to all of them. The art that moves or scales with each artboard is the art inside it before any of them changes, and an object inside several of them goes with the first one listed that moves or scales its art. An empty list and a list that names an artboard twice are @@ -4866,6 +5209,20 @@ is the width of one video pixel over its height, which `view.videoRulers` counts the native format keep both (written only when on or not 1), and `inspect_document` adds `showVideoSafeAreas: true` and `videoRulerPixelAspectRatio` to an artboard that has them. +Artboard Options' Guide Label: `artboard.setProps {index, guideLabel?: name | "#rrggbb" | null}` (or each entry of +`artboards`) gives the artboard a guide label, and `artboard.new` takes one too. The canvas draws the artboard's own +guides (`guide.add {artboard}`) in the label's color instead of the guide color preference, in the preference's style; +canvas guides, guides of an artboard without a label and guides whose artboard is gone keep the preference's color, and +selected guides are still drawn in the selection color. The value is a layer color's name, spelled exactly as Layer +Options lists it (`"Light Blue"`, `"Red"`, …), or `#rrggbb`; null clears it, and new artboards and older files have none. +The label is VectorCraft's own (no public documentation describes one): it is screen-only, so exports and print leave +it out, the paper and the artboard's background color stay as they are, and a locked artboard's label can change. +Anything else (a preset's index, another letter case, `#rrggbbaa`) is refused with "`guideLabel` is null, a layer +color's name or #rrggbb", and a list with a bad value anywhere changes nothing. Duplicates and copies keep it, the +native format writes it only when set (a preset index past the layer colors opens as none), and `inspect_document` adds +`guideLabel` (the name or `#rrggbb`) to an artboard that has one. `artboard.setProps` adds no undo step when nothing it +is given differs from the artboard. + Artboard Options' Global checkboxes are application preferences, not artboard properties: `fadeRegionOutsideArtboard` (Fade Region Outside Artboard) and `artboardUpdateWhileDragging` (Update While Dragging), both on by default (`prefs.set {values: {fadeRegionOutsideArtboard: false}}`; also Edit › Preferences › General › Artboard Options). With @@ -4943,7 +5300,8 @@ fills or strokes carry effects is written as one piece per fill and stroke, so o When an image in the art can't be decoded, `object.rasterize` and `object.cropImage` (without `trim`) make their image without it, and their results carry the `warning` that Flatten Transparency gives. `object.rasterize` takes each frame of threaded text that it rasterizes out of its thread with the text it shows, as `type.createOutlines` does (see -Threading text from the in and out ports), and the other frames keep the text they hold. +Threading text from the in and out ports), and the other frames keep the text they hold. `object.rasterize` +refuses an image larger than 64 million pixels or longer than 32,768 pixels a side, and the art stays as it was. ```json {"name":"run_command","arguments":{"command":"document.rasterEffectsSettings","params":{"resolution":"high","background":"white","addAround":36}}} @@ -5896,7 +6254,9 @@ as Overprint Preview shows them (darkened); either way the file has no overprint overprints. `flattenerPreset` (High Resolution, Medium Resolution, Low Resolution or a saved preset, `flattener.presets.list`) flattens transparency before printing, as Object → Flatten Transparency does; empty, a PDF keeps it live (PostScript, which has none, uses `file.print`'s `flattenerPreset`, else this one, else medium). -`printAsBitmap` prints each composite page as one image of the art at the document's raster effects resolution. +`printAsBitmap` prints each composite page as one image of the art at the document's raster effects resolution, +or at the highest resolution that fits when the image would be larger than 64 million pixels or longer than 32,768 +pixels a side. `color.profile` names an RGB or CMYK profile: composite PDF colours are converted to it with `color.intent` (CMYK colours keep their numbers with `preserveNumbers`), so a CMYK profile writes device CMYK; separations separate with a CMYK one. Settings saved before these options load with their defaults. @@ -6312,8 +6672,9 @@ with binding punctuation (`Tg`) on, which opens as `forced`. `none` isn't saved. `text.setFormat` and `text.setRangeStyle {tcyUpDown?, tcyLeftRight?}` set the Character panel menu's Tate-chu-yoko Settings of the characters, in points from -1296 to 1296 (document points, as `baselineShift`). In vertical type a block of tate-chu-yoko characters (`tateChuYoko`) moves up by a positive Up/Down and down by a negative one, and right -by a positive Left/Right and left by a negative one. The block moves as one piece with the values of its first -character, and keeps its one em down the column, its caret positions and its hit region. Two or three digits set +by a positive Left/Right and left by a negative one. On a vertical path, a positive Up/Down moves the block toward the +path's start and a positive Left/Right moves it to the path's left, with every path effect. The block moves as one piece +with the values of its first character, and keeps its one em down the column, its caret positions and its hit region. Two or three digits set across the column without the mark do not move, and horizontal type keeps the values without moving the characters. Neither value turns `tateChuYoko` on. Both are 0 by default and saved only when not 0, and character styles carry them. A value that is not a number is refused with `` `tcyUpDown` must be a number ``, and one outside the range with @@ -6632,6 +6993,9 @@ With Preferences › General › Anti-aliased Artwork off, the canvas draws all so does an export whose own Anti-aliasing option is None. SVG, PDF and EPS export draw the type unchanged. The native document such a file carries (an EPS VectorCraft wrote, or an SVG or PDF saved with Preserve Editing) keeps each frame's method, and opening the file restores it. +A graph label given a method keeps it for every label of its kind (value axis numbers, category labels or legend +labels) when the graph is drawn again; the graph saves it as `valuesAntiAlias`, `categoriesAntiAlias` or +`legendAntiAlias` in its label styles. Reset Panel sets Sharp. Saved as `antiAlias` only when not `sharp`. One undo step. ```json @@ -7008,7 +7372,26 @@ id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearanc `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them as ordinary paths with those paints; a result it refuses is drawn as if the effect weren't there, and `plugin.info`'s -`lastError` names the plug-in and the refused field. An exporter adds a write-only file format `plugin.` (listed by `document.formats`): +`lastError` names the plug-in and the refused field. While the app draws a document on screen, the live-effect plug-ins +of its first view share a 2,000 ms budget (VectorCraft's own value), and each run also keeps to its own 5,000 ms limit: +once the budget is spent no run starts, and a result that comes back after it is not used. 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 is deferred; the status bar +then says how many (`Opened with 3 plug-in effects deferred. Effect › Refresh Deferred Effects runs them.`). Later +drawings leave a deferred stage as it is until its input or parameters change, which runs it under the per-call limit. +`effect.deferredStatus {}` returns `{budgetMs: 2000, effects: [{objectId, effectIndex, item?, pluginId, reason}]}` for +the active document (`reason`: `budget`, `timeout`, `missing`, `failed` or `safeMode`; `item` is the fill or stroke +whose effect it is; `objectId` can be an object in the art of a symbol, pattern, brush or opacity mask; an empty list +when none is deferred). A stage whose object is deleted, or whose plug-in effect is +removed, moved from its place in the list or hidden (or whose fill or stroke is hidden), is no longer listed. `effect.refreshDeferred {ids?}` (Effect › Refresh +Deferred Effects, enabled while a stage is deferred) runs the deferred stages of those objects (default: all of them) +again with a fresh 2,000 ms budget and returns `{refreshed, stillDeferred, failed}`: `stillDeferred` counts stages left +out for want of time again, the stages of an object that is hidden or in a hidden group or layer, which is not drawn, +and the stages with a part of their input too small for the drawing the refresh makes, and `failed` those that +timed out, failed or have no plug-in. `id` names one object in place of +`ids`, and an entry that is not an object id of the document is an error. Each document has its own budget and its own deferred stages. Exports, Expand +Appearance and commands run every stage under the per-call limit, so an export never leaves out a stage that was only +deferred for time, and the canvas then draws the result. The web build measures the budget and the per-call +limit with the page's `performance.now()`. An exporter adds a write-only file format `plugin.` (listed by `document.formats`): `document.export {format: "plugin.", params?, path?}` writes it, as does a `path` ending in one of its extensions that no built-in format has. An importer adds a read-only file format `plugin.` (listed by `document.formats` with `read: true`, and `openExtensions` holds the extensions File › Open opens with it, without those a built-in format reads or that File › Open installs, imports or loads as something else, such as `.wasm` or `.ase`): `document.open {path | name, dataBase64, importer?: @@ -7487,8 +7870,12 @@ bounding-box handles scale it in plane space (`perspective.transform`; Shift kee centre), and `press_key` `5` during a drag switches the move to perpendicular to the plane (press again to switch back). Holding Shift during an in-plane move constrains each object's displacement to an axis or 45° diagonal of its own plane. `perspective.move` accepts `constrain: true` (default false) and adjusts Snap to Grid along the constrained -direction on the first object's plane and depth. With Snap to Grid, every object on the first object's plane moves -by the same plane offset, whatever its depth, and the edge of their joint bounds nearer a gridline lands on it. +direction on the first object's plane and depth. With Snap to Grid, an in-plane move moves every object on the first +object's plane by the same plane offset, whatever its depth. Without `constrain`, on each axis, the edge of their joint +bounds nearer a gridline lands on it when that edge ends within a quarter cell of the gridline. With `constrain`, an +edge also lands only when it ends within a quarter cell of a gridline: a horizontal or vertical move can land only an +edge on its own axis, and a 45° move lands the edge on the axis whose nonzero correction is smaller. When no edge on +those axes is that close, the move does not snap. A perpendicular move does not snap. `press_key` Escape during a move, a resize or a plane widget drag cancels it and puts the objects and the grid back. The arrow keys nudge a selection in perspective by the keyboard increment (`perspective.nudge`; Shift ×10, Alt copies). Object › Transform › Transform Again repeats the last perspective move or scale in plane space. diff --git a/docs/plugins.md b/docs/plugins.md index 026dcc0d9a..06fd89f28a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -128,7 +128,7 @@ The host is [`wasmi`](https://github.com/wasmi-labs/wasmi), a pure-Rust WebAssem | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | | Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | -| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (desktop; checked every 20 M instructions) | `Limit("time budget")` | +| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions; the web build reads the page's `performance.now()`) | `Limit("time budget")` | | Import input | 128 MiB of the file (`vectorcraft_plugins::import::MAX_INPUT_BYTES`) | the file doesn't open; a larger file named by `path` is not read past that | | Call depth | 1,024 frames | trap | | Module shape | wasmi's strict limits (≤ 10,000 functions, 1 memory, …) | rejected | @@ -137,6 +137,19 @@ An export runs where the export runs: with Background Export on, on the export's plug-in between two of those 20 M-instruction slices; nothing is written then. An import stops the same way when the open it runs in is cancelled, and nothing opens then. +### Live effects while a document opens + +While the app draws a document on screen, the live-effect runs of its first view share a 2,000 ms budget +(`vectorcraft_plugins::deferred::OPENING_BUDGET_MS`, VectorCraft's own value), measured from the first run. Each run +takes the lesser of its 5 s limit and what is left of the budget; once the budget is spent no run starts, and a result +that comes back after it is not used. A stage left out this way, or one that times out, traps, returns output the host +refuses or has no plug-in, draws its input art unchanged and is deferred. The status bar then says how many stages +are deferred, and later drawings leave them as they are until their input or parameters change. Effect › Refresh +Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget, and `effect.deferredStatus` lists +them with the reason (`budget`, `timeout`, `missing`, `failed`, `safeMode`). Each document has its own budget. +Exports, Expand Appearance and commands run every stage under the 5 s limit. The web build has the same budget, +measured with the page's `performance.now()`. + ### Heavy filters Some filters do heavy but legitimate work, such as routing a plotter's pen, packing shapes onto a sheet or running a @@ -157,7 +170,7 @@ much there is only once the run has ended. Cancel (also Esc) and Continue in Background (`plugin.cancelRuns`, `plugin.hideRuns`). When it is done its result is applied as `plugin.run` with the same parameters and objects, as one undo step, unless the document or the plug-in changed meanwhile: then nothing changes, and the status bar says to run it again. On the web, which has no threads, - it runs at once; the instruction budget alone bounds it there. + it runs at once, under the same instruction budget and 300 s limit. - `plugin.run` itself runs a heavy filter where it is called, as it runs any filter: an MCP client waits for it, and its `notifications/cancelled` stops it. diff --git a/docs/revolve.md b/docs/revolve.md index 18be779d23..e52770fd65 100644 --- a/docs/revolve.md +++ b/docs/revolve.md @@ -6,9 +6,10 @@ Select a path, compound path, type, clipping group, blend, symbol instance, or a On a group or layer, every visible member sweeps about one axis, as [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html) describes for a group. The following rules are VectorCraft's own: type stays editable and sweeps as its glyph outlines, the shared axis lies on the chosen edge of the members' bounds together, and each member keeps its own paint. -The faces of all members draw in one back-to-front order. The opacity and blending mode of a member, or of a group -inside the group, apply once to all its faces. Where a face of another member lies between its faces in that order -and overlaps them on the page, its faces are split there, and the opacity and blending mode apply once to each part. +The faces of all members draw in one back-to-front order. The opacity, blending mode and opacity mask of a member, +or of a group inside the group, apply once to all its faces. Where a face of another member lies between its faces +in that order and overlaps them on the page, its faces are split there, and the opacity, blending mode and opacity +mask apply once to each part. The mask stays where it is on the page; it does not turn with the faces. Two faces overlap when the convex hulls of their outlines come within the 0.75 pt seam stroke of each other. After 4,194,304 overlap tests on one group, each further face of such a member is drawn as a part of its own. The profile's horizontal distance from a vertical axis is its radius. **Axis side** chooses the left or right diff --git a/docs/roadmap.md b/docs/roadmap.md index d79efc9f17..82362eb94c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -143,25 +143,15 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts | 3–6 (existing scope; Affinity export unestimated) | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, three generated libraries (Basic Shapes, UI Frames, Map Markers), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, three generated libraries (Basic Shapes, UI Frames, Map Markers), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, four generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, five generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files; the script document model and console and batch work remain | 18–27 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | | M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | @@ -199,6 +189,8 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | M10/G5: Status Effects built-in graphic style library; MCP docs catch-up for UI Frames and Map Markers; estimates unchanged | +| 2026-11-10 | minor | M10/G5: Inventory Icons built-in symbol library (Sword, Shield, Potion, Key, Gem); estimates unchanged | | 2026-11-10 | minor | M7: the Edit Custom Dictionary dialog (#4936); the Check Spelling dialog remains; scores and estimates unchanged. | | 2026-11-10 | minor | M10/G5: Game HUD built-in graphic style library; estimates unchanged | | 2026-11-10 | minor | M10/G5: Map Markers built-in symbol library (Pin, Flag, Crosshair, Checkpoint); estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4721d30a02..07d626e5a4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -47,6 +47,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | | 2026-11-09 | minor | Stroke panel: Line Arrow, a 41st generated arrowhead: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, a sharp tip and square-cut ends, twice as wide as the other heads; bounds and clicks follow each head's own reach (`stroke.set` `LineArrow`, #5421); scores and estimates unchanged | | 2026-11-09 | minor | Canvas: a 3D effect (Extrude & Bevel, Inflate, Rotate, Revolve) changed on type or a group draws again where its art was and is, measured by that art; the canvas measures through its renderer and draws the part with the art it made to measure it. Exports and Object › Rasterize take the solid of 3D type. Fit to Artwork Bounds and per-artboard SVG export measure every artboard through one renderer, building each solid once. A 3D effect on a fill or stroke that builds nothing (Revolve after Roughen) no longer overflows the stack on the canvas, in Object › Rasterize and in raster and EPS exports: the fill or stroke draws as without it. Tests `tests::changed::a_3d_effect_changed_on_type_or_a_group_changes_where_its_solid_was`, `fx::tests::a_renderer_measures_the_art_on_each_artboard_building_each_solid_once`, `canvas::tests::an_edit_to_a_3d_effect_redraws_with_the_art_measured`, `fx::tests::a_3d_effect_that_builds_nothing_draws_the_item_as_without_it`. Scores and estimates unchanged. | | 2026-11-07 | minor | File formats and Type core (#6147): `.ai`/EPS type keeps its paragraphs' tab stops (positions and alignments; leaders aren't read; at most 1,024 a paragraph and 2^20 a story), and right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops; centred and justified lines are aligned as a whole as before; evidence added. Scores and estimates unchanged. | @@ -222,7 +223,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Revolve, Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers and Inventory Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | @@ -231,7 +232,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers and Inventory Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | @@ -495,7 +496,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Revolve (Classic), Rotate (Classic), Map Art and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, and Map Markers are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers and Inventory Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | @@ -538,7 +539,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~38% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have three (Basic Shapes, UI Frames with default 9-slice, Map Markers), graphic style libraries seven (including Game HUD) and brush libraries five (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~42% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have four (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons), graphic style libraries eight (including Game HUD and Status Effects) and brush libraries five (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, Game Trails) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -564,6 +565,9 @@ since 2026-10-01. **Drawing tools — Polygon and Star counts:** The existing canvas placement dialog reads the stored count and saves it only after successful placement. `polygon_and_star_canvas_counts_persist_without_new_toolbar_dialogs` covers both tools, repeated drags, tool switching, reopening and Cancel. Counts remain session tool options. Existing click and toolbar gestures are retained; no score or hour change. **Drawing tools, Star inner radius held with Ctrl/Cmd:** While a star is dragged out, Ctrl/Cmd keeps the inner radius the star showed when the key went down, also when the key is pressed with the pointer still. `a_star_drag_holds_its_inner_radius_with_ctrl_and_straightens_with_alt` and `a_star_drag_holds_the_inner_radius_it_shows_when_ctrl_goes_down` cover it, with Alt's straight shoulders and a drag canceled with Escape. +**Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. +**Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. +**Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. @@ -639,6 +643,7 @@ since 2026-10-01. Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a feature lands. - **New ruler guides (G1):** Alt swaps orientation while dragging from either ruler, following the [public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). Preview, snapping and final placement use the current axis. Tool and egui event tests exercise both rulers, modifier changes, cancellation and one-step Undo/Redo; existing-guide Alt-copy and ruler-origin gestures are unchanged. +- **Artboard guides with Cmd/Ctrl + ruler drag:** VectorCraft's own option, Preferences › Guides & Grid › Artboard Guides with Cmd/Ctrl + Ruler Drag (`cmdRulerDragArtboardGuides`), off by default. With it on, Cmd/Ctrl held when a drag leaves a ruler makes a guide of the active artboard, and with the Artboard tool a canvas guide; the key is read when the drag starts. The guide is made only where it lies within the active artboard. The documented way to limit a guide to one artboard, dragging it out with the Artboard tool ([Align objects with guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html)), is unchanged when the option is off. Tests `rulerguide::tests::a_guide_within_its_artboard_is_made_only_inside_it`, `tests::menucmds::cmd_ruler_drags_make_guides_of_the_active_artboard_when_the_preference_is_on` and `canvas::tests::cmd_ruler_drags_make_artboard_guides_with_the_preference_on`. - **Width-point finite-arithmetic follow-up (G1/M3):** Adjoining adjustments avoid intermediate overflow; non-finite normalized or resulting factors are rejected before committing. Engine regressions in `tests/widthpoints.rs` cover finite extremes, small nonzero results, atomic rejection, Undo/Redo and native save/reopen. Historical focused validation on the `a3357121` integration observed 2 expected RED failures with 11 passing controls, then all 13 tests passing with the repair; none were ignored. All three added regressions passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. Scores and hours unchanged. - **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). @@ -646,9 +651,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Smooth widths between width points (#5714):** a variable-width stroke changes width along a smooth curve from one width point to the next, where it used to run in a straight line and turn a corner at each point. The public description is that the path "gradually gets wider or narrower from one point to the next" in "a flowing, continuous curve", and that stacked points make a sharp break ([Peachpit, Expressive Strokes](https://www.peachpit.com/articles/article.aspx?p=2979069)); the exact curve is not documented, so each side follows a monotone cubic (Fritsch–Carlson): no kink at a point, flat where a point is wider or narrower than both neighbours, never past the points either side, points on one line kept on it. The outline samples straight runs between width points closely enough to follow the curve to the drawing tolerance (at most 64 samples per span and 4,096 per piece). Presets with a middle point (Lens, Pinch, Teardrop, Wave) look softer; two-point tapers are unchanged. Tests: `appearance::profile::tests::{widths_run_smoothly_through_width_points, widths_never_pass_the_points_either_side, a_step_ends_the_curve_on_each_side, widest_covers_every_width_along_the_profile}`, `stroke::width::tests::{a_straight_run_follows_the_curve_between_width_points, samples_between_width_points_are_capped}`. - **Stroke gradients where a variable-width stroke meets itself (#5960):** with a gradient along or across a stroke that has a width profile, where the stroke crosses itself the later part paints over the earlier one only where the two overlap, and a narrow part running close beside a wide one leaves its edge alone. Each slice of the gradient reaches as far as the stroke is wide where it sits (for a dashed stroke, as wide as it gets within the reach of a cap or dot, found in one pass along the path, so a densely flattened path costs no more per point), where it used to reach as far as the stroke is wide anywhere and paint a square of its colour over the wider part. Strokes without a profile are unchanged. Tests: `stroke::tests_gradient::a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap`, `a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone`, `a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone` and `widest_ahead_is_the_widest_within_the_window`, with the existing coverage tests (joins, caps, arrowheads, profiles, dashes, aligned strokes). - **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`. +- **Ruler double-click (#5239):** a double-click (both clicks on that ruler) on the top ruler adds a vertical guide at the pointer's x and one on the left ruler a horizontal guide at its y (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), through `guide.add` in one undo step; the guide is not snapped, is shown even when guides were hidden, and is an artboard guide with the Artboard tool, as a drag from a ruler makes one. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe the gesture, so it follows the request in #5239. egui frame tests cover both rulers, a lone click, Undo, a canvas click before a ruler click, and rotated views. - **Rulers (#1212):** drag the intersection to preview and set a document zero point, or double-click it to reset to the active artboard's top-left. Transform, Properties and Control X/Y fields measure from it and convert entered positions back to absolute command coordinates. The origin survives every native format version and compression; geometry, guides and patterns stay in place. Public reference: [Use rulers](https://helpx.adobe.com/ca/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html). - **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html). - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). +- **Artboard guide labels (#6414, in part):** Artboard Options' Guide Label gives an artboard a color label (`artboard.setProps`/`artboard.new` `guideLabel`: a layer color's name, `#rrggbb` or null), and the canvas draws that artboard's own guides in it; canvas guides, guides of an unlabeled artboard and guides whose artboard is gone keep the guide color preference, and selected guides keep the selection color. The [help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) describes guides restricted to an artboard, not a label, so the label, its palette and the color precedence are VectorCraft's own. It is screen-only (exports and print leave it out), written to the native format only when set, kept by duplicates and copies, and changeable on a locked artboard; `artboard.setProps` adds no undo step when nothing changes. This VectorCraft addition does not raise a score. Regression tests: `tests/panelcmds.rs` (`artboard_guide_labels_are_set_and_cleared_in_one_undo_step`, `artboard_guide_labels_round_trip_through_the_native_format`), `doc` `tests.rs` (`guide_label_text_names_a_layer_color_or_rgb`, `artboard_guide_label_defaults_and_skips_in_json`), `canvas::tests` (`artboard_guide_label_colors_only_its_own_guides`), `dialogs/tests.rs` (`artboard_options_shows_sets_and_clears_the_guide_label`). - **Fade Region Outside Artboard:** Artboard Options' Global checkboxes Fade Region Outside Artboard and Update While Dragging ([user guide, Artboard options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) are application preferences (`fadeRegionOutsideArtboard`, `artboardUpdateWhileDragging`), both on by default. While the Artboard tool is active the canvas draws everything outside the artboards, the pasteboard and the art on it, with each color channel at 60% of its value (VectorCraft's own amount), or only outside the box around all the artboards when crossing artboards would leave more than 4,096 rectangles in view; with Update While Dragging off it draws as usual during an artboard move or resize. Presentation Mode, exports and print do not change. Regression tests: `canvas::tests` (`the_artboard_tool_fades_the_pasteboard`, `presentation_mode_draws_no_fade`, `the_fade_darkens_art_on_the_pasteboard_and_not_on_the_artboard`, `outside_rects_cover_the_bounds_minus_the_boards`, `outside_rects_of_a_row_of_boards_stay_few`, `the_fade_of_crossing_boards_stays_bounded`, `update_while_dragging_keeps_or_drops_the_fade_during_an_artboard_drag`, `the_pasteboard_fade_leaves_exports_unchanged`), `dialogs/tests.rs` (`artboard_options_global_checkboxes_set_the_preferences`, `artboard_options_error_leaves_the_global_preferences_unchanged`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. @@ -656,8 +663,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`. +- **Export and Import Preferences (#6435):** an optional VectorCraft feature. The Preferences dialog's Export Preferences… saves the applied preferences to a JSON file (`prefs.export`; the web build downloads it), and Import Preferences… applies such a file (`prefs.import`). The file leaves out the folder preferences. The import checks every value first and changes nothing on an error; it keeps the open document's units and records no undo step. The file format is VectorCraft's own. Tests: `crates/engine/src/tests/prefs_file.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Preferences search:** a Search Preferences field above the category list has the keyboard focus when the dialog opens, and Cmd/Ctrl+F gives it back; typing lists the settings it finds, and choosing one shows its category, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html) describes. VectorCraft's own rules: the field matches a setting's label, section or category, ignoring case, in the interface language or in English; the list replaces the categories while the field has text and shows every match, or "No settings found"; the chosen setting's row is highlighted and scrolled into view; Escape in the field with text clears it, and Escape in the empty field closes the dialog. The dialog's `__search` field (`ui.dialog.set`) holds the text. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Reset Preferences asks first (#6435):** the Preferences dialog's Reset Preferences button opens a question over the dialog (`resetPreferences`). Cancel or Escape goes back to Preferences unchanged, with its category, search and edits kept; OK goes back with every preference at its default value, which OK in Preferences applies and Cancel there discards. The question and its wording are VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. @@ -722,6 +731,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. + - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. + - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. + - Scripts: the Script Console panel's report line reads as `script.console` gives it, `time unavailable` included on a platform without a clock; counts of host calls, dropped lines and cut lines take the singular for one, in each language's own plural forms; and a run that is no longer available still gets its end line (`crates/engine/src/tests/script_console.rs`, `crates/ui-egui/src/panels/tests_script_console.rs`). + - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. + - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), and `#targetengine` and `#engine` are refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). + - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). + - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens, links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. + - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. + - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). @@ -787,7 +805,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The macOS menu bar is built from the in-window menus (one model, `native_menu`) and laid out as a Mac app's: the VectorCraft menu holds About, Settings ▸ (each Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays Hide Edges), Hide Others, Show All and Quit; Window gains Minimize ⌃⌘M, Zoom and Bring All to Front, and Help the system's search field. Its key equivalents go back to egui as key presses, so user shortcuts, focused text fields and the Type tool's input method behave as in the window, and nothing fires twice; enabled, check marks and labels update in place. `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps the menus in the window; `ui.inspect` reports `nativeMenuBar`. - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes, UI Frames (Panel, Button and Bar with default 9-slice guides) and Map Markers (Pin, Flag, Crosshair and Checkpoint, no default 9-slice), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. + - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes, UI Frames (Panel, Button and Bar with default 9-slice guides), Map Markers (Pin, Flag, Crosshair and Checkpoint, no default 9-slice) and Inventory Icons (Sword, Shield, Potion, Key and Gem, no default 9-slice), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a ``, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). - **Symbol editing mode** ([Edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a double-click on a symbol instance, the Control bar's Edit Symbol button, a double-click on a symbol in the Symbols panel and the panel menu's Edit Symbol (`symbol.edit`) open the symbol's art on a temporary isolated layer, where the instance shows it (from the panel: centered on the active artboard, or in the view in a document without artboards), with the rest of the document dimmed. Each edit there changes every instance at once; the instances keep their own transforms and stay linked (Break Link to Symbol still expands one), and a dynamic symbol's instances keep their appearance changes to the objects the art still has. Escape, the isolation bar's back button, the Control bar's Exit Symbol Editing Mode and a double-click outside the art leave the mode (`symbol.exitEditing`); leaving without an edit adds no undo step. Saving leaves the editing layer out. Tests: `crates/engine/src/tests/symboledit.rs`, `select::tests::a_double_click_on_a_symbol_instance_edits_its_symbol`, `panels::symbols::tests::edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view`. - **Dynamic symbol appearance follows what an object draws** (VectorCraft's own rule): `symbol.instance.setAppearance` refuses a fill or stroke for an object of the art that does not draw it (a guide, blend, envelope, Repeat, Intertwine group, gradient mesh or placed document; a nested symbol instance's stroke, and its fill unless a solid color or none, which stains its art; an image's fill or stroke without a Convert to Shape or Outline Object effect) with an error that names the key and the object, and the call changes nothing. Opacity, blend and `null`, which takes a stored change back, are taken for every object. Tests: `crates/engine/src/tests/dynamic_symbols.rs`. @@ -928,6 +946,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). + A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). @@ -936,6 +955,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). With Direct Selection, the Pen and the anchor tools, a group, compound path or clip group selected whole shows the anchors of its paths filled, as a path selected whole does; the direction handles still show only on a path that is selected itself. Public references: [Adjust anchor point, handle, and bounding box display size](https://web.archive.org/web/20251114182206/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/adjust-anchor-point-handle-and-bounding-box-display-size.html) and [Drawing basics](https://web.archive.org/web/20231130064834/https://helpx.adobe.com/illustrator/using/drawing-basics.html) (archived copies). + When the Add Anchor Point tool, the Pen's Auto Add, the Smart Pen's Alt-click on a segment or Alt-click with the Scissors adds an anchor to a path with direct-selected anchors or segments (`path.insertAnchor`), the same points stay selected: the anchors and segments after the new anchor are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves. `path.curvatureEdit`, `path.removeAnchor`, `path.convertAnchor`, `path.reshapeSegment`, `path.split`, `path.setHandle`, `path.moveAnchor` and `path.insertAnchor` refuse a `subpath` that is not a whole number of 0 or more, and `path.split` refuses such an `anchor` or `segment`; without a `subpath` they edit subpath 0. `path.reshapeSegment` refuses a delta of 1e9 pt or longer, as `object.blend.spine.reshapeSegment` does, and `path.convertAnchor` and `path.freehand` refuse a point whose x or y is 1e9 pt or more in size. `path.reshapeSegment`, `object.blend.spine.reshapeSegment`, `path.convertAnchor`, `path.curvatureEdit`, `path.insertAnchor`, `path.moveAnchors`, `path.reshape`, `path.close` and the Pencil, Curvature, Knife, Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a number, point or handle given as text, such as "10", and leave the document unchanged; `path.convertAnchor` refuses an `x` without a `y`, or a `y` without an `x`. @@ -950,7 +970,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command, the Eyedropper, a graphic style, Default Fill and Stroke or Swap Fill and Stroke, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character or Appearance controls, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command, the Eyedropper, a graphic style, Default Fill and Stroke or Swap Fill and Stroke, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph or Appearance controls, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. Type in a column design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits: the first digit is the least number of places before the decimal point (zeros are added in front; 0 gives as many as the value needs), and the second digit sets the places after it, rounded. Unless it is inside a group that clips or has its own opacity or appearance, or inside a blend, compound shape, envelope, repeat or intertwined objects, the type keeps its size and is drawn once per column in a repeating design. The legend swatch leaves it out. - **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View. @@ -1010,6 +1030,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't). A move that Shift keeps level, upright or diagonal stays on that line when it snaps, with the Selection, Group Selection or Direct Selection tool. It slides along the line until the selection lands on the grid or on whole pixels, lines up with the other objects or is spaced evenly with them, or until the line passes an anchor or crosses a ruler guide near the point the selection was grabbed by. A level or upright move snaps along its own axis only. Snap to Last Location: with Smart Guides on and Preferences › Smart Guides › Snap to Last Location on (off by default, VectorCraft's own choice), a selection moved by dragging with the Selection, Group Selection or Direct Selection tool, Shift too, goes back to where the move began while it is within Snapping Tolerance of it, labeled "last location"; an Alt copy is not pulled back onto its original, and with View › Snap to Grid or Snap to Pixel on the move snaps to the grid or to whole pixels instead (`prefs.set` key `snapToLastLocation`). The public [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) page lists the option as snapping objects back to their previous position; the distance, the label, the copy rule and the grid and pixel rule are VectorCraft's own. Tests: `select::tests::snap_to_last_location_puts_a_move_back_where_it_began`, `select::tests::snap_to_pixel_wins_over_snap_to_last_location`, `direct::tests::snap_to_last_location_puts_a_path_moved_by_its_anchor_back`, `direct::tests::snap_to_pixel_wins_over_snap_to_last_location_for_a_path_moved_by_its_anchor`, `tests_prefs::snap_to_last_location_puts_a_dragged_square_back`. + Pixel Preview: with View › Pixel Preview on, the tools use no Smart Guides. Nothing snaps to Smart Guides or shows their guides, and Snap to Point acts as it does with Smart Guides off. View › Smart Guides keeps its setting and applies again when Pixel Preview is turned off. [Work with Smart Guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/work-with-smart-guides.html) says Smart Guides cannot be used while Pixel Preview is on. Tests: `tests::smartguides::pixel_preview_turns_smart_guides_off`, `canvas::tests::pixel_preview_stops_smart_guides_snapping_a_move`. Distance Guides: with Smart Guides on (View › Smart Guides and Preferences › Smart Guides › Invoke Distance Guides, on by default), something selected and the Selection tool, holding Alt/Option over another object shows the distances between the selection's bounds and that object's: on an axis on which they lie apart, one line across the gap between their facing edges; on one on which they overlap, the offsets of their left and right (top and bottom) edges, each line running across the middle of where they overlap, with a dashed line out to the other object's edge when it passes beside it. Over an empty part of an artboard it shows the selection's distances from the artboard's left, right, top and bottom edges. Each line has ticks at its ends and its length in a pill of the smart guide colour, in the General unit; letting Alt go, pressing (a pan or zoom press too), moving off them, leaving the canvas or a floating panel, menu or dialog over the pointer takes them away, and with the pointer still they follow what lies under it as the view scrolls, zooms or turns, as the document, the tab or the selection changes, and when the Selection tool is switched to. Behaviour from the public [Use Distance Guides for accurate placement](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html) and [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) pages, which describe hovering only: nothing shows while moving or nudging. Tests: `select::tests::alt_over_*`, `select::tests::distance_guides_need_alt_a_selection_and_smart_guides`, `tests_prefs::invoke_distance_guides_measures_the_selection_to_the_object_under_alt`, `canvas::tests::alt_over_another_object_draws_the_distance_guide_label`, `canvas::tests::distance_guides_go_when_the_hover_ends`, `canvas::tests::distance_guides_follow_what_lies_under_a_still_pointer`. A move pressed on a path's stroke, or within 6 px of its outline away from its anchors and center, is held by the nearest point of that path, with the Selection, Group Selection or Direct Selection tool, and a straight segment Direct Selection drags is held by its own nearest point. That point is what snaps, so the path lands exactly on a ruler guide (with "align") instead of the pressed spot landing there and the path a few pixels beside it, an offset that showed only zoomed far in (#3701). A press in the middle of a fill still snaps the pressed spot: the public [Align objects with guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) page has Snap to Point align the point under the pointer, which is placed exactly where the object should meet the guide. A bounding-box handle dragged with the Selection or Free Transform tool snaps what it moves as a dragged point snaps (#2054). With View › Snap to Grid on, it snaps to the nearest gridline, and with Snap to Pixel on, it snaps to whole pixels. With Smart Guides off and Snap to Point on, it snaps to the other objects' anchors and the ruler guides within the Snap to Point distance. With Smart Guides and Snap to Point both on, it lines up with the ruler guides as well as the other objects. Shift still keeps the proportions, and Alt still scales about the center. @@ -1107,7 +1128,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. - The Character panel's Anti-aliasing Method dropdown, under Character Rotation, sets how the edges of the selected type objects are drawn as pixels (`text.setFormat {antiAlias}`), for the whole object, with each frame of a thread keeping its own method, on the canvas, in raster exports and when the type is rasterized. VectorCraft defines the methods: Sharp, the default, draws edges as before; None paints a pixel only where the type covers at least half of it; Crisp shows a pixel covered by a share c at `2c - 0.5`, and Strong shows it at `2c`, each kept between 0 and 1. SVG, PDF and EPS export are unchanged. Scores and hours unchanged. + The Character panel's Anti-aliasing Method dropdown, under Character Rotation, sets how the edges of the selected type objects are drawn as pixels (`text.setFormat {antiAlias}`), for the whole object, with each frame of a thread keeping its own method and graph labels keeping it when the graph is drawn again, on the canvas, in raster exports and when the type is rasterized. VectorCraft defines the methods: Sharp, the default, draws edges as before; None paints a pixel only where the type covers at least half of it; Crisp shows a pixel covered by a share c at `2c - 0.5`, and Strong shows it at `2c`, each kept between 0 and 1. SVG, PDF and EPS export are unchanged. Scores and hours unchanged. The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. The OpenType panel's Position menu lists Default Position, Superscript, Subscript, Numerator and Denominator, as [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) describes; Superscript, Subscript, Numerator and Denominator set `sups`, `subs`, `numr` and `dnom` for the selected type and turn the other three off, and Default Position turns all four off. The menu shows Mixed when the characters it acts on differ, and an entry chosen then applies to all of them. These two rules are VectorCraft's own, as is setting the feature on type whose font lacks the glyphs, which then draws unchanged. The panel's menus and checkboxes change only their own features on each selected character, so characters keep their other OpenType features (`text.setStyle` and `text.setRangeStyle` `{featureChanges}`). Tests: `panels::opentype::tests`, `features::tests::numerators_and_denominators_are_kept_and_shaped`. The Glyphs panel's Show menu and panel menu have Alternates for Current Selection, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes: the grid lists the alternate glyphs of the character selected with the Type tool, and a double-click draws that character with the glyph as one undo step (`text.glyphAlternates`, `text.setGlyphAlternate`). The alternates come from the font's `GSUB` single and alternate substitutions of `aalt`, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99` and a few other alternate features, each glyph once. The text keeps the character, native files keep the choice with the face it was made in, and type set in another font or version draws the default glyph. The list uses the font of the character's text even when the panel browses another font, and the panel shows a note when the character has no alternates, its font is missing or no character is selected; these rules are VectorCraft's own. Tests: `panels::glyphs::tests`, `tests::alternates`, `tests::textedit::a_glyph_alternate_replaces_one_character_through_undo_and_reopen`. @@ -1159,10 +1180,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Tabs ruler's upper first-line marker and lower left-indent marker show absolute positions and set paragraph indents (`text.setFormat`). Dragging the lower marker keeps the upper position, while Ctrl-dragging it (Command on macOS) moves both; marker drags snap like tab stops, and each release is one undo step. With differing left indents, only the upper marker is shown and its absolute target applies to every touched paragraph. When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent (18 pt further in for each list level past the first) when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. -- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). +- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. - Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. + Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. The Character panel's All Caps, Underline and Strikethrough buttons and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break show off while only some of the selected characters have the attribute, and choosing one then turns it on for all of them, as `type.underline` (Cmd+Shift+U) does for underlining; the Character Alignment and Digits submenus check no item while the selected characters differ. `text.setFormat` refuses a value that is not true or false for its on/off attributes, as `text.setRangeStyle` does. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). @@ -1303,7 +1324,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. - - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; seven generated style libraries (including Game HUD) save and load as `.vcstyles`. + - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eight generated style libraries (including Game HUD and Status Effects) save and load as `.vcstyles`. In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Load text styles from another document:** the Character Styles and Paragraph Styles panel menus have Load Character Styles… or Load Paragraph Styles… and Load All Styles…, which copy the styles of a document picked in an open dialog, with the swatches and patterns they paint with, in one undo step (`charStyle.load`, `paraStyle.load`, `textStyle.loadAll`); a style the document already has, under its name or a numbered one, is not added again, any other whose name is taken gets a number, and the file's Normal styles are not loaded. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -1348,7 +1369,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`). A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. The stops of an axial or radial shading in a DeviceN space that mixes one spot ink with process plates (a spot ink over a constant cyan, for example) link to the ink's swatch at its tint and keep the process plates, and PDF and EPS (Level 3) export write those stops in a DeviceN space of the ink and those plates, so the spot plate is not lost (#3235, `import_color::a_device_n_gradient_of_a_spot_ink_over_a_process_plate_keeps_both_inks`). Solid fills that mix a spot ink with process plates, and stops that mix several spot inks, still import as RGB, with the spot inks kept as swatches. A `.ai` or EPS opened from its editing data keeps both swatches when a pattern's name, or a named color's, is also another swatch's: a pattern's swatch named as a default swatch, a named color or a palette color becomes "Name 2", and a named color named as a gradient or pattern swatch of the palette becomes "Name 2", with the fills, strokes and gradient stops linked to it following it (`ai::tests::a_pattern_swatch_named_as_another_swatch_is_numbered`, `ai::tests::a_color_named_as_a_palette_gradient_or_pattern_is_numbered`). - PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning. A Perceptual gradient of spot inks is written as a Separation or DeviceN shading of the stops on its curve; a dithered gradient fill, and a Perceptual gradient with RGB or Lab stops other than white or more than 4,096 stops on its curve, are written as images in process colors, with a warning. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). + PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning. A CMYK document, or an export that converts colors to a CMYK destination profile, writes RGB and Lab stops in CMYK first (unless the export converts colors to an RGB destination profile), so there such a gradient, Classic or Perceptual, is written as a DeviceN shading that keeps the spot ink. A Perceptual gradient of spot inks is written as a Separation or DeviceN shading of the stops on its curve; a dithered gradient fill, and a Perceptual gradient with RGB or Lab stops other than white or more than 4,096 stops on its curve, are written as images in process colors, with a warning. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). PDF export writes a spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4) as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients, colorized images and Lab alternates; Registration still prints on every plate (`pdf/src/tests/output.rs`). - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). Preferences › File Handling › Data Recovery › Folder has a Choose… button on the desktop that picks the folder Data Recovery keeps its copies in ([Illustrator reference, Set Data Recovery preferences](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)); a picked folder that Data Recovery cannot create its folders in or list is refused with a status message, and the field keeps its value. OK applies the same check to a folder typed into the field (VectorCraft's own rule): when it fails, the dialog stays open, the status bar says why and no preference changes; an empty field (the default folder) and the folder already saved are not checked. Preferences › Plug-ins & Scratch Disks is where additional plug-ins folders are set ([Illustrator preferences help](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html)); its Additional Plug-ins Folder has a Choose… button on the desktop as well, VectorCraft's own, matching Data Recovery's, and VectorCraft's own rule refuses a picked or typed folder whose contents can't be listed. Additional Fonts Folder and Templates Folder stay typed only. @@ -1410,11 +1431,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). - In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), 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, and the export's warnings give each such page's size and how it is written (#6382). PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. + PDF/X-1a, PDF/X-3 and PDF 1.3 files keep the art under the hidden part of a picture, gradient, pattern, mesh or raster effect that a clipping mask or clipping layer crops: flattening rasterizes only the part of such art that its clipping path shows, on its own page and on the next one. Layers the file leaves out are left out of the flattening, and transparent art that a clipping path hides entirely is removed (`crates/engine/src/cmd/fileio/tests_pdfx.rs`). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). A placed PDF or `.ai` file in a `.ai`'s editing data comes in as a placed document instead of a linked image: it shows the page and Crop to box its dictionary names, and the preview the file keeps until its file is found, then the page as vectors. A placed file in opacity-mask art keeps showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). @@ -1536,7 +1558,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). With the Perspective Selection tool, Ctrl+Alt-drag (Command+Option-drag on macOS) also copies objects on their perspective plane; Alt/Option-drag continues to do so. With the Perspective Selection tool, holding Shift while moving or copying constrains each object's displacement to the nearest axis or 45° diagonal of its own plane; releasing Shift resumes the raw pointer position, and 5 still moves perpendicular to the plane. Snap to Grid follows the constrained line on the first object's plane and depth. - With Snap to Grid on, a move of objects on one perspective plane at different depths moves them all by the same offset on the plane, so they keep their spacing, and the edge of their joint bounds nearer a gridline lands on it. Regression: `snap_moves_objects_at_different_depths_by_one_plane_offset` in `crates/engine/src/tests/persp_select.rs`. + With Snap to Grid on, a move of objects on one perspective plane at different depths moves them all by the same offset on the plane, so they keep their spacing. Without Shift, on each axis, the edge of their joint bounds nearer a gridline lands on it when that edge ends within a quarter cell of the gridline. With Shift, an edge also lands only when it ends within a quarter cell of a gridline: a horizontal or vertical move can land only an edge on its own axis, and a 45° move lands the edge on the axis whose nonzero correction is smaller. When no edge on those axes is that close, the move does not snap. A move perpendicular to the plane does not snap. Regression: `snap_moves_objects_at_different_depths_by_one_plane_offset` in `crates/engine/src/tests/persp_select.rs`. When the desktop app opens a document on a thread of its own (#1245), that thread also reads the document's linked files and lays out its type, and the UI thread only adds the finished document: in release builds, the step left on the UI thread takes 0.02 ms instead of 1.04 s for a document with 12 linked 3000 × 2000 TIFFs, and it takes 0.1 ms instead of 0.85 s for one with 300 Auto Size area type objects, every second one in three columns. Laying out type keeps each font face's shaping plans, at most 32 per face, so type objects of the same font, script, direction, language and features share one plan: the layouts of a document of 5,000 short point type objects take 59 ms instead of 73 ms in a release build, and the glyphs, bounds and baselines do not change. Laying out type looks up the font face of each style run once and uses it for the run's glyphs and for the line metrics of a paragraph that starts in that run: the layouts of a document of 5,000 short point type objects take a median of 215 million CPU cycles instead of 236 million in a release build (11 alternating runs of each build on Windows 11, measured while other builds were running), and the glyphs, bounds and baselines do not change. @@ -1633,6 +1655,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. +- **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. The web build times the budget and each run's limit with the page's `performance.now()`. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/plugins/src/host.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Plug-in settings and cache (G17, #2191):** at plug-in API level 2 a plug-in with the `settings` permission keeps settings of its own (`env.vc_settings_get`, `_set`, `_delete`) and one with `cache` a cache the user can clear (`env.vc_cache_read`, `_write`, `_clear`), under its id in the `Plug-ins` folder. Keys are plain names, never paths; VectorCraft's own caps refuse a write past 256 settings, 1 MiB of settings or 512 MiB of cache; a damaged settings file is moved aside and the settings start empty. `plugin.clearCache` empties a cache, `plugin.list` and `plugin.info` give `cacheBytes`, replacing a plug-in keeps its storage and `plugin.remove` deletes it. Another module under an id that is installed or has storage installs only with `replace: true`, which the app asks the user for; each storage call counts the whole settings file or cache entry it reads and writes toward the run's 1 GiB. Regressions: `crates/plugins/src/storage.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_clear_cache.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in settings and cache totals in memory (#6228):** the settings stay in memory while `settings.json` keeps its size and modified time, a set to the same value writes nothing, every other change is written to the file before the call returns, and `cacheBytes` comes from a total kept while the `cache` folder keeps its modified time. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. @@ -1694,7 +1717,7 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi `pdf::tests::dithered_perceptual_gradients_export_as_images_with_noise_on_the_fill` and the Gradient panel's `the_method_menu_makes_the_gradient_perceptual`. Scores and hours unchanged. -PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html); [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html)). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). A Perceptual gradient that mixes spot colors with each other or with CMYK or gray stops is written as a DeviceN shading of its inks: at each stop on the curve, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color there, or at the stop's mix position between the two colors when that mix's lightness turns back on the way from one color to the other, as from red to blue (VectorCraft's own rule). Dithered fills, freeform gradients, Perceptual gradients that mix a spot color with RGB or Lab stops, and Perceptual gradients whose curve has more than 4,096 stops once expanded (VectorCraft's own limit) are still images, and the export warns that their spot colors are written in process colors. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve`, `ink_mixes_follow_the_perceptual_curve` and `ink_mixes_use_the_mix_position_when_the_lightness_turns_back`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings`, `perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings` and `spot_gradients_drawn_as_images_warn`. +PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html); [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html)). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). A Perceptual gradient that mixes spot colors with each other or with CMYK or gray stops is written as a DeviceN shading of its inks: at each stop on the curve, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color there, or at the stop's mix position between the two colors when that mix's lightness turns back on the way from one color to the other, as from red to blue (VectorCraft's own rule). Dithered fills, freeform gradients, Perceptual gradients that mix a spot color with RGB or Lab stops, and Perceptual gradients whose curve has more than 4,096 stops once expanded (VectorCraft's own limit) are still images, and the export warns that their spot colors are written in process colors. In a CMYK document, or an export that converts colors to a CMYK destination profile, RGB and Lab stops are written in CMYK, so a Perceptual gradient that mixes a spot color with them is a DeviceN shading; an export that converts colors to an RGB destination profile keeps them in RGB. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve`, `ink_mixes_follow_the_perceptual_curve` and `ink_mixes_use_the_mix_position_when_the_lightness_turns_back`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings`, `perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings`, `perceptual_spot_gradients_with_rgb_stops_in_a_cmyk_document_export_as_device_n_shadings` and `spot_gradients_drawn_as_images_warn`. In these Separation and DeviceN shadings, a white stop linked to a swatch that is not a spot color (a global White swatch, for example) is paper white, 0% of the ink, as an unlinked white stop is, so a gradient of one spot ink and such a stop stays a Separation shading; a stop linked to a white spot color stays a stop of that ink (VectorCraft's own rule). Test: `engine::tests::linked_stops::white_stops_linked_to_process_swatches_are_paper_in_spot_gradients`. @@ -1883,7 +1906,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## Dynamic symbols (2026-11-01) -Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own opacity and blend for any object of the symbol's art, and its own fill and stroke for an object that draws them, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol expands the symbol's own art; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them, and Replace Symbol drops them when it gives the instance a different symbol. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: on-canvas editing beyond a solid fill and stroke on a path, compound path or type object inside a dynamic instance; reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests. Score unchanged at 87% (estimated); hours 5–9 → 4–8. +Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own opacity and blend for any object of the symbol's art, and its own fill and stroke for an object that draws them, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol keeps the instances linked and keeps each change whose object the edited art still has; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them, and Replace Symbol drops them when it gives the instance a different symbol. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: on-canvas editing beyond a solid fill and stroke on a path, compound path or type object inside a dynamic instance; reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests, `crates/engine/src/tests/symboledit.rs`. Score unchanged at 87% (estimated); hours 5–9 → 4–8. ## Document Tools add-on: Export All Open Documents (2026-11-01) @@ -1936,7 +1959,7 @@ Edit Custom Dictionary followed (2026-11-10), as the same page's "Edit the custo ## Control bar: Paragraph section while type is selected (2026-11-06) -With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1440 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). +With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1536 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). ## Area type: vertical alignment in the Properties and Control panels (2026-11-04) @@ -1950,6 +1973,8 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Bundled content: built-in Status Effects graphic style library; style libraries evidence updated; ~40% → ~42%; MCP Symbol libraries list UI Frames and Map Markers; more built-in graphic-style libraries remain. | +| 2026-11-11 | minor | Bundled content: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem); symbol libraries evidence updated; ~38% → ~40%; more built-in symbol libraries remain. | | 2026-11-10 | minor | Type advanced: the Edit Custom Dictionary dialog, #4936; evidence added; the Check Spelling dialog remains; scores and hours unchanged. | | 2026-11-10 | minor | File formats: in a `.ai` or EPS opened from its editing data, an envelope of type opens live where it draws as its drawn art and the layers with it draw as the page (the envelope weighed as the art it draws); elsewhere, and where a text or visibility variable binds its type, it keeps its drawn art, with a note (#3179); evidence updated; scores and hours unchanged. | | 2026-11-10 | minor | Bundled content: built-in Game HUD graphic style library; style libraries evidence updated; ~34% → ~36%; more built-in graphic-style libraries remain. | @@ -2103,6 +2128,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-20 | minor | Type core: Hyphenation… and Justification… no longer listed as missing (done in #2310, #2755); evidence: a paragraph's Auto Leading drives the Character panel's Leading, the leading nudge and Fill with Placeholder Text; scores unchanged | | 2026-10-22 | minor | Drawing tools: a Pen, Anchor Point or Direct Selection drag's preview no longer stalls (#834: the position where the pointer re-entered the window could be skipped, and the move in the release's frame was lost); score and hours unchanged (estimated) | | 2026-10-23 | minor | Guides and snapping: a path moved by a press on its stroke or beside its edge (Selection, Group Selection, Direct Selection), and a straight segment Direct Selection drags, snap by the nearest point of the path, so the path lands exactly on a ruler guide with "align" instead of the pressed spot landing there and the path a few pixels beside it (#3701); `tests_prefs::a_move_held_by_a_paths_stroke_lands_the_path_on_a_ruler_guide`, `tests_prefs::a_straight_segment_dragged_by_direct_selection_lands_on_a_ruler_guide`. Score and hours unchanged. | +| 2026-11-11 | minor | Guides and snapping: a Shift move slides the selection along its line onto a ruler guide by its edges and centre, as a move without Shift does (#4312); a guide a nearly parallel line only reaches a long way off pulls nothing. Score and hours unchanged (estimated). | | 2026-10-22 | minor | Live vector effects: the Transform effect has Transform Objects, Transform Patterns and Scale Strokes & Effects, its checkboxes visible (#885); the area row now lists only the options on a fill's or stroke's own Transform effect. Score and hours unchanged (estimated). | | 2026-10-23 | minor | COLR colour fonts (v0 and v1) draw and export as vector art; evidence added; scores unchanged. | | 2026-10-22 | minor | Libraries panel: the buttons beside the library picker show the items as icons (the default) or in a list, colours and graphics as rows with their names (a colour's hex value too), dragged and dropped by row; graphic thumbnails are shrunk to the size they are drawn at, so thin strokes stay whole. Tests: `panels::libraries::tests::the_list_view_shows_names_and_takes_drops_by_row`, `the_panel_draws_its_libraries`. Scores and hours unchanged. | diff --git a/docs/three-d.md b/docs/three-d.md index bfb626c5ad..e6dc279da3 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -122,7 +122,11 @@ them all. The members stay editable: moving or editing one reshapes the solids. - Each member's own geometry effects shape it first, then those of each group inside the 3D group that holds it, applied to that group's members together; the 3D group's geometry effects before the 3D effect reshape the members, and those after it bend the result as a whole. The members' other effects, and the group's own fills and - strokes, are not drawn. A member's opacity applies to its solids; its blending mode does not. + strokes, are not drawn. A member's opacity applies to its solids; its blending mode does not. An opacity mask on + a member masks its solids, and one on a group inside the 3D group masks the solids of that group's members + together. The mask stays where it is on the page; it does not turn with the solids. A disabled mask is ignored. +- When a member, or a group inside the 3D group, has an opacity mask, each solid is drawn on its own, the backmost + member's first, as when a solid is transparent. - When every solid is opaque, all members' faces are drawn in one back-to-front order; otherwise each solid is drawn on its own, the backmost member's first. - Hidden members and guides are left out. A group holding a live object other than a blend (an envelope, a mesh, a diff --git a/docs/type-parity.md b/docs/type-parity.md index defb384739..4013f8be19 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -81,6 +81,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Tracking and manual kerning in horizontally scaled type: they are thousandths of the em as the Horizontal Scale draws it (`vectorcraft_text::spacing_scale`), so at 50% a tracking of 100 adds 0.05 em after each character, half as much as at 100%. They were added at the full em whatever the scale, so narrow tracked type drifted further right with each letter. Illustrator's own layout in users' `.ai` files (used locally, not committed) spaces such type so, and PDF scales its character spacing by its horizontal scaling alike (ISO 32000-1 §9.4.4). Inline graphics take it after them too; vertical type keeps the full em, its advances down the column not all taking the Horizontal Scale. The automatic kerning the Character panel reads, Touch Type's limits and Artwork Cleanup's Combine Point Text measure in the same em, and Scale Text Attributes now keeps tracked type where a horizontal stretch of its transform drew it. Type that has both a Horizontal Scale other than 100% and tracking or manual kerning lays out differently than before in every document. Tests `tests::tracking_and_manual_kerning_take_the_horizontal_scale`, `tests::typo::optical_pairs_in_horizontally_scaled_type_measure_without_the_scaled_tracking`, `tests::inline::shift_tracking_and_missing_symbols`, `tests::vertical::vertical_tracking_keeps_the_em_at_any_horizontal_scale` and the engine's `horizontally_scaled_pair_reads_as_the_kerning_that_keeps_it`, `scale_text_attributes_keeps_tracked_type_where_it_was` and `combine_puts_horizontally_scaled_pieces_back_where_they_were`. Scores and estimates unchanged. | | 2026-11-10 | minor | Edit Custom Dictionary (#4936): Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, applied on Done; the Check Spelling dialog remains. Scores and estimates unchanged. | | 2026-11-10 | minor | Type on a path (#3565): Direct Selection shows the direction handles of selected type on a path's path, as of a path selected whole, and drags them (`text.setPathHandle`; Alt: one side, Shift: 45° steps); the text reflows along the new curve. Scores and estimates unchanged. | | 2026-11-10 | minor | Spelling in the canvas context menu (#4936): a right-click on type has Spelling › Auto Spell Check, checked while it is on; the Check Spelling and Edit Custom Dictionary dialogs remain. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d1b54ef4d6..44d0b19a4e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -51,6 +51,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | | 2026-11-08 | minor | Style panels: a double-click on a user character style's row opens its Character Style Options (`ui.charStyleOptions`), and on a paragraph style's row its Paragraph Style Options (rename); the Character Style Options dialog keeps a fixed width and scrolls its sections in a shorter window, so OK and Cancel stay on screen. Tests `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options` and `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. Scores and estimates unchanged. | | 2026-11-08 | minor | #3380, deletion only: preserve gradient placement and exact surviving geometry; consume owned subpaths with a shared original-node snapshot; consolidate status/evidence and document command/helper contracts. Compound behavior and the existing M2 status entry are retained. Endpoint highlighting remains open; scores and estimates unchanged. | | 2026-11-07 | minor | #3380 (deletion only): independent surviving path objects; transformed appearance, stacking, selection, cubic handles and Undo/Redo covered by `delete_path_pieces`; compound semantics retained. Endpoint highlighting remains open; scores and estimates unchanged. | @@ -157,7 +158,7 @@ tools, never checked side by side) isn't captured row by row. | Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | | Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Live Paint Bucket, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | -| Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests | +| Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | @@ -237,6 +238,7 @@ tools, never checked side by side) isn't captured row by row. | Snapping panel/popover consolidating the snap options (30.0) | partial | Control bar › Snapping provides quick access through existing view commands and prefs.set, including Snap to Glyph and Alignment Guides (#6164); no View › Snapping submenu. Floating-panel parity remains unverified. | | Customisable rotation snap angle (#973) | missing | Illustrator: Constrain Angle and construction angles only | | Ruler guides: drag out, select, move, delete, lock, Make/Release Guides | done | #414, #451; marquee selects unlocked ruler guides | +| A double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler, a horizontal one on the left ruler (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), exactly where the pointer is (no snapping), shown even with guides hidden, one undo step (`guide.add`); both clicks of the pair must be on that ruler, and the first adds nothing. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe this gesture, so it follows the request in #5239 | done | #5239; an artboard guide with the Artboard tool, as a drag from a ruler makes one; `canvas/tests.rs` `double_clicking_a_ruler_adds_a_guide_at_that_position`, `a_canvas_click_then_a_ruler_click_adds_no_guide`, `a_ruler_double_click_follows_a_rotated_view` | | Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | | Ruler origin: corner drag with preview, double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | | Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer | done | `guide.setLayer`; guides from older files go on a layer | @@ -282,7 +284,7 @@ tools, never checked side by side) isn't captured row by row. | Numeric spinner arrows step once on a click and keep repeating while held with the mouse | done | #6307; headless test `a_held_spinner_arrow_repeats` holds past egui's click timeout and checks release. | | Arithmetic in fields (`+ - * /`, and `%` of the value before it: `3cm*50%`, `50pt+25%`) and unit suffixes (`3 mm`, `1in`, `2p6`) | done | `Unit::parse`; mixed units in one expression not verified | | Numeric fields: focus click selects the whole value; dragging selects from the pressed character | partial | #1326; select-all waits for click release; px/pt/plain/optional fields, both directions and replacement text tested; native API input, 17 px partial replacement, Undo/Redo, saved-file round trip and screenshots verified; Tab, double-click, arrows and wheel preserved; short movements still classified as clicks can select all and remain open | -| Units: pt, pc, in, mm, cm, px, ft-in, m, yd, ft; General/Stroke/Type units | done | units preference reverting to points on SVG output reported (#864) | +| Units: pt, pc, in, mm, cm, px, ft-in, m, yd, ft; General/Stroke/Type units | done | units preference reverting to points on SVG output reported (#864). A file that records no units (PDF, EPS or `.ai` without ruler units, raster images, metafiles, Affinity files) opens and reverts in General units; native, SVG and DXF files and a `.ai` or EPS with ruler units keep theirs, as a [Community Expert's answer](https://community.adobe.com/questions-652/change-units-from-points-to-inches-won-t-stick-765372) describes (#5820) | | Units › East Asian Type (Q and Ha) | done | #394: `unitsAsianType` offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide's Measurement Units](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`); only it lists Q and Ha. The public pages do not say which fields use it, so no field uses it yet and that waits for a source. Tests `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | | Field precision: 3 decimals for steps; values kept as f64 | done | | | Scrubby labels (beyond Illustrator) | done | #400; the labels that are links (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke) scrub too, and a click on them still opens their panel (#4088) | @@ -363,6 +365,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po |---|---|---| | Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; overflow and cross-window drag remain separate | | A document tab dragged along the tab strip moves its document; a line marks where it goes, the current document and every document's view stay as they were, and a drag off the strip still floats it | done | #5663, [public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html); `document.move`; `tests::tab_reorder`, `chrome::tests` (drop index with floating and view tabs), `engine` `tests::document_move` | +| A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | Behaviour | Status | Notes | |---|---|---| @@ -407,7 +410,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | | Attributes fill-rule controls with a compound member selected | done | Edits the compound's rule; direction still edits only the member; rendered-hole and Undo/Redo regression tests (#1197) | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | -| Symbol libraries: Window › Symbol Libraries (Basic Shapes, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; only one built-in library (original, generated in code) | +| Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; four built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; four built-in libraries (original, generated in code) | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | @@ -438,6 +441,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | +| Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -507,6 +511,11 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Outline view: a click on a path's outline selects it through an image or a gradient mesh in front, which Outline draws as a frame or mesh lines (#6437). | +| 2026-11-11 | minor | A middle-click on a document tab (or its ×) closes it as the × does; closing a document's last view with unsaved changes asks to save first (#6506). VectorCraft addition; scores and estimates unchanged. | +| 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | +| 2026-11-10 | minor | Symbol libraries: Inventory Icons joins Basic Shapes, UI Frames and Map Markers as a fourth built-in library (Sword, Shield, Potion, Key, Gem; no default 9-slice). | +| 2026-11-11 | minor | Files that record no units (PDF, EPS or `.ai` without ruler units, raster images, metafiles, Affinity files, importer plug-ins) open and revert in Preferences › Units › General instead of points; native, SVG and DXF files and `.ai`/EPS ruler units are kept (#5820). Scores and estimates unchanged. | | 2026-11-10 | minor | Held numeric spinner arrows keep stepping past the click timeout and stop on release (#6307). Scores and estimates unchanged. | | 2026-11-09 | minor | Interim macOS canvas cursor delivery (#2292): existing artwork in aligned 1×/2× AppKit representations, visible system fallback and host-owned restoration. Headless routing, bitmap and ownership coverage; native timing, menus, focus/handback, mixed displays, Spotlight and full-screen Spaces remain unverified. Scores and estimates unchanged. | | 2026-11-08 | minor | Floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part); tab groups remain intact. Scores and estimates unchanged. | @@ -544,6 +553,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Randomize Opacity (#4925); scores and estimates unchanged | | 2026-11-01 | minor | Arrange Tools add-on (a VectorCraft addition): Sort Objects (#4917); scores and estimates unchanged | | 2026-11-01 | minor | Blob Brush and Eraser: the tip's outline (size, angle, roundness, at the zoom) follows the pointer before and while painting, around a small centre dot, updating at once with `[` / `]` and Tool Options; precise cursors (Caps Lock) show only the crosshair (#4977); scores and estimates unchanged (estimated) | +| 2026-11-11 | minor | Blob Brush: while painting, the preview of a round tip is the outline of the area the stroke adds, round at both ends, as the stroke it commits (#4343). Scores unchanged (estimated). | | 2026-11-01 | minor | Layers panel: an open blend lists its spine as a `` row below its key objects, and a click selects the blend so Direct Selection edits the spine (#4820); scores and estimates unchanged | | 2026-11-01 | minor | Pen with Cmd/Ctrl held: the lent Selection tool no longer scales the path being drawn by bounding-box handles the canvas hides while its end anchor is selected (a flat path did nothing under a resize pointer); a Cmd drag moves the path instead, and with Direct Selection moves anchors and segments, one undo step each (#4980); scores and estimates unchanged | | 2026-11-01 | minor | Dynamic symbols (#4938): Symbol Options › Symbol Type; per-instance appearance for objects of a dynamic symbol's art; Reset in the Properties panel and the Symbols panel menu; on-canvas Direct Selection of the parts remains |