#4943: merge main; keep both type-parity status lines

This commit is contained in:
ruchirguitar committed 2026-11-10 21:31:21 +05:30
commit c79932e410
165 files changed
+7981 -457

No files matched your search

Generated
+5 -3
View File
@@ -975,12 +975,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1049,7 +1049,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -6652,6 +6652,8 @@ dependencies = [
"kurbo 0.13.1",
"log",
"md-5",
"objc2-core-foundation",
"objc2-core-graphics",
"roxmltree 0.21.2",
"serde",
"serde_json",
+1 -1
View File
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/vectorcraft"
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
+1
View File
@@ -5,3 +5,4 @@
mod cli;
mod fileio;
mod mcp_e2e;
mod script;
+39
View File
@@ -0,0 +1,39 @@
use std::process::Command;
use serde_json::{Value, json};
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
/// `run` with `script.run` after `file.new`, with `params`.
fn run_script(params: &Value) -> std::process::Output {
Command::new(BIN).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", &params.to_string()]).output().unwrap()
}
/// `run` runs a script headless: the reply holds the report, with what the script logged and the
/// documents it changed.
#[test]
fn run_gives_the_report_of_a_script() {
let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.log(vc.args.n * 2);";
let out = run_script(&json!({"source": source, "name": "double.js", "args": {"n": 21}}));
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let lines: Vec<Value> = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(lines.len(), 2, "{lines:?}");
assert_eq!(lines[1]["command"], "script.run");
let report = &lines[1]["result"];
assert_eq!(report["ok"], true, "{report}");
assert_eq!(report["name"], "double.js");
assert_eq!(report["log"], json!([42]), "{report}");
assert_eq!(report["changed"].as_array().map(Vec::len), Some(1), "{report}");
}
/// A script that throws fails its step with the script's message, and the steps before it ran.
#[test]
fn run_fails_the_step_of_a_script_that_throws() {
let out = run_script(&json!({"source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); throw new Error('no margin given');"}));
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("step 1 (script.run)") && stderr.contains("no margin given"), "{stderr}");
let printed: Vec<Value> = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(printed.len(), 1, "only file.new printed: {printed:?}");
assert_eq!(printed[0]["command"], "file.new");
}
+1 -1
View File
@@ -26,7 +26,7 @@ log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
rfd = { workspace = true }
rfd = { workspace = true, features = ["file-handle-inner"] }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
wasm-bindgen-futures = "0.4"
+31 -2
View File
@@ -9,6 +9,9 @@ use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour, is_address};
use vectorcraft_engine::cmd::fileio;
use vectorcraft_engine::cmd::recovery::{self, Hold, RecoveryStore};
use vectorcraft_engine::cmd::scripts::RUN_EXTS;
use vectorcraft_engine::script::MAX_SOURCE_BYTES;
use vectorcraft_ui_egui::dialogs::script_run::ScriptInbox;
use vectorcraft_ui_egui::graphics::GraphicsLoss;
use vectorcraft_ui_egui::i18n;
use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox};
@@ -47,6 +50,7 @@ struct Host {
runner: eframe::WebRunner,
inbox: Inbox,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
drag: DragPos,
pasted: Rc<RefCell<Pasted>>,
/// Pen and finger input read from the page's Pointer Events (`crate::pencil`).
@@ -75,6 +79,7 @@ pub fn start() {
runner: eframe::WebRunner::new(),
inbox: Arc::default(),
place_inbox: Arc::default(),
script_inbox: Arc::default(),
drag: DragPos::default(),
pasted: Rc::default(),
pointers: SharedPointers::default(),
@@ -120,7 +125,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
}
host.pasted.borrow_mut().ctx = Some(ctx.clone());
let stylus = host.pointers.borrow().stylus();
let services = services(host.inbox.clone(), host.place_inbox.clone(), ctx.clone(), host.locks.clone(), stylus);
let services =
services(host.inbox.clone(), host.place_inbox.clone(), host.script_inbox.clone(), ctx.clone(), host.locks.clone(), stylus);
let app = match taken.borrow_mut().take() {
Some(mut app) => {
// The old services asked the old context for frames.
@@ -425,12 +431,35 @@ impl eframe::App for WebShell {
}
}
fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option<WebLocks>, stylus: StylusFeed) -> Services {
fn services(
inbox: Inbox,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
ctx: egui::Context,
locks: Option<WebLocks>,
stylus: StylusFeed,
) -> Services {
let open_inbox = inbox.clone();
let picked = place_inbox.clone();
let place_ctx = ctx.clone();
let screen_color = eye_dropper(ctx.clone());
let (script_picked, script_ctx) = (script_inbox.clone(), ctx.clone());
Services {
// File › Scripts › Other Script…: the picked file goes to the warning before it runs.
script_async: Some(Box::new(move || {
let inbox = script_picked.clone();
let ctx = script_ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let filter = vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", "Scripts");
let Some(file) = rfd::AsyncFileDialog::new().add_filter(filter, RUN_EXTS).pick_file().await else {
return;
};
let bytes = if file.inner().size() > MAX_SOURCE_BYTES as f64 { None } else { Some(file.read().await) };
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
ctx.request_repaint();
});
})),
script_inbox: Some(script_inbox),
// File → Place…: the picked files go to the Place dialog.
place_async: Some(Box::new(move || {
let inbox = picked.clone();
-1
View File
@@ -8,7 +8,6 @@ mod layers;
mod profile;
mod stroke_style;
pub(crate) use layers::HEAD_REACH;
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
+3 -6
View File
@@ -139,10 +139,6 @@ impl StrokeGradientMode {
}
}
/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are
/// cut square a little behind its 4 × 4 box).
pub(crate) const HEAD_REACH: f64 = 4.6;
fn ten() -> f64 {
10.0
}
@@ -188,7 +184,8 @@ impl StrokeLayer {
}
}
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide.
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see
/// [`Arrowhead::reach`] and [`Arrowhead::half_width`]).
pub fn arrow_weight(&self, end: bool) -> f64 {
let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 };
(self.width * pct / 100.0).max(0.25)
@@ -197,7 +194,7 @@ impl StrokeLayer {
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
pub fn head_reach(&self, end: bool) -> f64 {
let head = if end { self.end_arrow } else { self.start_arrow };
head.map_or(0.0, |_| HEAD_REACH * self.arrow_weight(end) + self.width / 2.0)
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
}
/// How far the arrowheads can reach from the path's end points (0 without heads).
pub fn arrow_reach(&self) -> f64 {
+27 -1
View File
@@ -49,6 +49,10 @@ impl Dash {
}
}
/// How far the arrowheads drawn in the 4 × 4 box reach from their tip, in units of their weight
/// (the open arrow's arms are cut square a little behind the box).
const HEAD_REACH: f64 = 4.6;
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Arrowhead {
@@ -94,13 +98,18 @@ pub enum Arrowhead {
Kite,
TriangleBar,
Oval,
/// Two arms of the head's weight (the line's weight at 100 % scale, for lines of 0.25 pt or
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
/// the other heads.
LineArrow,
}
impl Arrowhead {
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
pub const ALL: [Arrowhead; 40] = [
pub const ALL: [Arrowhead; 41] = [
Arrowhead::Arrow,
Arrowhead::ArrowOpen,
Arrowhead::LineArrow,
Arrowhead::Barbed,
Arrowhead::Concave,
Arrowhead::DoubleArrow,
@@ -141,6 +150,22 @@ impl Arrowhead {
Arrowhead::Fork,
];
/// How far any part of the head can be from its tip, in units of its weight.
pub fn reach(self) -> f64 {
match self {
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
Arrowhead::LineArrow => 5.75,
_ => HEAD_REACH,
}
}
/// How far the head spreads either side of its line, in units of its weight.
pub fn half_width(self) -> f64 {
match self {
Arrowhead::LineArrow => 4.0,
_ => 2.0,
}
}
/// The name the arrowhead menus show.
pub fn label(self) -> &'static str {
match self {
@@ -184,6 +209,7 @@ impl Arrowhead {
Arrowhead::Kite => "Kite",
Arrowhead::TriangleBar => "Triangle to Bar",
Arrowhead::Oval => "Oval",
Arrowhead::LineArrow => "Line Arrow",
}
}
}
+10 -3
View File
@@ -219,7 +219,7 @@ fn profile_presets_round_trip_their_ids() {
#[test]
fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
// Saved files store these names: they may only ever be appended to.
const SAVED: [&str; 40] = [
const SAVED: [&str; 41] = [
"Triangle",
"TriangleOpen",
"Circle",
@@ -260,6 +260,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
"Kite",
"TriangleBar",
"Oval",
"LineArrow",
];
for name in SAVED {
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
@@ -293,9 +294,15 @@ fn outset_covers_arrowheads() {
st.arrow_scale = (100.0, 200.0);
assert_eq!(st.arrow_weight(false), 4.0);
assert_eq!(st.arrow_weight(true), 8.0);
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0));
let reach = Arrowhead::Triangle.reach();
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, reach * 8.0 + 2.0));
// A 32 pt head whose tip sits up to its length (plus the cap) past the end point.
assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0);
assert_eq!(a.outset(), reach * 8.0 + 2.0);
// The line arrow's arms spread twice as wide, so it reaches further from its tip.
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::LineArrow);
assert!(Arrowhead::LineArrow.reach() > reach);
assert_eq!(a.outset(), Arrowhead::LineArrow.reach() * 8.0 + 2.0);
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::Triangle);
a.stroke_mut().unwrap().width = 0.01;
assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size");
}
+5
View File
@@ -276,6 +276,11 @@ impl Document {
self.next_id
}
/// Makes the next id at least `id`, so ids below it are not given out again.
pub fn raise_next_id(&mut self, id: u64) {
self.next_id = self.next_id.max(id);
}
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data).
pub fn fix_next_id(&mut self) {
// Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a
+23 -15
View File
@@ -123,18 +123,33 @@ impl Document {
std::borrow::Cow::Owned(d)
}
/// Does `wants` hold for a node anywhere in the document's art: the layers, symbol definitions,
/// graph designs, pattern swatches (the one being edited included) and their opacity masks?
pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool {
let roots = self
.layers
/// The roots of every tree of the document's art: the layers, symbol definitions, graph designs,
/// pattern swatches and the original of the pattern being edited. Opacity masks hang off nodes
/// in these trees.
pub fn art_roots(&self) -> impl Iterator<Item = &Arc<Node>> {
self.layers
.iter()
.chain(self.symbols.iter().map(|s| &s.art))
.chain(self.graph_designs.iter().map(|g| &g.art))
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()));
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()))
}
/// [`Self::art_roots`], to change.
pub fn art_roots_mut(&mut self) -> impl Iterator<Item = &mut Arc<Node>> {
self.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()))
}
/// Does `wants` hold for a node anywhere in the document's art ([`Self::art_roots`]) or its
/// opacity masks?
pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool {
let mut any = false;
for root in roots {
for root in self.art_roots() {
crate::swatches::walk_with_masks(root, &mut |n| any |= wants(n));
}
any
@@ -144,14 +159,7 @@ impl Document {
/// [`Self::any_node`] looks). Only the trees that hold such a node are copied out of the art
/// they share.
pub fn edit_nodes_where(&mut self, wants: impl Fn(&Node) -> bool, mut f: impl FnMut(&mut Node)) {
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in roots {
for root in self.art_roots_mut() {
edit_branches_where(root, &wants, &mut f);
}
}
+6 -6
View File
@@ -7,7 +7,6 @@ use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest};
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2};
use crate::appearance::HEAD_REACH;
use crate::{Appearance, ArrowAlign, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile};
/// Arc-length accuracy for placing a point along a profile (document points).
@@ -386,18 +385,19 @@ impl StrokeLayer {
}
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
/// leaving along `out`) can paint? Heads are at most about 4.6 weights long and 4 wide. With
/// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and
/// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With
/// [`ArrowAlign::Extend`] a head points along `out` with its tip up to its length (or the cap)
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
/// chord the path bends through under it, so anywhere within its length of the end.
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
let hw = self.arrow_weight(end);
let v = p - at;
let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false };
let (hw, v) = (self.arrow_weight(end), p - at);
match self.arrow_align {
ArrowAlign::Tip => v.hypot() <= HEAD_REACH * hw + tol,
ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol,
ArrowAlign::Extend => {
let along = v.dot(out);
v.cross(out).abs() <= 2.0 * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -HEAD_REACH * hw - tol
v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol
}
}
}
+33
View File
@@ -158,6 +158,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
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 },
];
/// Built-in library `id`, made once.
@@ -453,6 +454,34 @@ fn blends_transparency() -> Vec<GraphicStyle> {
]
}
/// Game HUD: fills and glows for health, mana, damage and quest chrome (original arcade/HUD look).
fn game_hud() -> Vec<GraphicStyle> {
vec![
style("Health Fill", vec![F(fill("#e74c3c")), S(stroke("#5c1a1a", 1.25))], vec![]),
style(
"Mana Glow",
vec![F(fill("#3498db"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 7.0, "color": "#5dade2"}))],
),
style(
"Damage Flash",
vec![F(fill("#ff6b35"))],
vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 80.0, "blur": 8.0, "color": "#ffe66d", "source": "edge"}))],
),
style("Quest Outline", vec![F(fill("#f7f3e8")), S(round("#2c3e50", 3.0))], vec![]),
style(
"Coin Shine",
vec![F(fill("#f1c40f")), S(stroke("#b7950b", 1.5))],
vec![fx("stylize.dropShadow", json!({"mode": "multiply", "opacity": 40.0, "x": 2.0, "y": 3.0, "blur": 4.0, "color": "#1d1b2a"}))],
),
style(
"Boss Alert",
vec![F(fill("#1a1a2e")), S(round("#e94560", 2.5))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 6.0, "color": "#e94560"}))],
),
]
}
#[cfg(test)]
mod tests {
use super::*;
@@ -475,6 +504,10 @@ mod tests {
}
assert!(Arc::ptr_eq(&builtin_style_library("hand-drawn").unwrap(), &builtin_style_library("hand-drawn").unwrap()), "made once");
assert!(builtin_style_library("nope").is_none());
let game = builtin_style_library("game-hud").unwrap();
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"]);
}
#[test]
+18
View File
@@ -367,6 +367,24 @@ impl TextObject {
pub fn move_path_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool {
matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| move_anchors(path, to_text, refs, d))
}
/// Move the out (`out`) or in direction handle of anchor `ai` of subpath `si` of type on a
/// path's path to `pos` in document space, as a path's anchor takes it
/// ([`vectorcraft_geom::Anchor::set_handle`]; `independent`: that side only, the anchor a
/// corner): a Direct Selection drag of a handle (#3565). The handle is set in document space,
/// so a smooth anchor keeps its other handle's length as drawn; the brackets keep their
/// fractions of the path. False, changing nothing, for other type, when the anchor doesn't
/// exist, a degenerate `xf` or a path that would not be finite.
pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool {
let xf = self.xf;
matches!(self.kind, TextKind::OnPath { .. })
&& self.reshape_local(|path, to_text| {
let Some(a) = path.anchor_mut(si, ai) else { return false };
let mut drawn = a.transform(xf);
drawn.set_handle(out, pos, independent);
*a = drawn.transform(to_text);
true
})
}
/// Edit a copy of the area frame with `f` (given the document → text space map) and keep it
/// when `f` succeeds and the result is finite.
fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool {
+15 -5
View File
@@ -1,5 +1,5 @@
//! Arrowheads. A head of weight `hw` (stroke weight × scale) fits a box `4·hw` long and `4·hw`
//! wide. Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms.
//! wide; the line arrow's arms reach twice as far out ([`Arrowhead::half_width`]). Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms.
//! The stroke ends under the head at the head's *inset* from the tip: halfway into solid heads,
//! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
@@ -8,7 +8,7 @@
use std::borrow::Cow;
use std::f64::consts::{FRAC_PI_2, PI};
use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, PI};
use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen, PathSeg, Point, Shape, Vec2};
use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer};
@@ -252,6 +252,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2;
/// Flattening tolerance of the curved local heads, in units.
const LOCAL_TOL: f64 = 1e-3;
/// Where the stroke ends under a head drawn in local units ([`local`]), in those units.
fn local_stop(kind: Arrowhead) -> Stop {
match kind {
Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0),
@@ -261,7 +262,7 @@ fn local_stop(kind: Arrowhead) -> Stop {
Arrowhead::Fork => Stop::At(2.7),
Arrowhead::HalfArrowLeft | Arrowhead::HalfArrowRight | Arrowhead::Feather => Stop::At(1.3),
Arrowhead::Swallowtail => Stop::At(1.4),
Arrowhead::Chevron => Stop::At(1.0),
Arrowhead::Chevron | Arrowhead::LineArrow => Stop::At(1.0),
Arrowhead::Slash => Stop::At(1.2),
Arrowhead::DoubleSlash => Stop::At(1.05),
Arrowhead::DoubleArrow => Stop::At(1.7),
@@ -273,8 +274,9 @@ fn local_stop(kind: Arrowhead) -> Stop {
}
/// The outline of a head added after the first ten, in local units: x from the tip (0) back
/// along the line (to at most 4), y across it (−2 to 2, positive to the right of the direction
/// the head points). Every shape is generated here.
/// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2,
/// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape
/// is generated here.
fn local(kind: Arrowhead) -> BezPath {
let mut p = BezPath::new();
let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>());
@@ -363,6 +365,14 @@ fn local(kind: Arrowhead) -> BezPath {
poly(&mut p, &[(0.0, 2.0), (0.6, 2.0), (0.6, 0.25), (4.0, 1.8), (4.0, -1.8), (0.6, -0.25), (0.6, -2.0), (0.0, -2.0)])
}
Arrowhead::Oval => p.extend(kurbo::Ellipse::new((2.0, 0.0), (2.0, 1.2), 0.0).path_elements(LOCAL_TOL)),
Arrowhead::LineArrow => {
// Arms one unit thick (the head's weight: the line's at 100 % for lines of 0.25 pt or
// more) at right angles to each other, from a sharp tip to their outer corners at
// (4, ±4), cut square across: a unit across an arm at 45° is ½√2 along each axis, and
// the arms' inner edges meet √2 behind the tip.
let t = FRAC_1_SQRT_2;
poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]);
}
// The first ten are drawn by `shape`.
Arrowhead::Triangle
| Arrowhead::TriangleOpen
+35 -4
View File
@@ -1,6 +1,6 @@
//! Every arrowhead's outline: drawn, inside its box (4 × 4 weights; the open arrow's square-cut
//! arms reach a little further back), without self-intersections, and covering the end of the
//! stroke under it.
//! Every arrowhead's outline: drawn, inside its reach and half width (4 × 4 weights for most; the
//! open arrow's square-cut arms reach a little further back, the line arrow's twice as far out),
//! without self-intersections, and covering the end of the stroke under it.
use kurbo::{BezPath, PathEl, Point, Shape};
use vectorcraft_color::{Color, Paint};
@@ -53,7 +53,13 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
let h = head(kind);
assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn");
let b = h.outline.bounding_box();
assert!(b.x0 >= 91.0 - 1e-6 && b.x1 <= 100.0 + 1e-6 && b.y0 >= -4.0 - 1e-6 && b.y1 <= 4.0 + 1e-6, "{kind:?} leaves its box: {b:?}");
let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width());
assert!(b.x1 <= 100.0 + 1e-6 && b.y0 >= -side - 1e-6 && b.y1 <= side + 1e-6, "{kind:?} leaves its box: {b:?}");
if kind.half_width() == 2.0 {
assert!(b.x0 >= 91.0 - 1e-6, "{kind:?} is longer than the 4 × 4 box: {b:?}");
}
let far = contours(&h.outline).iter().flatten().map(|p| p.distance(h.tip)).fold(0.0, f64::max);
assert!(far <= reach + 1e-6, "{kind:?} reaches {far} from its tip, past {reach}");
let edges: Vec<(Point, Point)> = contours(&h.outline).iter().flat_map(|c| (0..c.len()).map(|i| (c[i], c[(i + 1) % c.len()]))).collect();
assert!(edges.len() >= 3, "{kind:?}");
for (i, a) in edges.iter().enumerate() {
@@ -74,6 +80,31 @@ fn the_stroke_ends_inside_every_head() {
}
}
#[test]
fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() {
// Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt.
let h = head(Arrowhead::LineArrow);
let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y);
// A sharp tip on the end point; outer corners 4 units back and out, square-cut ends.
let pts: Vec<Point> = contours(&h.outline).concat();
for (corner, name) in [(at(0.0, 0.0), "tip"), (at(4.0, 4.0), "right corner"), (at(4.0, -4.0), "left corner")] {
assert!(pts.iter().any(|p| p.distance(corner) < 1e-9), "{name} {corner:?} in {pts:?}");
}
// Open between the arms, solid at the tip.
assert_eq!(h.outline.winding(at(2.5, 0.0)), 0);
assert_ne!(h.outline.winding(at(0.7, 0.0)), 0);
// Halfway along each arm, 45° off the line, it is one unit (the line's weight) across.
let s = std::f64::consts::FRAC_1_SQRT_2;
for side in [1.0, -1.0] {
let (mx, my) = (2.0 + 0.5 * s, side * (2.0 - 0.5 * s));
let (nx, ny) = (-side * s, s);
for (d, inside) in [(0.45, true), (-0.45, true), (0.55, false), (-0.55, false)] {
let w = h.outline.winding(at(mx + nx * d, my + ny * d));
assert_eq!(w != 0, inside, "arm {side} at {d} across");
}
}
}
#[test]
fn half_arrows_barb_on_their_own_side() {
// Pointing along +x on a y-down page, left is −y.
+1
View File
@@ -40,6 +40,7 @@ vectorcraft-metafile = { workspace = true }
vectorcraft-plugins = { workspace = true }
vectorcraft-affinity = { workspace = true }
vectorcraft-scriptcheck = { workspace = true }
vectorcraft-js = { workspace = true }
# The commands' parameter schemas (schemas.rs).
vectorcraft-apischema = { workspace = true }
image = { workspace = true }
@@ -635,6 +635,7 @@ pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) {
}
};
st.change_unsaved(clear);
st.history.rewrites += 1;
for e in st.history.undo.iter_mut().chain(st.history.redo.iter_mut()) {
let saved = Arc::ptr_eq(&e.doc, &st.saved_doc);
clear(&mut e.doc);
+31
View File
@@ -914,3 +914,34 @@ fn read_path_for_a_named_importer_stops_at_the_limit() {
assert!(e.to_string().contains("larger than") && e.to_string().contains("drawing.tuv"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
/// #3084, #2096: Export for Screens writes JPGs a strict reader opens, in every colour model and at
/// the qualities and scales the reports used. A four-component (CMYK) file has no JFIF segment,
/// which describes only one- and three-component images (#3140); RGB and gray files keep it.
#[test]
fn export_for_screens_jpgs_open_in_every_colour_model() {
let mut s = session(100.0, 80.0, 1);
s.execute("paint.setFill", &json!({"color": "#cc3300"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap();
for (model, components) in [("rgb", 3), ("cmyk", 4), ("gray", 1)] {
for quality in [100, 80, 50] {
let r = s
.execute(
"document.exportForScreens",
&json!({"formats": [{"format": "jpg"}, {"format": "jpg", "scale": 2}], "settings": {"jpg": {"colorModel": model, "quality": quality}}}),
)
.unwrap();
let files = r["files"].as_array().unwrap();
assert_eq!(files.len(), 2, "{model} {quality}: {r}");
for (f, width) in files.iter().zip([100, 200]) {
let bytes = b64(f);
let what = format!("{model} q{quality} {}", f["name"]);
assert_eq!(bytes.get(..2), Some(&[0xFF, 0xD8][..]), "{what}: starts with SOI");
let jfif = bytes.get(2..4) == Some(&[0xFF, 0xE0][..]);
assert_eq!(jfif, components != 4, "{what}: JFIF only on one- and three-component files");
let image = image::load_from_memory(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(image.width(), width, "{what}");
}
}
}
}
+1
View File
@@ -140,6 +140,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool),
p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool),
p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool),
p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool),
p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool),
+32 -2
View File
@@ -766,11 +766,14 @@ pub fn skip_reason(s: &Session, st: &DocState) -> Option<&'static str> {
return Some("unchanged since its last recovery copy");
}
if s.prefs.recovery_off_for_complex && object_count(&st.doc) > COMPLEX_OBJECTS {
return Some("complex document (Data Recovery is off for complex documents)");
return Some(COMPLEX_SKIP);
}
None
}
/// Why a complex document with unsaved changes gets no copy.
const COMPLEX_SKIP: &str = "complex document (Data Recovery is off for complex documents)";
/// A file name part from a title: letters, digits, `-`, `_` and spaces (others as `-`).
fn safe_stem(title: &str) -> String {
let stem: String = fileio::file_stem(title).chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ') { c } else { '-' }).collect();
@@ -866,8 +869,35 @@ fn remove_copy(s: &Session, file: &str) {
}
}
/// Document `uid` was saved, reverted or closed: its recovery copy goes.
/// Closed document `st`'s recovery copy goes.
pub(crate) fn forget_closed(s: &Session, st: &crate::DocState) {
if let Some(copy) = &st.recovery {
remove_copy(s, &copy.file);
}
}
/// Writes a copy of every document that needs one now. An error when a document with unsaved
/// changes would be left without a current copy.
pub(crate) fn save_copies(s: &mut Session) -> Result<()> {
let store = need_store(s, "script.run")?;
let (jobs, _) = jobs(s, &store)?;
let uncopied = s.documents().iter().any(|st| skip_reason(s, st) == Some(COMPLEX_SKIP));
if uncopied {
return Err(EngineError::Other("a document with unsaved changes has no recovery copy".into()));
}
for j in jobs {
j.write(store.as_ref()).map_err(EngineError::Other)?;
j.finish(s);
}
Ok(())
}
/// Document `uid` was saved, reverted or closed: its recovery copy goes. While a script runs the
/// run's commit settles that.
pub fn forget(s: &mut Session, uid: u64) {
if s.script_in_run {
return;
}
let Some(copy) = s.document_mut(uid).and_then(|st| st.recovery.take()) else { return };
remove_copy(s, &copy.file);
}
+128 -10
View File
@@ -11,21 +11,139 @@ use vectorcraft_scriptcheck::{Limits, Loaded, Loader, Report};
/// The ids a reply can hold, for the windows that show it.
pub use vectorcraft_scriptcheck::{IncludeStatus, Need, OUTSIDE, PROBLEMS};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param};
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param};
use crate::script;
/// The extensions of the scripts File › Open shows a check for.
pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"];
/// The extensions of the scripts `script.run` takes as a file, in any case.
pub const RUN_EXTS: &[&str] = &["js", "jsx"];
/// Does `path` name a file `script.run` takes?
pub fn runs(path: &str) -> bool {
std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| RUN_EXTS.iter().any(|x| e.eq_ignore_ascii_case(x)))
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
query "script.check",
"Check Script",
[],
None,
"{path? | data?: the script's text | dataBase64?, name?: the file's name (default: the path's; with a path, only the reply's name), includes?: false (with a path: also check the files its #include lines name, inside the script's folder; not on the web)} check a script written for the reference app (.jsx, .jsxinc, .js, or a compiled .jsxbin) without running any of it → {name, kind: script|compiled|module|notText|tooLarge, needs: [language|dom|files|menuCommands|dialogs|hostOnly], lines, targets: [{value, app, instance?, version?, locale?, line, file?}], directives: [{name, value, line, form: \"#\"|\"//@\", file?}], includes: [{value, line, status: checked|missing|notFollowed|cycle|notRead|limit|unreadable, path?, file?}], features: [{id, count, lines}], dom: {members: [{path, count}], types: [{name, count}]}, menuCommands: {strings: [{value, count, lines}], dynamic}, outside: [{id: filesWritten|filesOpened|network|nativeCode|otherApps|environment|unseenCode|preferences, count, lines, modes?}], problems: [{code, line?, file?, detail?}], truncated} (file: the included file it is in; lines: at most 20 of the script's own, while counts include the included files; at most 8 MiB a file and 32 MiB in all, 64 included files 16 deep, 1,024 paths looked up for them, 1,000 entries a list, text echoed cut to 120 characters)",
always,
check
)]
vec![
cmd!(
query "script.run",
"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",
always,
run
),
cmd!(
query "script.stop",
"Stop Script",
[],
None,
"{} stop the running script, which puts every document back as it was before the run; asking again while it stops is harmless → {stopped: whether a script was running}",
always,
stop
),
cmd!(
query "script.check",
"Check Script",
[],
None,
"{path? | data?: the script's text | dataBase64?, name?: the file's name (default: the path's; with a path, only the reply's name), includes?: false (with a path: also check the files its #include lines name, inside the script's folder; not on the web)} check a script written for the reference app (.jsx, .jsxinc, .js, or a compiled .jsxbin) without running any of it → {name, kind: script|compiled|module|notText|tooLarge, needs: [language|dom|files|menuCommands|dialogs|hostOnly], lines, targets: [{value, app, instance?, version?, locale?, line, file?}], directives: [{name, value, line, form: \"#\"|\"//@\", file?}], includes: [{value, line, status: checked|missing|notFollowed|cycle|notRead|limit|unreadable, path?, file?}], features: [{id, count, lines}], dom: {members: [{path, count}], types: [{name, count}]}, menuCommands: {strings: [{value, count, lines}], dynamic}, outside: [{id: filesWritten|filesOpened|network|nativeCode|otherApps|environment|unseenCode|preferences, count, lines, modes?}], problems: [{code, line?, file?, detail?}], truncated} (file: the included file it is in; lines: at most 20 of the script's own, while counts include the included files; at most 8 MiB a file and 32 MiB in all, 64 included files 16 deep, 1,024 paths looked up for them, 1,000 entries a list, text echoed cut to 120 characters)",
always,
check
),
]
}
/// A refusal of `script.run`'s parameters, which only a program's own call can give.
fn param(msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: "script.run".into(), msg: msg.into() }
}
/// `maxFuel`: a whole number from 1 to [`script::MAX_FUEL`], or the default when omitted.
fn max_fuel(p: &Value) -> Result<u64> {
let Some(v) = p.get("maxFuel") else { return Ok(script::DEFAULT_FUEL) };
v.as_u64()
.filter(|n| (1..=script::MAX_FUEL).contains(n))
.ok_or_else(|| param(format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL)))
}
/// The text of a script read as bytes: a byte order mark is left out, and compiled scripts and
/// bytes that are not UTF-8 are refused.
fn script_text(bytes: &[u8]) -> Result<String> {
if bytes.starts_with(b"@JSXBIN@") {
return Err(EngineError::Other(COMPILED.to_string()));
}
let text = std::str::from_utf8(bytes).map_err(|_| EngineError::Other(NOT_TEXT.to_string()))?;
Ok(text.strip_prefix('\u{feff}').unwrap_or(text).to_string())
}
const COMPILED: &str = "this is a compiled script, which cannot be run; use its source text";
const NOT_TEXT: &str = "the script is not UTF-8 text";
/// The error for a script over [`script::MAX_SOURCE_BYTES`].
pub const TOO_LARGE: &str = "the script is too large to run";
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let optional_str = |key: &str| match p.get(key) {
None => Ok(None),
Some(Value::String(t)) => Ok(Some(t.as_str())),
Some(_) => Err(param(format!("`{key}` must be a string"))),
};
let (path, source, given_name) = (optional_str("path")?, optional_str("source")?, optional_str("name")?);
// Checked before anything copies or writes out `args`, which would go one call deeper per level.
if let Some(place) = p.get("args").and_then(script::too_deep) {
return Err(param(format!("`args{place}` is nested more than 64 levels deep")));
}
let args = match p.get("args") {
None => serde_json::Map::new(),
Some(Value::Object(o)) => o.clone(),
Some(_) => return Err(param("`args` must be an object")),
};
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 fuel = max_fuel(p)?;
let text = match (path, source) {
(Some(""), None) => return Err(param("`path` is empty")),
(Some(path), None) => {
if path.to_ascii_lowercase().ends_with(".jsxbin") {
return Err(EngineError::Other(COMPILED.to_string()));
}
if !runs(path) {
return Err(param("`path` must name a .js or .jsx file"));
}
// One byte more than a script may have shows that the file is too large.
let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?;
if bytes.len() > script::MAX_SOURCE_BYTES {
return Err(EngineError::Other(TOO_LARGE.to_string()));
}
script_text(&bytes)?
}
(None, Some(source)) => {
if source.len() > script::MAX_SOURCE_BYTES {
return Err(EngineError::Other(TOO_LARGE.to_string()));
}
script_text(source.as_bytes())?
}
_ => 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 })?;
if s.script_frames {
return Ok(json!({"running": true, "name": name}));
}
s.script_run_to_end()
}
fn stop(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({"stopped": s.script_request_stop()}))
}
/// The folder a script is in, which its included files are read from.
+1 -1
View File
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
["Window", "Stroke"],
None,
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}",
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
+4 -3
View File
@@ -140,7 +140,7 @@ pub(crate) fn enter(s: &mut Session, p: &Value) -> Result<Value> {
}
s.end_text_edit();
let st = s.doc()?;
let back = Return { redo: st.history.redo.clone(), before: Some(st.doc.clone()) };
let back = Return { redo: Arc::new(st.history.redo.clone()), before: Some(st.doc.clone()) };
let (isolation, active_layer) = (st.isolation, st.active_layer);
let layer = s.edit(ENTER, |d, sel| {
let layer = begin(d, sel, &name, xf, instance)?;
@@ -229,7 +229,7 @@ pub(crate) fn leave(s: &mut Session, _: &Value) -> Result<Value> {
}
st.selection = Arc::unwrap_or_clone(entry.selection);
st.selection.prune(&st.doc);
st.history.redo = redo;
st.history.redo = Arc::unwrap_or_clone(redo);
st.revision += 1;
} else {
s.edit("Exit Symbol Editing Mode", |d, sel| {
@@ -257,9 +257,10 @@ pub(crate) fn finish(d: &mut Document, sel: &mut Selection) {
/// The redo steps entering symbol editing mode cleared, which leaving without an edit gives back,
/// and the document entering started from, which tells the entering step apart from any other.
/// Copies of the document's state share the redo steps.
#[derive(Clone, Debug, Default)]
pub(crate) struct Return {
redo: Vec<crate::HistoryEntry>,
redo: Arc<Vec<crate::HistoryEntry>>,
before: Option<Arc<Document>>,
}
+28
View File
@@ -157,6 +157,7 @@ pub struct BuiltinSymbolLibrary {
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 },
];
/// Built-in library `id`, made once.
@@ -221,6 +222,33 @@ fn ui_frames() -> SymbolLibrary {
SymbolLibrary { name: "UI Frames".into(), doc }
}
/// Map Markers: pin, flag, crosshair and checkpoint for map/HUD art (original, no 9-slice).
fn map_markers() -> SymbolLibrary {
let c = Point::ZERO;
let pin = [(0.0, 22.0), (-9.0, 4.0), (-12.0, -6.0), (-8.0, -16.0), (0.0, -20.0), (8.0, -16.0), (12.0, -6.0), (9.0, 4.0)];
let flag = [(-16.0, 22.0), (-12.0, 22.0), (-12.0, -8.0), (18.0, -14.0), (-12.0, -20.0), (-12.0, -22.0), (-16.0, -22.0)];
let pin: Vec<Point> = pin.iter().map(|&(x, y)| Point::new(x, y)).collect();
let flag: Vec<Point> = flag.iter().map(|&(x, y)| Point::new(x, y)).collect();
let markers = [
("Pin", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pin, true)), "#e74c3c"),
("Flag", vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&flag, true)), "#3498db"),
("Crosshair", shapes::star(c, 20.0, 5.0, 4, 0.0), "#2c3e50"),
("Checkpoint", shapes::polygon(c, 18.0, 4, 0.0), "#27ae60"),
];
let mut doc = Document::new(100.0, 100.0);
for (name, path, hex) in markers {
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 = "Map Markers".into();
SymbolLibrary { name: "Map Markers".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 })
+38
View File
@@ -115,6 +115,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
reshape_path
),
cmd!(
"text.setPathHandle",
"Move Type Path Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path)",
has_doc,
set_path_handle
),
cmd!(
"text.fitHeadline",
"Fit Headline",
@@ -1268,6 +1277,35 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.setPathHandle";
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 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);
let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. }));
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
return Err(bad(C, "not type on a path outside perspective"));
}
s.edit("Reshape Type Path", |doc, _| {
let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
let before = t.kind.clone();
let within = |t: &TextObject| {
t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD))
};
if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) {
t.kind = before;
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
}
refresh_bounds(t);
Ok(())
})?;
ok()
}
#[cfg(test)]
mod area_tests;
@@ -2081,3 +2081,35 @@ fn fit_min_percent_for_several_frames_keeps_each_frames_fit() {
assert_eq!(fit(&s, plain), vectorcraft_doc::AreaFit::None, "the plain frame doesn't start shrinking");
assert_eq!(fit(&s, shrink), vectorcraft_doc::AreaFit::ShrinkText { min_percent: 30.0 });
}
/// #3565: `text.setPathHandle` moves a direction handle of type on a path's path, in document
/// space, as `path.setHandle` moves a path's: a smooth anchor's other handle turns with it at
/// its length, `independent` leaves it and makes the anchor a corner; one undo step.
#[test]
fn set_path_handle_reshapes_type_on_a_path() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let path =
s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 300, "in": [50, 300], "out": [150, 300]}, {"x": 400, "y": 300}]})).unwrap();
let text = s.execute("text.createInPath", &json!({"path": path["id"], "mode": "onPath", "text": "Along the curve"})).unwrap();
let id = NodeId(text["id"].as_u64().unwrap());
let first = |s: &Session| match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => *t.type_path().unwrap().subpaths[0].anchors.first().unwrap(),
_ => panic!("not text"),
};
let smooth = first(&s).kind == vectorcraft_geom::AnchorKind::Smooth;
s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 0, "which": "out", "x": 100, "y": 250})).unwrap();
let a = first(&s);
assert!((a.h_out.x - 100.0).abs() < 1e-6 && (a.h_out.y - 250.0).abs() < 1e-6, "{a:?}");
if smooth {
assert!((a.h_in.x - 100.0).abs() < 1e-6 && (a.h_in.y - 350.0).abs() < 1e-6, "smooth: the in handle turns with it at its length: {a:?}");
}
s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 0, "which": "in", "x": 60, "y": 300, "independent": true})).unwrap();
let b = first(&s);
assert_eq!(b.h_out, a.h_out, "independent: the other handle stays");
assert_eq!(b.kind, vectorcraft_geom::AnchorKind::Corner);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(first(&s), a, "one undo step each");
assert!(s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 9, "which": "out", "x": 0, "y": 0})).is_err(), "no such anchor");
assert!(s.execute("text.setPathHandle", &json!({"id": path["id"], "anchor": 0, "which": "out", "x": 0, "y": 0})).is_err(), "not type");
}
+1
View File
@@ -83,6 +83,7 @@ pub(crate) fn strip_replay_only(id: &str, p: &mut Value) {
/// Instances and Lock Guides change the selection, and the proof views, the preferences and added
/// fonts give the documents new revisions (they draw again, and type lays out again).
const WAIT_FOR_TOOL_EDIT: &[&str] = &[
"script.run",
"command.batch",
"document.find",
"symbol.selectInstances",
+1 -1
View File
@@ -446,7 +446,7 @@ impl DocState {
}
let e = HistoryEntry::kept(label, doc, selection, &self.doc);
self.history.undo.push(e);
self.history.redo.clear();
self.history.clear_redo();
self.history.trim();
}
/// End the interaction in progress, undoing what it changed.
+6
View File
@@ -1,5 +1,8 @@
use super::{NodeId, cancel};
/// The text of [`EngineError::Busy`], which ends every error a frontend reports for it.
pub const SCRIPT_BUSY: &str = "a script is running: stop it or wait for it to finish";
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
#[error("unknown command `{0}`")]
@@ -20,6 +23,9 @@ pub enum EngineError {
/// The caller asked for the command to stop ([`cancel`]). It changed nothing.
#[error("cancelled; nothing was changed")]
Cancelled,
/// A running script holds the documents until it ends. Nothing was changed.
#[error("{}", SCRIPT_BUSY)]
Busy,
/// A bug: the command panicked. The document was rolled back to its state before the command.
#[error("internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug)")]
Internal { cmd: String, msg: String },
+34 -1
View File
@@ -208,7 +208,40 @@ pub fn check_read(path: &str) -> Result<(), String> {
/// May `path` be written here? Always, without roots in force.
pub fn check_write(path: &str) -> Result<(), String> {
current().map_or(Ok(()), |r| r.check(path, Access::Write))
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
WRITES.with(|w| {
if let Some(paths) = w.borrow_mut().as_mut()
&& !paths.iter().any(|(p, _)| p == path)
{
paths.push((path.to_string(), stamp(path)));
}
});
Ok(())
}
/// A file's modification time and length; `None` when there is no file at `path`.
type Stamp = Option<(Option<std::time::SystemTime>, u64)>;
fn stamp(path: &str) -> Stamp {
std::fs::metadata(path).ok().filter(std::fs::Metadata::is_file).map(|m| (m.modified().ok(), m.len()))
}
thread_local! {
/// The paths [`check_write`] allowed on this thread while they are being recorded, each with
/// its file's stamp at that moment.
static WRITES: std::cell::RefCell<Option<Vec<(String, Stamp)>>> = const { std::cell::RefCell::new(None) };
}
/// Starts recording the paths [`check_write`] allows on this thread.
pub(crate) fn start_recording_writes() {
WRITES.with(|w| *w.borrow_mut() = Some(Vec::new()));
}
/// Ends recording → the recorded paths whose file exists now: after a command that `succeeded`,
/// all of them; after one that failed, those made or changed since they were allowed.
pub(crate) fn finish_recording_writes(succeeded: bool) -> Vec<String> {
let recorded = WRITES.with(|w| w.borrow_mut().take()).unwrap_or_default();
recorded.into_iter().filter(|(path, before)| stamp(path).is_some_and(|now| succeeded || Some(now) != *before)).map(|(path, _)| path).collect()
}
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
+120 -2
View File
@@ -1,7 +1,13 @@
use super::{Arc, Document, Selection};
#[cfg(test)]
thread_local! {
/// Tests: how many undo steps were copied on this thread.
pub(crate) static ENTRY_CLONES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// One undo step.
#[derive(Clone, Debug)]
#[derive(Debug)]
pub struct HistoryEntry {
pub label: String,
/// The document as it was. It keeps no lookup cache ([`Document::drop_lookup_cache`]): a
@@ -27,6 +33,25 @@ pub struct HistoryEntry {
color_mode_bytes: usize,
}
impl Clone for HistoryEntry {
fn clone(&self) -> Self {
#[cfg(test)]
ENTRY_CLONES.with(|n| n.set(n.get() + 1));
HistoryEntry {
label: self.label.clone(),
doc: self.doc.clone(),
selection: self.selection.clone(),
bytes: self.bytes,
next_bytes: self.next_bytes,
next: self.next,
named: self.named.clone(),
serial: self.serial,
color_mode_paints: self.color_mode_paints.clone(),
color_mode_bytes: self.color_mode_bytes,
}
}
}
/// The next [`HistoryEntry::serial`]: 1 for the first step made, so 0 never names a step.
fn next_serial() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
@@ -148,11 +173,52 @@ pub struct History {
/// About the most memory the steps may keep ([`HistoryEntry::bytes`]): past it the oldest
/// steps go, but never the last [`History::MIN_STEPS`] undo (and redo) steps.
pub byte_budget: usize,
/// Counts the changes made in place to steps below the newest ([`History::put_back`]).
pub(crate) rewrites: u64,
/// Between [`History::mark`] and [`History::release`] or [`History::put_back`].
pub(crate) held: bool,
/// The redo steps a new step cleared while held ([`History::clear_redo`]).
pub(crate) set_aside: Option<Vec<HistoryEntry>>,
}
impl Default for History {
fn default() -> Self {
History { undo: vec![], redo: vec![], limit: 0, byte_budget: default_history_budget() }
History { undo: vec![], redo: vec![], limit: 0, byte_budget: default_history_budget(), rewrites: 0, held: false, set_aside: None }
}
}
/// What [`History::put_back`] needs to give a history back as it was when [`History::mark`] took
/// it: the newest undo and redo steps, and where each stack stood under them. It holds no other
/// step, so taking one costs the same however many the history holds.
pub(crate) struct HistoryMark {
undo: StackMark,
redo: StackMark,
limit: usize,
byte_budget: usize,
rewrites: u64,
}
/// One stack of a [`HistoryMark`].
struct StackMark {
len: usize,
/// [`HistoryEntry::serial`] of the step under the newest one, 0 for none.
below: u64,
newest: Option<HistoryEntry>,
}
impl StackMark {
fn of(steps: &[HistoryEntry]) -> Self {
let len = steps.len();
StackMark { len, below: len.checked_sub(2).and_then(|i| steps.get(i)).map_or(0, |e| e.serial), newest: steps.last().cloned() }
}
/// Puts `steps` back as they were. → `false` when a step under the newest one was removed since.
fn put_back(self, steps: &mut Vec<HistoryEntry>) -> bool {
let kept = self.len.saturating_sub(1);
let intact = steps.len() >= kept && kept.checked_sub(1).is_none_or(|i| steps.get(i).is_some_and(|e| e.serial == self.below));
steps.truncate(kept);
steps.extend(self.newest);
intact
}
}
@@ -208,6 +274,58 @@ impl History {
self.redo.drain(..n);
}
/// A [`HistoryMark`] of the history now. Until [`History::release`] or [`History::put_back`],
/// [`History::trim`] lets no step go, so the steps under the newest one stay where they are, and
/// [`History::clear_redo`] sets the redo steps aside.
pub(crate) fn mark(&mut self) -> HistoryMark {
let mark = HistoryMark {
undo: StackMark::of(&self.undo),
redo: StackMark::of(&self.redo),
limit: self.limit,
byte_budget: self.byte_budget,
rewrites: self.rewrites,
};
self.limit = usize::MAX;
self.byte_budget = usize::MAX;
self.held = true;
self.set_aside = None;
mark
}
/// Removes the redo steps, as a new step does. While held ([`History::mark`]) the first call
/// keeps them for [`History::put_back`].
pub(crate) fn clear_redo(&mut self) {
if self.held && self.set_aside.is_none() {
self.set_aside = Some(std::mem::take(&mut self.redo));
} else {
self.redo.clear();
}
}
/// Keeps the history as it is now: the limits `mark` held back apply again.
pub(crate) fn release(&mut self, mark: &HistoryMark) {
self.held = false;
self.set_aside = None;
self.limit = mark.limit;
self.byte_budget = mark.byte_budget;
self.trim();
}
/// Gives the history back as it was at `mark`. → `false` when that is not possible: an undo or
/// redo step under the newest one was removed or changed in place since.
pub(crate) fn put_back(&mut self, mark: HistoryMark) -> bool {
if let Some(redo) = self.set_aside.take() {
self.redo = redo;
}
let undo = mark.undo.put_back(&mut self.undo);
let redo = mark.redo.put_back(&mut self.redo);
let intact = self.rewrites == mark.rewrites && undo && redo;
self.held = false;
self.limit = mark.limit;
self.byte_budget = mark.byte_budget;
intact
}
/// Estimate the newest undo step again, its next state now being `now` (the steps after it were
/// merged into it, or an undo group extended it). It takes a new number ([`History::step`]).
pub(crate) fn recost_last(&mut self, now: &Document) {
+17 -1
View File
@@ -243,6 +243,21 @@ pub struct Session {
pub(crate) screens_hand_off: Option<Option<cmd::fileio::ScreenExport>>,
/// Where Data Recovery keeps its copies ([`cmd::recovery`]).
pub recovery: cmd::recovery::Recovery,
/// The running script's job, while there is one: the mutation lease ([`script`]).
pub(crate) script_key: Option<script::JobKey>,
/// Stops the running script at its next instruction; the same flag for every run.
pub(crate) script_stop: vectorcraft_js::Interrupt,
/// The report of the run that ended last.
pub(crate) script_report: Option<Value>,
/// `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,
/// Each open document's highest next id a run has seen, by [`DocState::uid`].
pub(crate) script_high_water: std::collections::HashMap<u64, u64>,
/// While a slice of a script runs in this session.
pub(crate) script_in_run: bool,
/// Write recovery copies of the unsaved documents before a run, and don't start without them.
pub script_copy_first: bool,
/// While the active tool's actions run: their commands aren't "a command from outside the
/// tool" ([`Session::after_command`]).
pub(crate) in_tool_actions: bool,
@@ -329,6 +344,7 @@ mod history;
mod interaction;
mod prefs;
mod sanity;
pub mod script;
mod session;
#[cfg(test)]
@@ -337,7 +353,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
use command_sets::given_ids;
pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
pub use doc_state::{DocState, OpenRows, RecalledSelection};
pub use error::{EngineError, Result};
pub use error::{EngineError, Result, SCRIPT_BUSY};
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
pub(crate) use interaction::PreviewCopies;
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
+8 -5
View File
@@ -84,9 +84,9 @@ pub(crate) fn update_changed(s: &mut Session, _: &Value) -> Result<Value> {
impl Session {
/// Start stamping the active document's linked files on a worker thread, unless a look is
/// still running (or the build has no files to look at: the web app).
/// still running, a script is running (or the build has no files to look at: the web app).
pub fn start_link_scan(&mut self) {
if self.link_scan.is_some() || cfg!(target_arch = "wasm32") {
if self.link_scan.is_some() || self.script_key.is_some() || cfg!(target_arch = "wasm32") {
return;
}
let Some(st) = self.active() else { return };
@@ -115,10 +115,13 @@ impl Session {
}
}
/// Apply a finished look (`None` while there is none, or it is still running): see
/// [`Session::apply_link_stamps`]. A look whose worker ended without stamps is cleared, also
/// with `None`, so the next one can start.
/// Apply a finished look (`None` while there is none, it is still running, or a script is
/// running): see [`Session::apply_link_stamps`]. A look whose worker ended without stamps is
/// cleared, also with `None`, so the next one can start.
pub fn poll_link_scan(&mut self) -> Option<Result<Value>> {
if self.script_key.is_some() {
return None;
}
self.link_scan.take_if(|scan| ended_without_stamps(scan, |ended| ended.load(Ordering::SeqCst)));
let (uid, stamps) = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?;
self.link_scan = None;
+3
View File
@@ -31,6 +31,8 @@ pub struct Prefs {
pub disable_auto_add_delete: bool,
pub use_precise_cursors: bool,
pub show_tool_tips: bool,
/// Other Script… warns before it runs a chosen script.
pub show_external_script_warning: bool,
pub anti_aliased_artwork: bool,
pub select_same_tint_percent: bool,
pub show_home_screen: bool,
@@ -372,6 +374,7 @@ impl Default for Prefs {
disable_auto_add_delete: false,
use_precise_cursors: false,
show_tool_tips: true,
show_external_script_warning: true,
anti_aliased_artwork: true,
select_same_tint_percent: false,
show_home_screen: true,
File diff suppressed because it is too large. Load diff
+7
View File
@@ -129,6 +129,13 @@ impl Session {
link_scan: None,
global_edit_options: Default::default(),
keyboard_text: false,
script_key: None,
script_stop: vectorcraft_js::Interrupt::new(),
script_report: None,
script_frames: false,
script_high_water: Default::default(),
script_in_run: false,
script_copy_first: cfg!(target_arch = "wasm32"),
}
}
+9
View File
@@ -7,6 +7,9 @@ impl Session {
/// Run `f` on a mutable copy of the active document. Outside an interaction this records one
/// undo step labelled `label`; inside one it just mutates (the interaction commits later).
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
if self.script_running() {
return Err(EngineError::Busy);
}
// An edit made while typing (the Transform panel) is a step of its own: inside the typing
// session, the next keystroke's preview would start again from before it (#1881).
if !self.previewing && cmd::typing_in_progress(self) {
@@ -225,6 +228,9 @@ impl Session {
}
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
if self.script_running() {
return Err(EngineError::Busy);
}
// Typing in progress is kept first: a drag or a dialog's preview would otherwise start
// from the snapshot taken before the typing, and drop it (#1881).
if label != "Typing" && cmd::typing_in_progress(self) {
@@ -262,6 +268,9 @@ impl Session {
/// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview).
pub fn preview(&mut self, cmd: &str, params: &Value) -> Result<Value> {
if self.script_running() {
return Err(EngineError::Busy);
}
let (paint, restore_paint) = {
let menu = self.menu.clone();
let st = self.doc_mut()?;
+18 -3
View File
@@ -39,6 +39,14 @@ impl Session {
/// Execute a command by id. This is THE entry point for every frontend.
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?;
// A clipboard import is a query that replaces the clipboard, which the end of a run sets too.
if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) {
return Err(EngineError::Busy);
}
// A step of a batch a script runs is held to the same rule as the script's own commands.
if self.script_in_run && crate::script::refused_to_scripts(id) {
return Err(EngineError::Other(crate::script::refused_text(id)));
}
// An edit the active tool is computing on another thread (a Shape Builder merge) is
// applied before a command that may edit, select, save or give a document a new revision,
// as the click came first. Queries that only read do not wait for it.
@@ -302,8 +310,13 @@ impl Session {
/// document goes back to how it was before the command (its art, selection, interaction and
/// undo history), and the same document stays active, instead of crashing the frontend.
pub(crate) fn run_guarded(&mut self, id: &str, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
let snapshot: Vec<_> =
self.docs.iter().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.interaction.clone(), d.history.clone())).collect();
// In a script's run a panic ends the run, and the run's rollback puts the histories back.
let in_run = self.script_in_run;
let snapshot: Vec<_> = self
.docs
.iter()
.map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.interaction.clone(), (!in_run).then(|| d.history.clone())))
.collect();
let active = self.active().map(|d| d.uid);
let r = match guard::catch_panic(|| self.run_nested(f)) {
Ok(r) => r,
@@ -316,7 +329,9 @@ impl Session {
st.doc = doc;
st.selection = selection;
st.interaction = interaction;
st.history = history;
if let Some(history) = history {
st.history = history;
}
cmd::globaledit::follow_history(st);
st.drop_stale_variables_highlight();
st.revision += 1;
+1
View File
@@ -149,6 +149,7 @@ mod repeat_edit;
mod save;
mod saveoptions;
mod scalestrokes;
mod script_run;
mod scripts;
mod select_ids_first;
mod shaper;
+20
View File
@@ -147,6 +147,26 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() {
assert!(s.link_scan.is_none());
}
#[test]
fn a_change_during_a_script_waits_for_the_script_to_end() {
let dir = Folder::new("watch-script");
let path = dir.file("art.png");
std::fs::write(&path, png(40, 40, RED)).unwrap();
let mut s = session();
s.prefs.update_links = "automatically".into();
let id = place(&mut s, &path);
look(&mut s);
save(&path, &png(40, 40, BLUE));
s.start_link_scan();
s.wait_link_scan();
s.script_frames = true;
s.execute("script.run", &json!({"source": "while (true) {}"})).unwrap();
assert!(s.poll_link_scan().is_none(), "the finished look waits");
assert!(s.script_abandon());
assert_eq!(s.poll_link_scan().expect("the stamps are applied").unwrap()["updated"], json!([id.0]));
assert_eq!(colour(&s), BLUE);
}
#[test]
fn a_change_during_a_drag_waits_for_the_drag_to_end() {
let dir = Folder::new("watch-drag");
+999
View File
@@ -0,0 +1,999 @@
//! `script.run` and `script.stop`: one transaction per run, the rollback after a throw, a limit, a
//! stop or a panic, the mutation lease between slices, ids, growth and what a run reports.
use std::cell::Cell;
use serde_json::{Value, json};
use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_RESULT_BYTES};
use crate::*;
fn rect(x: i64) -> Value {
json!({"x": x, "y": 0, "width": 10, "height": 10})
}
/// Two open documents, each with one rectangle, the second one active.
fn two_docs() -> Session {
let mut s = Session::new();
for x in [0, 50] {
s.execute("file.new", &json!({})).unwrap();
s.execute("shape.rectangle", &rect(x)).unwrap();
}
s
}
/// What a rollback has to put back.
fn state(s: &Session) -> Value {
let docs: Vec<Value> = s
.documents()
.iter()
.map(|d| {
json!({
"uid": d.uid,
"art": format!("{:?}", d.doc.layers),
"selection": d.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>(),
"undo": d.history.undo.iter().map(|e| e.label.clone()).collect::<Vec<_>>(),
"redo": d.history.redo.len(),
"path": d.path,
"dirty": d.is_dirty(),
})
})
.collect();
json!({"docs": docs, "active": s.active().map(|d| d.uid), "journal": s.journal.len(), "paint": format!("{:?}", s.paint)})
}
fn run(s: &mut Session, source: &str) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
fn objects(s: &Session, doc: usize) -> usize {
s.documents()[doc].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum()
}
/// A framed run of `source`, one slice in.
fn paused(s: &mut Session, source: &str) {
s.script_frames = true;
assert_eq!(run(s, source).unwrap()["running"], true);
assert!(s.script_pump().is_none());
assert!(s.script_running());
}
fn two_rect_script() -> String {
"vc.run('shape.rectangle', {x:100,y:0,width:5,height:5});\
vc.run('shape.rectangle', {x:110,y:0,width:5,height:5});\
vc.run('document.activate', {index:0});\
vc.run('shape.rectangle', {x:120,y:0,width:5,height:5});\
vc.run('document.activate', {index:1});"
.to_string()
}
#[test]
fn a_run_is_one_undo_step_in_each_document_it_changed() {
let mut s = two_docs();
let before = state(&s);
let r = run(&mut s, &two_rect_script()).unwrap();
assert_eq!(r["ok"], true);
assert_eq!((objects(&s, 0), objects(&s, 1)), (2, 3));
assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script");
assert_eq!(s.documents()[1].history.undo.last().unwrap().label, "Run Script");
assert_eq!(s.documents()[1].history.undo.len(), before["docs"][1]["undo"].as_array().unwrap().len() + 1);
let after = format!("{:?}", s.documents()[1].doc.layers);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(objects(&s, 1), 1);
assert_eq!(format!("{:?}", s.documents()[1].doc.layers), before["docs"][1]["art"].as_str().unwrap());
assert_eq!(s.documents()[1].selection.objects.len(), before["docs"][1]["selection"].as_array().unwrap().len());
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(format!("{:?}", s.documents()[1].doc.layers), after);
}
#[test]
fn a_run_that_changes_nothing_leaves_no_step_no_mark_and_no_journal_entry() {
for source in ["", "var a = 1 + 2;", "vc.log(vc.document); vc.commands.length;"] {
let mut s = two_docs();
s.execute("document.save", &json!({"path": std::env::temp_dir().join(format!("vc-noop-{}.svg", std::process::id())).to_string_lossy()}))
.unwrap();
let before = state(&s);
let revisions = |s: &Session| s.documents().iter().map(|d| d.revision).collect::<Vec<_>>();
let revisions_before = revisions(&s);
let r = run(&mut s, source).unwrap();
assert_eq!(r["changed"], json!([]), "{source}");
assert_eq!(state(&s), before, "{source}");
assert_eq!(revisions(&s), revisions_before, "{source}");
}
}
#[test]
fn a_caught_command_failure_leaves_nothing_behind_and_the_script_goes_on() {
let mut s = two_docs();
let source = "var m = '';\
try { vc.run('command.batch', {commands: [\
{command:'shape.rectangle', params:{x:1,y:1,width:1,height:1}},\
{command:'no.such', params:{}}]}); } catch (e) { m = e.message; }\
try { vc.run('shape.rectangle', {x:'bad'}); } catch (e) { m += '|' + e.name; }\
vc.log(m); vc.run('shape.rectangle', {x:200,y:0,width:5,height:5});";
let r = run(&mut s, source).unwrap();
assert_eq!(objects(&s, 1), 2, "{r}");
assert!(r["log"][0].as_str().unwrap().contains("|Error"), "{r}");
}
#[test]
fn a_failure_puts_back_every_document_and_the_session() {
enum How {
Throw,
Fuel,
Stop,
Panic,
}
for how in [How::Throw, How::Fuel, How::Stop, How::Panic] {
let mut s = two_docs();
let before = state(&s);
let edits = two_rect_script();
let r = match how {
How::Throw => run(&mut s, &format!("{edits} throw new Error('boom');")),
How::Fuel => s.execute("script.run", &json!({"source": format!("{edits} while (true) {{}}"), "maxFuel": 2_000_000})),
How::Stop => {
paused(&mut s, &format!("{edits} while (true) {{}}"));
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
s.script_pump().unwrap()
}
How::Panic => {
paused(&mut s, &format!("{edits} while (true) {{}}"));
PANIC_IN_SLICE.with(|p| p.set(true));
let r = s.script_pump().unwrap();
PANIC_IN_SLICE.with(|p| p.set(false));
r
}
};
assert!(r.is_err());
assert_eq!(state(&s), before);
assert!(!s.script_running());
s.script_frames = false;
assert_eq!(run(&mut s, "1").unwrap()["ok"], true, "a later run starts");
}
}
#[test]
fn a_stop_with_no_run_reports_it() {
assert_eq!(Session::new().execute("script.stop", &json!({})).unwrap()["stopped"], false);
}
#[test]
fn an_error_names_the_script_its_place_and_kind() {
let mut s = two_docs();
let e = run(&mut s, "var a;\n throw new TypeError('no');").unwrap_err().to_string();
assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)");
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_eq!(s.script_report().unwrap()["line"], 1);
}
#[test]
fn bad_parameters_are_refused_before_anything_runs() {
let mut s = two_docs();
let before = state(&s);
let mut deep = json!(1);
for _ in 0..100 {
deep = json!([deep]);
}
for p in [
json!({}),
json!({"source": "1", "args": {"a": deep}}),
json!({"path": "a", "source": "b"}),
json!({"path": ""}),
json!({"path": 1}),
json!({"source": "1", "nope": 1}),
json!({"source": "1", "args": []}),
json!({"source": "1", "args": {"a": "x".repeat(1 << 20)}}),
json!({"source": "1", "answers": {"a": 1}}),
json!({"source": "1", "answers": 1}),
json!({"source": "1", "maxFuel": 0}),
json!({"source": "1", "maxFuel": -1}),
json!({"source": "1", "maxFuel": 1.5}),
json!({"source": "1", "maxFuel": "9"}),
json!({"source": "1", "maxFuel": 100_000_000_001u64}),
] {
assert!(matches!(s.execute("script.run", &p), Err(EngineError::BadParams { .. })), "{p}");
}
assert_eq!(state(&s), before);
}
#[test]
fn files_are_checked_before_they_are_read() {
let dir = std::env::temp_dir().join(format!("vc-script-run-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let write = |name: &str, bytes: &[u8]| {
let p = dir.join(name);
std::fs::write(&p, bytes).unwrap();
p.to_string_lossy().into_owned()
};
let mut s = two_docs();
let path = |p: &str| json!({"path": p});
let ok = write("Bézier (1) & co.js", b"\xef\xbb\xbfvc.log(1);\r\nvc.log(2);\r\n");
let r = s.execute("script.run", &path(&ok)).unwrap();
assert_eq!((r["log"].clone(), r["name"].as_str()), (json!([1, 2]), Some("Bézier (1) & co.js")));
let invalid = write("a.js", b"var a = '\xff';");
assert!(s.execute("script.run", &path(&invalid)).unwrap_err().to_string().contains("UTF-8"));
let huge = write("huge.js", &vec![b' '; script::MAX_SOURCE_BYTES + 1]);
assert!(s.execute("script.run", &path(&huge)).unwrap_err().to_string().contains("too large"));
let compiled = write("b.jsxbin", b"@JSXBIN@ES@2.0@");
assert!(s.execute("script.run", &path(&compiled)).unwrap_err().to_string().contains("compiled"));
let renamed = write("c.js", b"@JSXBIN@ES@2.0@");
assert!(s.execute("script.run", &path(&renamed)).unwrap_err().to_string().contains("compiled"));
assert!(s.execute("script.run", &path(&dir.to_string_lossy())).is_err());
let huge_source = " ".repeat(script::MAX_SOURCE_BYTES + 1);
assert!(run(&mut s, &huge_source).unwrap_err().to_string().contains("too large"));
let other = write("notes.txt", b"vc.log(1);");
assert!(matches!(s.execute("script.run", &path(&other)), Err(EngineError::BadParams { .. })), "a text file that is not a script");
let upper = write("UP.JSX", b"vc.log(3);");
assert_eq!(s.execute("script.run", &path(&upper)).unwrap()["log"], json!([3]));
std::fs::create_dir_all(dir.join("folder.js")).unwrap();
assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() {
let path = std::env::temp_dir().join(format!("vc-script-batch-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let p = path.to_string_lossy().into_owned();
let mut s = two_docs();
let source = format!(
"try {{ vc.run('command.batch', {{commands: [\
{{command: 'view.guides.lock', params: {{locked: true}}}},\
{{command: 'document.export', params: {{path: {p:?}, format: 'svg'}}}},\
{{command: 'no.such', params: {{}}}}]}}); }} catch (e) {{ vc.log(e.name); }}"
);
let r = run(&mut s, &source).unwrap();
assert_eq!(r["log"], json!(["Error"]), "{r}");
assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay");
assert!(path.exists());
assert_eq!(r["written"], json!([p]), "{r}");
let _ = std::fs::remove_file(&path);
}
#[test]
fn an_export_that_fails_names_no_file() {
let path = std::env::temp_dir().join(format!("vc-script-no-folder-{}", std::process::id())).join("out.svg");
let p = path.to_string_lossy().into_owned();
let mut s = two_docs();
let source = format!("try {{ vc.run('document.export', {{path: {p:?}, format: 'svg'}}); }} catch (e) {{ vc.log(e.name); }}");
let r = run(&mut s, &source).unwrap();
assert_eq!(r["log"], json!(["Error"]), "{r}");
assert!(!path.exists());
assert_eq!(r["written"], json!([]), "{r}");
}
#[test]
fn a_failed_run_puts_back_the_choices_its_commands_made() {
let mut s = two_docs();
let before = s.global_edit_options.clone();
let source = "vc.run('select.globalEditOptions', {appearance: !vc.run('select.globalEditOptions', {}).appearance}); throw new Error('x');";
assert!(run(&mut s, source).is_err());
assert_eq!(s.global_edit_options, before);
let source = "try { vc.run('command.batch', {commands: [\
{command: 'select.globalEditOptions', params: {size: true}},\
{command: 'no.such', params: {}}]}); } catch (e) {}";
run(&mut s, source).unwrap();
assert_eq!(s.global_edit_options, before, "the failed command's choice went back");
assert!(!s.caps_lock);
assert!(run(&mut s, "vc.run('view.capsLock', {on: true}); throw new Error('x');").is_err());
assert!(!s.caps_lock, "the Caps Lock state went back");
run(&mut s, "vc.run('view.capsLock', {on: true});").unwrap();
assert!(s.caps_lock, "a finished run keeps it");
}
#[test]
fn a_failed_run_puts_back_the_preferences_its_commands_changed() {
let mut s = two_docs();
let basic = s.prefs.new_art_basic;
assert!(run(&mut s, &format!("vc.run('appearance.setNewArtBasic', {{on: {}}}); throw new Error('x');", !basic)).is_err());
assert_eq!(s.prefs.new_art_basic, basic);
}
#[test]
fn a_finished_run_keeps_its_preferences_and_the_ones_the_app_changed_meanwhile() {
let mut s = two_docs();
let (basic, increment) = (s.prefs.new_art_basic, s.prefs.keyboard_increment);
paused(&mut s, &format!("vc.run('appearance.setNewArtBasic', {{on: {}}}); for (var i = 0; i < 2000000; i++) {{}}", !basic));
assert_eq!(s.prefs.new_art_basic, basic, "between slices the app sees the preferences before the run");
s.prefs.keyboard_increment = increment + 1.0;
s.execute("view.capsLock", &json!({"on": true})).unwrap();
while s.script_pump().is_none() {}
assert_eq!((s.prefs.new_art_basic, s.prefs.keyboard_increment), (!basic, increment + 1.0));
assert!(s.caps_lock, "the Caps Lock state the app reported during the run stays");
}
#[test]
fn a_script_cannot_load_the_place_cursor() {
let mut s = two_docs();
let e = run(&mut s, "vc.run('file.place.queue', {paths: []});").unwrap_err().to_string();
assert!(e.contains("a script cannot run `file.place.queue`"), "{e}");
let listed = run(&mut s, "vc.log(vc.commands.some(function (c) { return c.id === 'file.place.queue'; }));").unwrap();
assert_eq!(listed["log"], json!([false]), "{listed}");
}
#[test]
fn a_command_whose_result_cannot_cross_is_put_back() {
TEST_RESULT_BYTES.with(|b| b.set(Some(1)));
let mut s = two_docs();
let r = run(&mut s, "try { vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); } catch (e) { vc.log(e.name); }");
TEST_RESULT_BYTES.with(|b| b.set(None));
let r = r.unwrap();
assert_eq!(r["log"], json!(["RangeError"]), "{r}");
assert_eq!(r["changed"], json!([]), "{r}");
assert_eq!((objects(&s, 0), objects(&s, 1)), (1, 1));
}
#[test]
fn an_abandoned_run_reports_the_files_it_wrote() {
let path = std::env::temp_dir().join(format!("vc-script-abandon-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let p = path.to_string_lossy().into_owned();
let mut s = two_docs();
paused(&mut s, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"));
assert!(path.exists(), "the first slice exported");
assert!(s.script_abandon());
let report = s.script_report().unwrap();
assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}");
assert!(s.script_failure_text().unwrap().contains(&p));
let _ = std::fs::remove_file(&path);
}
#[test]
fn a_run_that_only_closes_a_document_keeps_its_journal_entry() {
let mut s = two_docs();
let journal = s.journal.len();
let r = run(&mut s, "vc.run('file.close', {index: 1});").unwrap();
assert_eq!(r["changed"], json!([]), "{r}");
assert_eq!(s.documents().len(), 1);
assert_eq!(s.journal.len(), journal + 1);
assert_eq!(s.journal.iter().last().unwrap().0, "file.close");
}
#[test]
fn a_command_that_can_fail_after_copying_has_the_clipboard_put_back() {
let mut s = two_docs();
let keep_clipboard = |s: &mut Session, id: &str| {
let save = script::Savepoint::take(s, id);
s.clipboard.source_artboard = Some(Default::default());
save.restore(s);
};
keep_clipboard(&mut s, "edit.cut");
assert_eq!(s.clipboard.source_artboard, None, "put back");
s.clipboard.source_artboard = Some(Default::default());
keep_clipboard(&mut s, "shape.rectangle");
assert!(s.clipboard.source_artboard.is_some(), "only those commands pay for a copy of the clipboard");
}
#[test]
fn a_commands_savepoint_copies_the_same_number_of_undo_steps_however_long_the_runs_history() {
let copied = |n: usize| {
let mut s = two_docs();
crate::history::ENTRY_CLONES.with(|c| c.set(0));
let r = run(&mut s, &format!("for (var i = 0; i < {n}; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});")).unwrap();
assert_eq!(r["ok"], true);
assert_eq!(objects(&s, 1), n + 1);
crate::history::ENTRY_CLONES.with(Cell::get)
};
let (few, many) = (copied(20), copied(200));
// Each command copies at most its document's newest step, whatever the history holds.
assert!(many <= 200 + few, "{few} steps copied for 20 commands, {many} for 200");
}
#[test]
fn undo_redo_and_a_long_redo_stack_copy_the_same_number_of_steps_per_command() {
let copied = |n: usize| {
let mut s = two_docs();
crate::history::ENTRY_CLONES.with(|c| c.set(0));
let source = format!(
"for (var i = 0; i < {n}; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});\
for (var i = 0; i < {n}; i++) vc.run('edit.undo');\
for (var i = 0; i < {n}; i++) vc.run('select.none');\
for (var i = 0; i < {n}; i++) vc.run('edit.redo');"
);
let r = run(&mut s, &source).unwrap();
assert_eq!(r["ok"], true, "{r}");
assert_eq!(objects(&s, 1), n + 1);
crate::history::ENTRY_CLONES.with(Cell::get)
};
let (few, many) = (copied(20), copied(200));
// Ten times the commands copy about ten times the steps: each command copies its document's
// newest undo and redo steps, whatever the stacks hold.
assert!(many <= 12 * few, "{few} steps copied for 80 commands, {many} for 800");
}
#[test]
fn a_failed_command_gives_back_the_redo_steps_and_an_undo_it_made() {
let mut s = two_docs();
for x in 1..=3 {
s.execute("shape.rectangle", &rect(x)).unwrap();
}
for _ in 0..2 {
s.execute("edit.undo", &json!({})).unwrap();
}
let before = state(&s);
let save = script::Savepoint::take(&mut s, "shape.rectangle");
s.execute("shape.rectangle", &rect(9)).unwrap();
assert_eq!(s.documents()[1].history.redo.len(), 0);
assert!(save.restore(&mut s), "the redo steps the new step cleared are put back");
assert_eq!(state(&s), before);
let save = script::Savepoint::take(&mut s, "edit.undo");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert!(save.restore(&mut s));
assert_eq!(state(&s), before);
for _ in 0..2 {
s.execute("edit.redo", &json!({})).unwrap();
}
assert_eq!(objects(&s, 1), 4);
}
#[test]
fn a_failed_command_at_the_history_limit_keeps_the_oldest_step() {
let mut s = two_docs();
s.docs[1].history.limit = 5;
let before = state(&s);
for x in 1..=5 {
s.execute("shape.rectangle", &rect(x)).unwrap();
}
let save = script::Savepoint::take(&mut s, "shape.rectangle");
s.execute("shape.rectangle", &rect(9)).unwrap();
assert!(save.restore(&mut s), "the step the limit would have let go is put back");
assert_eq!(objects(&s, 1), 6);
for _ in 0..5 {
s.execute("edit.undo", &json!({})).unwrap();
}
assert_eq!(state(&s)["docs"][1]["art"], before["docs"][1]["art"]);
}
#[test]
fn a_snapshot_too_large_to_cross_throws_instead_of_reading_as_no_document() {
let mut s = two_docs();
s.docs[1].path = Some("x".repeat(17 << 20));
let r = run(&mut s, "var m = ''; try { vc.document; m = 'read'; } catch (e) { m = e.name + ': ' + e.message; } vc.log(m);").unwrap();
let m = r["log"][0].as_str().unwrap();
assert!(m.starts_with("RangeError: vc.document.") && m.ends_with("is too large for a script"), "{m}");
}
#[test]
fn recovery_copies_made_between_slices_hold_the_art_before_the_run() {
let store = std::sync::Arc::new(cmd::recovery::MemoryStore::default());
let mut s = two_docs();
s.recovery.set_store(store.clone());
paused(&mut s, &format!("{} while (true) {{}}", two_rect_script()));
cmd::recovery::save_copies(&mut s).unwrap();
s.script_abandon();
drop(s);
let mut s = Session::new();
s.recovery.set_store(store);
let r = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(r["restored"].as_array().map(Vec::len), Some(2), "{r}");
assert_eq!((objects(&s, 0), objects(&s, 1)), (1, 1), "the copies hold the art from before the run");
}
#[test]
fn values_that_cannot_cross_are_named_and_shared_ones_can() {
let mut s = two_docs();
let cases = [
("var a = {}; a.a = a; vc.run('shape.rectangle', a);", "RangeError|TypeError"),
("var a = {}, c = a; for (var i = 0; i < 100; i++) { c.n = {}; c = c.n; } vc.run('shape.rectangle', a);", "RangeError|TypeError"),
("vc.run('shape.rectangle', {x: 1/0});", "RangeError|TypeError"),
("vc.run('shape.rectangle', {x: function () {}});", "RangeError|TypeError"),
("vc.run('shape.rectangle', 7);", "TypeError"),
("vc.run(7);", "TypeError"),
];
for (source, kinds) in cases {
let e = run(&mut s, source).unwrap_err().to_string();
assert!(kinds.split('|').any(|k| e.contains(k)), "{source}: {e}");
}
let r = run(&mut s, "var p = {w: 5}; vc.log({a: p, b: p}); var l = ''; for (var i = 0; i < 20; i++) l += 'xxxxxxxxxx'; vc.log(l);").unwrap();
assert_eq!(r["log"][0], json!({"a": {"w": 5}, "b": {"w": 5}}));
assert_eq!(r["log"][1].as_str().unwrap().len(), 200);
}
#[test]
fn commands_outside_the_documents_are_refused_in_a_batch_too() {
let mut s = two_docs();
for source in [
"vc.run('prefs.set', {key: 'a', value: 1});",
"vc.run('script.run', {source: '1'});",
"vc.run('script.stop');",
"vc.run('edit.undoGroup.begin', {});",
"vc.run('view.proofColors', {on: true});",
"vc.run('view.proofSetup', {});",
"vc.run('view.overprintPreview', {on: true});",
"vc.run('view.separationsPreview', {});",
"vc.run('command.batch', {commands: [{command: 'prefs.reset', params: {}}]});",
] {
let e = run(&mut s, source).unwrap_err().to_string();
assert!(e.contains("cannot run"), "{source}: {e}");
}
let r = run(&mut s, "var c = vc.commands; var n = 0; for (var i = 0; i < c.length; i++) if (c[i].id.indexOf('prefs.') === 0) n++; vc.log(n); vc.log(c.length > 100);").unwrap();
assert_eq!(r["log"], json!([0, true]));
}
#[test]
fn a_script_cannot_clear_the_undo_steps_from_before_its_run() {
let mut s = two_docs();
let steps = s.documents()[1].history.undo.len();
let source = "vc.run('shape.rectangle', {x:9,y:9,width:1,height:1});\
var m = ''; try { vc.run('edit.clearHistory'); } catch (e) { m = e.message; } vc.log(m);";
let r = run(&mut s, source).unwrap();
assert_eq!(r["log"], json!(["a script cannot run `edit.clearHistory`"]), "{r}");
assert_eq!(s.documents()[1].history.undo.len(), steps + 1);
}
#[test]
fn the_vc_object_reads_the_active_document_and_cannot_be_changed() {
let mut s = two_docs();
let r = s
.execute(
"script.run",
&json!({"name": "x", "args": {"n": 2}, "source": "vc.args.n = 9; vc.api.version = 'x'; vc.log(vc.args.n); vc.log(vc.api.version); vc.log(vc.api.has('run')); vc.log(vc.api.has('nope')); vc.log(vc.document.artboards); vc.log(typeof vc.document.path);"}),
)
.unwrap();
assert_eq!(r["log"], json!([2, "1.0", true, false, 1, "object"]));
let mut empty = Session::new();
assert_eq!(run(&mut empty, "vc.log(vc.document === null);").unwrap()["log"], json!([true]));
assert!(run(&mut empty, "vc.run('shape.rectangle', {x:0,y:0,width:1,height:1});").unwrap_err().to_string().contains("Error"));
}
#[test]
fn the_log_is_bounded_and_a_script_can_catch_that() {
let mut s = two_docs();
let r = run(
&mut s,
"var n = 0; try { while (true) { vc.log(n); n++; } } catch (e) { vc.run('document.inspect', {}); throw new Error(e.name + ' at ' + n); }",
);
let e = r.unwrap_err().to_string();
assert!(e.contains(&format!("RangeError at {}", script::MAX_LOG_LINES)), "{e}");
}
#[test]
fn between_slices_every_change_is_refused_and_readers_see_the_committed_art() {
let mut s = two_docs();
let before = state(&s);
paused(&mut s, &format!("{} while (true) {{}}", two_rect_script()));
assert_eq!(state(&s), before);
for (id, p) in [
("shape.rectangle", rect(1)),
("clipboard.importSvg", json!({})),
("clipboard.importImage", json!({})),
("clipboard.importText", json!({})),
("clipboard.importPdf", json!({})),
("clipboard.importEmf", json!({})),
("clipboard.importEps", json!({})),
("edit.undo", json!({})),
("file.new", json!({})),
("file.close", json!({})),
("file.revert", json!({})),
("file.recovery.restore", json!({})),
("action.batch", json!({})),
("command.batch", json!({"commands": []})),
("effect.apply", json!({})),
("script.run", json!({"source": "1"})),
] {
assert!(matches!(s.execute(id, &p), Err(EngineError::Busy)), "{id}");
}
assert!(matches!(s.begin_interaction("x"), Err(EngineError::Busy)));
assert!(matches!(s.edit("x", |_, _| Ok(())), Err(EngineError::Busy)));
assert!(matches!(s.preview("shape.rectangle", &rect(1)), Err(EngineError::Busy)));
let press = tools::PointerEvent {
kind: tools::PointerKind::Down,
..serde_json::from_value(json!({"kind": "move", "pos": {"x": 0.0, "y": 0.0}})).unwrap()
};
assert!(matches!(s.pointer(&press, ViewInfo::default()), Err(EngineError::Busy)));
let inspected = s.execute("document.inspect", &json!({})).unwrap();
assert_eq!(inspected["layers"][0]["children"].as_array().map(Vec::len), Some(1), "{inspected}");
assert_eq!(state(&s), before, "the refused commands changed nothing");
s.script_abandon();
assert_eq!(state(&s), before);
assert!(s.execute("shape.rectangle", &rect(1)).unwrap()["id"].is_u64());
}
#[test]
fn a_document_closed_or_opened_in_a_run_follows_the_run() {
let closing = "vc.run('file.close', {index: 0}); vc.run('file.new', {}); vc.run('shape.rectangle', {x:1,y:1,width:1,height:1});";
let mut s = two_docs();
let before = state(&s);
assert!(run(&mut s, &format!("{closing} throw new Error('x');")).is_err());
assert_eq!(state(&s), before);
let first = s.documents()[0].uid;
run(&mut s, closing).unwrap();
assert_eq!(s.documents().len(), 2);
assert!(s.documents().iter().all(|d| d.uid != first));
assert_eq!(s.documents()[1].history.undo.len(), 0, "a document the script made starts with no undo steps");
}
#[test]
fn undo_in_a_run_reaches_only_the_runs_own_steps_and_old_ids_stay_dead() {
let mut s = two_docs();
let history = s.documents()[1].history.undo.len();
let source = "var p = vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}).id;\
vc.run('edit.undo');\
var q = vc.run('shape.rectangle', {x:2,y:2,width:1,height:1}).id;\
var why = '';\
try { vc.run('edit.clear', {ids: [p]}); } catch (e) { why = e.message; }\
vc.run('edit.undo');\
try { vc.run('edit.undo'); why += '|undid a step from before the run'; } catch (e) { why += '|stopped'; }\
vc.log({same: p === q, why: why});\
vc.run('shape.rectangle', {x:3,y:3,width:1,height:1});";
let r = run(&mut s, source).unwrap();
assert_eq!(r["log"][0]["same"], false, "{r}");
let why = r["log"][0]["why"].as_str().unwrap();
assert!(why.ends_with("|stopped") && why.len() > "|stopped".len(), "{why}");
assert_eq!(objects(&s, 1), 2);
assert_eq!(s.documents()[1].history.undo.len(), history + 1);
}
#[test]
fn a_string_over_the_crossing_limit_does_not_cross() {
let limits = vectorcraft_js::DataLimits { bytes: 20, ..vectorcraft_js::DataLimits::default() };
assert!(script::to_data(&json!("four"), &limits, 0, &mut (0, 0)).is_ok());
assert_eq!(script::to_data(&json!("fives"), &limits, 0, &mut (0, 0)), Err(String::new()));
}
#[test]
fn a_result_too_large_to_cross_names_its_place() {
let limits = vectorcraft_js::DataLimits { bytes: 90, ..vectorcraft_js::DataLimits::default() };
let v = json!({"a": [1, {"name": "x".repeat(40)}]});
assert_eq!(script::to_data(&v, &limits, 0, &mut (0, 0)), Err(".a[1].name".to_string()));
}
#[test]
fn ids_given_out_in_an_abandoned_run_are_not_given_out_again() {
let mut s = two_docs();
let before = s.active().unwrap().doc.peek_next_id();
paused(&mut s, &format!("{} while (true) {{}}", two_rect_script()));
assert!(s.script_abandon());
assert!(s.active().unwrap().doc.peek_next_id() > before);
}
#[test]
fn ids_given_out_in_a_failed_run_are_not_given_out_again() {
let mut s = two_docs();
let e =
run(&mut s, "var p = vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}).id; throw new Error('id=' + p + ';');").unwrap_err().to_string();
let used: u64 = e.split("id=").nth(1).unwrap().split(';').next().unwrap().parse().unwrap();
let dirty = s.documents()[1].is_dirty();
let id = s.execute("shape.rectangle", &rect(3)).unwrap()["id"].as_u64().unwrap();
assert!(id > used, "{id} after {used}");
assert!(dirty);
}
#[test]
fn a_rollback_keeps_the_history_after_an_undo_in_the_run() {
let mut s = two_docs();
let before = state(&s);
let source = "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); vc.run('edit.undo'); throw new Error('x');";
assert!(run(&mut s, source).is_err());
assert_eq!(state(&s), before);
}
#[test]
fn a_batch_joins_the_runs_one_step() {
let mut s = two_docs();
let undo = s.documents()[1].history.undo.len();
let source = "vc.run('command.batch', {commands: [\
{command:'shape.rectangle', params:{x:1,y:1,width:1,height:1}},\
{command:'shape.rectangle', params:{x:2,y:2,width:1,height:1}}]});";
run(&mut s, source).unwrap();
assert_eq!(s.documents()[1].history.undo.len(), undo + 1);
assert_eq!(objects(&s, 1), 3);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(objects(&s, 1), 1);
}
#[test]
fn a_run_with_nobody_to_ask_ends_at_its_growth_allowance() {
TEST_GROWTH.with(|g| g.set(Some(20)));
let mut s = two_docs();
let before = state(&s);
let source = "try { while (true) vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); } catch (e) { vc.run('shape.rectangle', {x:2,y:1,width:1,height:1}); }";
let e = run(&mut s, source).unwrap_err().to_string();
TEST_GROWTH.with(|g| g.set(None));
assert!(e.contains("objects and data"), "{e}");
assert_eq!(state(&s), before);
}
#[test]
fn a_document_a_run_opens_counts_toward_its_growth_allowance() {
TEST_GROWTH.with(|g| g.set(Some(20)));
let rects: String = (0..30).map(|i| format!(r#"<rect x="{i}" y="0" width="1" height="1"/>"#)).collect();
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">{rects}</svg>"#);
let data = vectorcraft_format::base64_encode(svg.as_bytes());
let mut s = two_docs();
let before = state(&s);
let source = format!("try {{ vc.run('document.open', {{name: 'a.svg', dataBase64: '{data}'}}); }} catch (e) {{}}");
let e = run(&mut s, &source).unwrap_err().to_string();
assert!(e.contains("objects and data"), "{e}");
assert_eq!(state(&s), before);
// A document whose art is all in a symbol counts it too.
let mut maker = Session::new();
maker.execute("file.new", &json!({})).unwrap();
for x in 0..30 {
maker.execute("shape.rectangle", &rect(x)).unwrap();
}
maker.execute("select.all", &json!({})).unwrap();
let instance = maker.execute("symbol.new", &json!({"name": "Many"})).unwrap()["id"].as_u64().unwrap();
maker.execute("edit.clear", &json!({"ids": [instance]})).unwrap();
assert_eq!(objects(&maker, 0), 0);
let data = maker.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string();
let source = format!("vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}});");
let e = run(&mut s, &source).unwrap_err().to_string();
TEST_GROWTH.with(|g| g.set(None));
assert!(e.contains("objects and data"), "{e}");
assert_eq!(state(&s), before);
}
#[test]
fn graph_design_art_counts_toward_the_growth_allowance() {
TEST_GROWTH.with(|g| g.set(Some(20)));
let mut s = two_docs();
for x in 0..30 {
s.execute("shape.rectangle", &rect(x)).unwrap();
}
let before = state(&s);
let designs = |s: &Session| s.documents().iter().map(|d| d.doc.graph_designs.len()).collect::<Vec<_>>();
let designs_before = designs(&s);
// A design saved from the selection in an open document.
let e = run(&mut s, "vc.run('select.all'); vc.run('graph.design', {new: 'Many'});").unwrap_err().to_string();
assert!(e.contains("objects and data"), "{e}");
assert_eq!(state(&s), before);
assert_eq!(designs(&s), designs_before);
// A document a run opens whose art is all in a graph design.
let mut maker = Session::new();
maker.execute("file.new", &json!({})).unwrap();
let ids: Vec<u64> = (0..30).map(|x| maker.execute("shape.rectangle", &rect(x)).unwrap()["id"].as_u64().unwrap()).collect();
maker.execute("select.all", &json!({})).unwrap();
maker.execute("graph.design", &json!({"new": "Many"})).unwrap();
maker.execute("edit.clear", &json!({"ids": ids})).unwrap();
assert_eq!(objects(&maker, 0), 0);
assert_eq!(maker.documents()[0].doc.graph_designs[0].art.count_with_masks(), 31);
let data = maker.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string();
let source = format!("vc.run('document.open', {{name: 'g.vectorcraft', dataBase64: '{data}'}});");
let e = run(&mut s, &source).unwrap_err().to_string();
TEST_GROWTH.with(|g| g.set(None));
assert!(e.contains("objects and data"), "{e}");
assert_eq!(state(&s), before);
}
/// Drops `v` one level at a time.
fn drop_flat(v: Value) {
let mut stack = vec![v];
while let Some(mut v) = stack.pop() {
match &mut v {
Value::Object(o) => stack.extend(std::mem::take(o).into_iter().map(|(_, x)| x)),
Value::Array(a) => stack.append(a),
_ => {}
}
}
}
#[test]
fn args_nested_ten_thousand_deep_in_a_script_throw_a_range_error_with_their_place() {
let mut s = two_docs();
let before = state(&s);
let source = "var v = 1; for (var i = 0; i < 10000; i++) v = {a: v}; var m = 'none'; \
try { vc.run('script.run', {source: '', args: v}); } catch (e) { m = e.name + '|' + e.message; } vc.log(m);";
let r = run(&mut s, source).unwrap();
let m = r["log"][0].as_str().unwrap_or_default();
assert!(m.starts_with("RangeError|") && m.contains(".args.a.a.a") && m.contains("nested too deep"), "{r}");
assert_eq!(state(&s), before);
}
#[test]
fn args_nested_ten_thousand_deep_from_a_caller_are_refused_with_their_place() {
let mut s = two_docs();
let before = state(&s);
// Built by moving each level in: `json!` would copy the value through `to_value`, one call per level.
let wrap = |key: &str, v: Value| Value::Object(std::iter::once((key.to_string(), v)).collect());
let mut deep = json!(1);
for _ in 0..10_000 {
deep = wrap("a", deep);
}
let mut params = wrap("args", wrap("b", deep));
params["source"] = json!("");
let e = s.execute("script.run", &params).unwrap_err().to_string();
drop_flat(params);
assert!(e.contains("`args.b.a.a.a") && e.contains("nested more than 64 levels deep"), "{e}");
assert_eq!(state(&s), before);
}
#[test]
fn a_person_can_let_a_growing_run_go_on_or_stop_it() {
TEST_GROWTH.with(|g| g.set(Some(20)));
let run_to_the_question = |s: &mut Session| {
s.script_frames = true;
run(s, "for (var i = 0; i < 25; i++) vc.run('shape.rectangle', {x:i,y:1,width:1,height:1});").unwrap();
let slices = Cell::new(0);
while !s.script_waiting() {
assert!(s.script_pump().is_none());
slices.set(slices.get() + 1);
assert!(slices.get() < 1_000);
}
// Waiting takes no fuel, however often the frame comes round.
assert!(s.script_pump().is_none());
};
let mut s = two_docs();
run_to_the_question(&mut s);
s.script_continue();
assert!(!s.script_waiting());
let done = loop {
if let Some(r) = s.script_pump() {
break r;
}
};
assert_eq!(done.unwrap()["ok"], true);
assert_eq!(objects(&s, 1), 26);
let mut s = two_docs();
let before = state(&s);
run_to_the_question(&mut s);
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
assert!(!s.script_waiting());
assert!(s.script_pump().unwrap().is_err());
TEST_GROWTH.with(|g| g.set(None));
assert_eq!(state(&s), before);
}
#[test]
fn a_file_saved_before_a_failure_stays_written_and_is_named() {
let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let p = path.to_string_lossy().into_owned();
let mut s = two_docs();
let before = state(&s);
let source =
format!("vc.run('file.saveAs', {{path: {p:?}}}); vc.run('shape.rectangle', {{x:1,y:1,width:1,height:1}}); throw new Error('later');");
let e = run(&mut s, &source).unwrap_err().to_string();
assert!(path.exists());
assert!(e.contains(&p), "{e}");
assert_eq!(s.script_report().unwrap()["written"], json!([p]));
assert_eq!(state(&s), before, "the document does not keep the new path");
let _ = std::fs::remove_file(&path);
}
#[test]
fn a_committed_run_exports_what_it_drew() {
let path = std::env::temp_dir().join(format!("vc-script-export-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let p = path.to_string_lossy().into_owned();
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let source = "for (var i = 0; i < 7; i++) vc.run('shape.rectangle', {x:i*20,y:5,width:10,height:10});";
run(&mut s, source).unwrap();
s.execute("document.save", &json!({"path": p})).unwrap();
let svg = std::fs::read_to_string(&path).unwrap();
assert_eq!(svg.matches("<rect").count() + svg.matches("<path").count(), 7, "{svg}");
let inspected = s.execute("document.inspect", &json!({})).unwrap();
assert_eq!(inspected["layers"][0]["children"].as_array().map(Vec::len), Some(7));
let _ = std::fs::remove_file(&path);
}
#[test]
fn a_run_needing_a_recovery_copy_it_cannot_write_does_not_start() {
let mut s = two_docs();
s.script_copy_first = true;
let before = state(&s);
let e = run(&mut s, "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1});").unwrap_err().to_string();
assert!(e.contains("recovery copy"), "{e}");
assert_eq!(state(&s), before);
assert!(!s.script_running());
}
#[test]
fn a_run_does_not_start_while_a_complex_document_goes_without_a_copy() {
let store = std::sync::Arc::new(cmd::recovery::MemoryStore::default());
let mut s = Session::new();
s.recovery.set_store(store);
s.script_copy_first = true;
let mut d = vectorcraft_doc::Document::new(1000.0, 1000.0);
let layer = d.layers[0].id;
for i in 0..cmd::recovery::COMPLEX_OBJECTS {
let id = d.alloc_id();
let r = vectorcraft_geom::Rect::new((i % 200) as f64, (i / 200) as f64, (i % 200) as f64 + 1.0, (i / 200) as f64 + 1.0);
let n = vectorcraft_doc::Node::path(id, vectorcraft_geom::shapes::rectangle(r), vectorcraft_doc::Appearance::default_art());
d.insert(Some(layer), i, n).unwrap();
}
s.add_document(d, None);
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
s.prefs.recovery_off_for_complex = true;
let e = run(&mut s, "1").unwrap_err().to_string();
assert!(e.contains("recovery copy"), "{e}");
assert!(!s.script_running());
s.prefs.recovery_off_for_complex = false;
assert_eq!(run(&mut s, "1").unwrap()["ok"], true);
}
#[test]
fn an_open_undo_group_stops_a_run_from_starting() {
let mut s = two_docs();
s.execute("edit.undoGroup.begin", &json!({})).unwrap();
assert!(run(&mut s, "1").unwrap_err().to_string().contains("undo group"));
s.execute("edit.undoGroup.end", &json!({})).unwrap();
assert_eq!(run(&mut s, "1").unwrap()["ok"], true);
}
#[test]
fn a_cancel_from_the_caller_stops_a_headless_run() {
let mut s = two_docs();
let before = state(&s);
let stop = s.script_interrupt();
stop.set();
assert!(s.execute("script.run", &json!({"source": "1", "maxFuel": 10_000})).is_ok(), "a run clears a flag left from before");
assert!(!stop.is_set());
assert_eq!(state(&s), before);
}
/// Script text: pieces that change documents, throw or loop, mixed with arbitrary text.
fn source_text() -> impl proptest::strategy::Strategy<Value = String> {
use proptest::prelude::*;
let piece = prop_oneof![
Just("vc.run('shape.rectangle', {x:1,y:1,width:5,height:5});".to_string()),
Just("vc.run('select.all'); vc.run('edit.clear');".to_string()),
Just("vc.run('file.new', {});".to_string()),
Just("vc.run('document.activate', {index:0});".to_string()),
Just("vc.run('no.such');".to_string()),
Just("vc.log(vc.document);".to_string()),
Just("throw new Error('x');".to_string()),
Just("vc.run('shape.rectangle', {x:2,y:2,width:5,height:5}); throw new Error('y');".to_string()),
Just("while (true) {}".to_string()),
Just("var o = {}; o.o = o; vc.run('shape.rectangle', o);".to_string()),
Just("{".to_string()),
Just("try {".to_string()),
Just("} catch (e) {}".to_string()),
"[ -~]{0,30}",
"\\PC{0,10}",
];
proptest::collection::vec(piece, 0..12).prop_map(|p| p.concat())
}
/// Every field of each open document but its next id, and the rest of what a rollback puts back.
/// A failed run raises the next id past the ids it gave out, which [`next_ids`] reads.
fn saved(s: &Session) -> (Value, Vec<String>) {
let docs = s
.documents()
.iter()
.map(|d| {
let mut doc = (*d.doc).clone();
doc.raise_next_id(1 << 50);
format!("{doc:?}")
})
.collect();
(state(s), docs)
}
fn next_ids(s: &Session) -> Vec<u64> {
s.documents().iter().map(|d| d.doc.peek_next_id()).collect()
}
proptest::proptest! {
#![proptest_config(proptest::prelude::ProptestConfig::with_cases(48))]
/// Any script text ends with a report or a script error, and a run that fails leaves every
/// document as it was.
#[test]
fn any_source_ends_with_a_report_or_a_script_error(source in source_text()) {
let mut s = two_docs();
let (before, ids) = (saved(&s), next_ids(&s));
match s.execute("script.run", &json!({"source": source, "maxFuel": 200_000})) {
Ok(r) => proptest::prop_assert_eq!(&r["ok"], &json!(true), "{}", r),
Err(e) => {
proptest::prop_assert!(matches!(e, EngineError::Other(_)), "{:?}", e);
let kind = s.script_report.as_ref().map(|r| r["kind"].clone());
proptest::prop_assert!(kind.as_ref().is_some_and(|k| k != "internal"), "{:?}: {}", kind, e);
proptest::prop_assert_eq!(saved(&s), before);
proptest::prop_assert!(next_ids(&s).iter().zip(&ids).all(|(after, was)| after >= was), "{:?} after {:?}", next_ids(&s), ids);
}
}
}
}
+13 -2
View File
@@ -38,10 +38,11 @@ fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
#[test]
fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() {
let mut s = Session::new();
let mut s = session();
let list = run(&mut s, "graphicStyle.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
assert!(libs.len() >= 6 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}");
assert!(libs.len() >= 7 && libs.iter().all(|l| l["category"] == "builtIn"), "{libs:?}");
assert!(libs.iter().any(|l| l["id"] == "game-hud" && l["name"] == "Game HUD"), "{libs:?}");
for l in libs {
let id = l["id"].as_str().unwrap();
let g = run(&mut s, "graphicStyle.library", json!({"library": id}));
@@ -56,6 +57,16 @@ 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 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")));
let node = doc(&s).node(id).unwrap();
assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex("#3498db").unwrap()));
assert_eq!(node.appearance.stroke_paint(), Paint::None);
assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["stylize.outerGlow"]);
// 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());
+31 -1
View File
@@ -84,12 +84,16 @@ 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(), 2, "{libs:?}");
assert_eq!(libs.len(), 3, "{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()),
(Some("ui-frames"), Some("UI Frames"), Some("builtIn"))
);
assert_eq!(
(libs[2]["id"].as_str(), libs[2]["name"].as_str(), libs[2]["category"].as_str()),
(Some("map-markers"), Some("Map Markers"), 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"]);
@@ -125,6 +129,32 @@ fn ui_frames_symbols_carry_default_nine_slice_when_added() {
));
}
#[test]
fn map_markers_symbols_add_without_nine_slice() {
let mut s = session();
let lib = run(&mut s, "symbol.library", json!({"library": "map-markers"}));
let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Pin", "Flag", "Crosshair", "Checkpoint"]);
let mut placed = Vec::new();
for (i, name) in names.iter().enumerate() {
let r = run(
&mut s,
"symbol.addFromLibrary",
json!({"library": "map-markers", "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 == "Pin"
));
}
#[test]
fn a_saved_library_reopens_and_its_symbols_join_another_document_in_one_step() {
let dir = folder("user");
+15
View File
@@ -456,6 +456,9 @@ impl Session {
/// applied, in order ([`Session::tool_poll`]); moves of the pointer with no button held go to
/// the tool at once.
pub fn pointer(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<Vec<UiRequest>> {
if self.script_running() {
return if ev.kind == PointerKind::Move { Ok(vec![]) } else { Err(EngineError::Busy) };
}
let n = self.next_input();
if ev.kind != PointerKind::Move && (!self.held_input.is_empty() || self.tool_edit_pending()) {
self.held_input.push_back((n, HeldInput::Pointer(*ev), view));
@@ -878,6 +881,9 @@ impl Session {
/// A key for the active tool. While the tool computes an edit on another thread, the key is held
/// and made once the edit is applied, after the input held before it.
pub fn tool_key(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> Result<Vec<UiRequest>> {
if self.script_running() {
return Err(EngineError::Busy);
}
let n = self.next_input();
if self.tool_editing() {
self.held_input.push_back((n, HeldInput::Key(key, mods), view));
@@ -911,6 +917,9 @@ impl Session {
/// Typed text for the active tool (Type tool).
pub fn tool_text(&mut self, text: &str, view: ViewInfo) -> Result<Vec<UiRequest>> {
if self.script_running() {
return Err(EngineError::Busy);
}
let acts = self.with_tool_cx(view, |t, cx| t.text_input(cx, text));
self.take_tool_panic()?;
self.apply_actions(acts)
@@ -1060,6 +1069,12 @@ impl Session {
self.plane_key(key).is_some() || self.with_tool_cx(view, |t, cx| t.claims_key(cx, key))
}
/// Has the active tool started something that Escape ends while no button is pressed (see
/// `Tool::ends_on_escape`)?
pub fn tool_ends_on_escape(&mut self, view: ViewInfo) -> bool {
self.with_tool_cx(view, |t, cx| t.ends_on_escape(cx))
}
pub fn overlays(&mut self, view: ViewInfo) -> Vec<Overlay> {
// The Blend tool's first pick is not marked after an edit that dropped it.
self.tell_tool_history_moved();
+2
View File
@@ -37,6 +37,8 @@ use crate::ps;
pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
#[cfg(test)]
pub(crate) use envelope::MAX_CHECKED;
#[cfg(test)]
pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN;
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
pub(crate) use frames::text_frames;
pub use obj::{NameEncoding, Names};
+8 -5
View File
@@ -35,12 +35,15 @@ use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, LayerColor, Node,
use vectorcraft_geom::PathData;
use super::obj::Obj;
use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour};
use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour, differ_on_black};
/// The plugin that writes envelopes.
pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use
/// The note for an envelope that keeps its drawn art.
pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art";
/// The note for an envelope of type, which keeps its drawn art with its type hidden (unless the
/// text document gives the type nothing, which a note of its own then says).
pub(crate) const TYPE_DRAWN: &str = "type in an envelope comes in as the envelope's drawn art, not as editable type";
/// The note for warped type that keeps its drawn art, before how many.
pub(crate) const WARPED_TYPE_DRAWN: &str = "warped text objects that came in as drawn art, not as editable type";
/// The most envelopes waiting for their drawn art at once.
@@ -325,9 +328,9 @@ fn alone(node: &Node, layer: NodeId, shared: &Shared<'_>) -> Document {
}
/// How `live` and `drawn`, drawn over `region` at `scale`, differ: the pixels that differ in
/// lightness or colour, those whose neighbours all differ too (where one draws something the other
/// doesn't, not an edge drawn a little apart), and the pixels either inks. `None` when they can't
/// be drawn.
/// lightness or colour, seen on white or on black (each is drawn on its own: white art shows only on
/// black), those whose neighbours all differ too (where one draws something the other doesn't, not
/// an edge drawn a little apart), and the pixels either inks. `None` when they can't be drawn.
fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Option<(usize, usize, usize)> {
let x = vectorcraft_render::Renderer::new().render_region(live, region, scale, false);
let y = vectorcraft_render::Renderer::new().render_region(drawn, region, scale, false);
@@ -336,7 +339,7 @@ fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Opt
}
let (w, h) = (x.width as usize, x.height as usize);
let (xs, ys) = (x.pixels.as_chunks::<4>().0, y.pixels.as_chunks::<4>().0);
let differs: Vec<bool> = xs.iter().zip(ys).map(|(p, q)| differ(p, q) || differ_in_colour(p, q)).collect();
let differs: Vec<bool> = xs.iter().zip(ys).map(|(p, q)| differ(p, q) || differ_in_colour(p, q) || differ_on_black(p, q)).collect();
let inked = xs.iter().zip(ys).filter(|(p, q)| p[3] > 8 || q[3] > 8).count();
let at = |i: usize, j: usize| differs.get(j * w + i).copied().unwrap_or(false);
let any = differs.iter().filter(|d| **d).count();
@@ -519,6 +519,7 @@ impl<'a> Reader<'a> {
// An envelope of type keeps its drawn art and its type, hidden, as above: the
// type is filled in after reading, which the envelope can't wait for.
if typed {
self.warn(crate::import::ai::envelope::TYPE_DRAWN);
return Ok(());
}
if self.envelopes.len() >= crate::import::ai::envelope::MAX_PENDING {
+47
View File
@@ -7826,6 +7826,23 @@ fn an_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() {
assert_eq!(r.warnings, [super::envelope::DRAWN]);
}
/// The same, in white: white art seen on white looks like nothing, so the check sees it on black
/// too, and a white envelope that draws elsewhere keeps its drawn art.
#[test]
fn a_white_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() {
use vectorcraft_doc::live::EnvelopeKind;
const WHITE: &str = "0 0 0 0 1 1 1 Xa\n";
let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true };
let content = envelope_content().replace(RED, WHITE);
let drawn = drawn_content(&other).replace(RED, WHITE);
let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &content, 1, &drawn);
let r = read_ok(&layer(&body));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{a:#?}");
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}");
assert_eq!(r.warnings, [super::envelope::DRAWN]);
}
/// A document of `n` warped text objects, with the art the live warp makes of each, in its look.
fn warped_type_doc(n: usize) -> (Document, Vec<super::envelope::WarpedLook>) {
use vectorcraft_doc::{Appearance, Effect, TextObject};
@@ -7871,6 +7888,36 @@ fn warped_type_past_the_budget_comes_in_as_its_look() {
assert_eq!(kept.extras().wrap, Some(wrap));
}
/// White warped type is checked as other type is: seen on white it looks like nothing, so the check
/// sees it on black too. Type whose live warp draws as its look stays type; type whose look is
/// warped the other way comes in as its look.
#[test]
fn white_warped_type_that_draws_elsewhere_comes_in_as_its_look() {
use vectorcraft_doc::{Appearance, CharStyle, Effect, TextObject};
let warp = |bend: f64| {
let mut appearance = Appearance::default();
appearance.effects.push(Effect { id: "warp.arc".into(), params: serde_json::json!({"bend": bend}), visible: true });
appearance
};
for (look_bend, replaced) in [(40.0, 0), (-40.0, 1)] {
let mut doc = Document::new(400.0, 200.0);
let mut layer = Node::layer(doc.alloc_id(), "Art", vectorcraft_doc::LayerColor::Preset(0));
let white = CharStyle { fill: Paint::solid(Color::WHITE), ..Default::default() };
let t = TextObject::point(kurbo::Point::new(20.0, 60.0), "TILT", white);
let mut text = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
text.appearance = warp(40.0).into();
let mut other = text.clone();
other.appearance = warp(look_bend).into();
let mut look = vectorcraft_effects::expand_outlined(None, &other, None).unwrap();
look.id = doc.alloc_id();
let looks = vec![super::envelope::WarpedLook { slot: text.id, look, left_out: None }];
layer.children_mut().unwrap().push(Arc::new(text));
doc.layers = vec![Arc::new(layer)];
let warped = super::envelope::WarpedType { looks, checks: 1, ..Default::default() };
assert_eq!(warped.settle(&mut doc, Some, &Default::default(), &mut vec![]), replaced, "look bent {look_bend}");
}
}
/// The budget for warped type is what the envelopes left: their checks and the page's share they
/// spent, with the page they are held to.
#[test]
+9
View File
@@ -56,6 +56,15 @@ pub(in crate::import) fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool {
lightness(p).abs_diff(lightness(q)) > SAME_PIXEL || (a.min(b) <= WHITE && a.abs_diff(b) > SAME_PIXEL)
}
/// Do two pixels look different seen on black: in lightness? An object drawn on its own and seen
/// only on white hides what it draws in white (white type over nothing looks like nothing): seen
/// on black too, that shows.
pub(in crate::import) fn differ_on_black(p: &[u8; 4], q: &[u8; 4]) -> bool {
// Premultiplied, a pixel is what it shows on black.
let on_black = |p: &[u8; 4]| [0, 1, 2].map(|i| u32::from(p[i]));
p != q && lightness(on_black(p)).abs_diff(lightness(on_black(q))) > SAME_PIXEL
}
/// How far apart two pixels' red, green or blue may be for them to be the same colour (a colour
/// and its CMYK equivalent stay within it; a red and a dark red don't).
const SAME_COLOUR: u32 = 64;
+2 -1
View File
@@ -5222,7 +5222,8 @@ fn envelope_options_keep_the_source_text_hidden_under_its_outlined_appearance()
}
});
assert_eq!(texts, [("CHONKYCATS".to_string(), false)], "{:?}", r.warnings);
assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings);
// The notes say the type isn't editable.
assert_eq!(super::tests::program_warnings(&r.warnings), [crate::import::ai::ENVELOPE_TYPE_DRAWN], "{:?}", r.warnings);
}
/// A live envelope that draws a little apart from its drawn art, in layers that already differ
+22 -5
View File
@@ -10,7 +10,8 @@
//! is left as it was and the save fails.
//!
//! On macOS `File::sync_all` is a full flush (`F_FULLFSYNC`), which SMB shares refuse with
//! `ENOTSUP` while a plain `fsync` works: [`sync_file`] falls back to the plain one there (#1620).
//! `ENOTSUP` and virtiofs shares (folders shared into a macOS VM) with `ENOTTY`, while a plain
//! `fsync` works: [`sync_file`] falls back to the plain one there (#1620).
use std::fs::{File, OpenOptions};
use std::io::{self, Write as _};
@@ -180,8 +181,9 @@ fn copy_new(from: &Path, path: &Path) -> io::Result<()> {
}
/// Flush `file` to stable storage (`sync_all`). On Apple platforms that is a full flush
/// (`F_FULLFSYNC`); where the volume refuses it with `ENOTSUP` (SMB shares, #1620) this falls back
/// to a plain `fsync`. Any other error, and a failed `fsync`, is returned as it is.
/// (`F_FULLFSYNC`); where the volume refuses it with `ENOTSUP` (SMB shares) or `ENOTTY` (virtiofs
/// shares, #1620) this falls back to a plain `fsync`. Any other error, and a failed `fsync`, is
/// returned as it is.
pub fn sync_file(file: &File) -> io::Result<()> {
match full_sync(file) {
Err(e) if full_flush_unsupported(&e) => plain_fsync(file),
@@ -190,9 +192,10 @@ pub fn sync_file(file: &File) -> io::Result<()> {
}
/// Whether `e` is a volume refusing a full flush. Never off Apple platforms: there `sync_all` is
/// already a plain `fsync`. Checked by its code because std maps `ENOTSUP` to `Uncategorized`.
/// already a plain `fsync`. Checked by its code because std maps `ENOTSUP` and `ENOTTY` to
/// `Uncategorized`.
fn full_flush_unsupported(e: &io::Error) -> bool {
cfg!(target_vendor = "apple") && e.raw_os_error() == Some(ENOTSUP)
cfg!(target_vendor = "apple") && matches!(e.raw_os_error(), Some(ENOTSUP | ENOTTY))
}
#[cfg(target_vendor = "apple")]
@@ -232,6 +235,9 @@ fn full_sync(file: &File) -> io::Result<()> {
const ENOTSUP: i32 = 45;
#[cfg(not(target_vendor = "apple"))]
const ENOTSUP: i32 = 95;
/// What macOS answers when a virtiofs share (a folder shared into a VM) is asked for a full flush.
/// The same number on every Unix.
const ENOTTY: i32 = 25;
#[cfg(test)]
thread_local! {
@@ -414,6 +420,17 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// A save to a virtiofs share (#1620: a folder shared into a macOS VM): macOS refuses the full
/// flush there with `ENOTTY` (os error 25), which falls back to a plain `fsync` as `ENOTSUP` does.
/// Elsewhere neither is a refused full flush, and other errors never are.
#[test]
fn a_full_flush_refused_with_enotty_falls_back_like_enotsup() {
let apple = cfg!(target_vendor = "apple");
assert_eq!(full_flush_unsupported(&io::Error::from_raw_os_error(25)), apple, "ENOTTY");
assert_eq!(full_flush_unsupported(&io::Error::from_raw_os_error(ENOTSUP)), apple, "ENOTSUP");
assert!(!full_flush_unsupported(&io::Error::other("the connection was lost")));
}
fn denied<T>() -> io::Result<T> {
Err(io::Error::new(io::ErrorKind::PermissionDenied, "refused by the share"))
}
+1 -1
View File
@@ -501,7 +501,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, .. }) => format!("function {name}() {{ [native code] }}"),
Some(Func::Host { name, .. } | Func::Data { 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")),
};
+4
View File
@@ -158,6 +158,9 @@ pub(crate) type NativeFn = fn(&mut crate::interp::Interp, Value, &[Value], bool)
/// A function the embedding defines.
pub(crate) type HostFn = dyn Fn(&[crate::JsValue]) -> Result<crate::JsValue, String>;
/// A function the embedding defines that takes and gives structured values.
pub(crate) type DataFn = crate::host::HostFunction;
/// The built-ins the interpreter treats specially when it calls them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum NativeKind {
@@ -177,6 +180,7 @@ pub(crate) enum Func {
Closure { code: Rc<Code>, env: EnvId },
Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str },
Host { f: Rc<HostFn>, name: Rc<str> },
Data { f: DataFn, name: Rc<str> },
Bound { target: ObjId, this: Value, args: Rc<[Value]> },
}
+351
View File
@@ -0,0 +1,351 @@
//! Structured values between a script and its host: [`Data`] (JSON's shapes and `undefined`), the
//! checks a value passes on its way across, and the frozen objects a host adds to the global
//! environment.
//!
//! A value read from a script may hold plain objects, arrays, strings, finite numbers, booleans,
//! `null` and `undefined`. A cycle, a value too deep or too large, a function, a getter, a date, a
//! regular expression, a boxed primitive, a hole in an array and a number that is not finite are
//! refused with a `TypeError` or `RangeError` naming where the value is. The same object may appear
//! more than once when it is not its own ancestor; each appearance counts against the size limit,
//! so sharing cannot multiply the work without limit.
use std::rc::Rc;
use crate::LimitKind;
use crate::heap::{Class, ENUMERABLE, Func, Key, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes};
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
use crate::value::{Value, index_key};
/// A value that crosses between a script and the host.
#[derive(Clone, Debug, PartialEq)]
pub enum Data {
Undefined,
Null,
Bool(bool),
Number(f64),
String(String),
Array(Vec<Data>),
/// An object's own enumerable properties, in the order the object lists them.
Object(Vec<(String, Data)>),
}
/// How much one crossing may carry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DataLimits {
/// How deeply arrays and objects may nest.
pub depth: usize,
/// Estimated bytes of the strings, names and numbers.
pub bytes: usize,
/// Array elements and object properties, all of them counted together.
pub entries: usize,
}
impl Default for DataLimits {
fn default() -> Self {
Self { depth: 64, bytes: 16 << 20, entries: 1 << 20 }
}
}
/// How a host function fails.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HostError {
/// Thrown to the script as an `Error`; the script can catch it.
Error(String),
/// Thrown to the script as a `TypeError`.
Type(String),
/// Thrown to the script as a `RangeError`.
Range(String),
/// Ends the run with [`LimitKind::Host`] and this message. The script cannot catch it.
Abort(String),
}
/// A function the host gives a script, with its arguments converted.
pub type HostFunction = Rc<dyn Fn(Vec<Data>) -> Result<Data, HostError>>;
/// 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 property whose value the function gives each time it is read.
Getter(HostFunction),
/// A frozen object with these members.
Object(Vec<(String, HostItem)>),
}
enum Step {
Name(Key),
Index(u32),
}
/// A value being read: what it has used so far, and where the reader is.
struct Reading {
limits: DataLimits,
bytes: usize,
entries: usize,
ancestors: Vec<ObjId>,
path: Vec<Step>,
function: Rc<str>,
}
impl Reading {
fn place(&self) -> String {
let mut s = String::new();
for step in &self.path {
match step {
Step::Index(i) => s.push_str(&format!("[{i}]")),
Step::Name(k) => {
s.push('.');
s.push_str(&String::from_utf16_lossy(k));
}
}
}
s
}
}
enum Shape {
Array(u32),
Plain(Vec<(Key, Prop)>),
}
impl Interp {
fn data_error(&mut self, r: &Reading, t: ErrorType, what: &str) -> Abrupt {
let message = format!("{}: argument{} {what}", r.function, r.place());
self.throw(t, &message)
}
fn charge_reading(&mut self, r: &mut Reading, bytes: usize) -> JsResult<()> {
r.bytes = r.bytes.saturating_add(bytes);
if r.bytes > r.limits.bytes {
return Err(self.data_error(r, ErrorType::Range, "is too large"));
}
Ok(())
}
fn charge_entries(&mut self, r: &mut Reading, n: usize) -> JsResult<()> {
r.entries = r.entries.saturating_add(n);
if r.entries > r.limits.entries {
return Err(self.data_error(r, ErrorType::Range, "has too many entries"));
}
Ok(())
}
fn read_data(&mut self, v: &Value, r: &mut Reading) -> JsResult<Data> {
match v {
Value::Undefined => Ok(Data::Undefined),
Value::Null => Ok(Data::Null),
Value::Bool(b) => Ok(Data::Bool(*b)),
Value::Number(n) if n.is_finite() => Ok(Data::Number(*n)),
Value::Number(_) => Err(self.data_error(r, ErrorType::Type, "is not a finite number")),
Value::String(s) => {
self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?;
Ok(Data::String(s.to_rust_string()))
}
Value::Object(id) => self.read_object(*id, r),
}
}
fn read_object(&mut self, id: ObjId, r: &mut Reading) -> JsResult<Data> {
self.use_fuel()?;
if r.ancestors.contains(&id) {
return Err(self.data_error(r, ErrorType::Type, "refers to itself"));
}
if r.ancestors.len() >= r.limits.depth {
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
}
let shape = match &self.object(id)?.class {
Class::Array { length, .. } => Shape::Array(*length),
Class::Ordinary => {
let o = self.object(id)?;
if o.props.len() > r.limits.entries {
return Err(self.data_error(r, ErrorType::Range, "has too many entries"));
}
Shape::Plain(o.props.iter().filter(|(_, p)| p.enumerable()).map(|(k, p)| (k.clone(), p.clone())).collect())
}
other => {
let what = format!("is a {}, not plain data", other.name());
return Err(self.data_error(r, ErrorType::Type, &what));
}
};
r.ancestors.push(id);
let out = match shape {
Shape::Array(length) => self.read_array(id, length, r),
Shape::Plain(props) => self.read_plain(props, r),
};
r.ancestors.pop();
out
}
fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult<Data> {
self.charge_entries(r, length as usize)?;
let mut items = Vec::with_capacity(length as usize);
for i in 0..length {
self.use_fuel()?;
r.path.push(Step::Index(i));
let prop = self.object(id)?.props.get(&index_key(i)).cloned();
let item = match prop {
Some(Prop::Data { value: Value::Undefined, .. }) | None => Err(self.data_error(r, ErrorType::Type, "is undefined")),
Some(Prop::Data { value, .. }) => self.read_data(&value, r),
Some(Prop::Accessor { .. }) => Err(self.data_error(r, ErrorType::Type, "is a getter, not plain data")),
}?;
r.path.pop();
items.push(item);
}
Ok(Data::Array(items))
}
fn read_plain(&mut self, props: Vec<(Key, Prop)>, r: &mut Reading) -> JsResult<Data> {
self.charge_entries(r, props.len())?;
let mut out = Vec::with_capacity(props.len());
for (k, prop) in props {
self.use_fuel()?;
self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?;
let name = String::from_utf16_lossy(&k);
r.path.push(Step::Name(k));
let item = match prop {
// A property holding `undefined` reads as one left out.
Prop::Data { value: Value::Undefined, .. } => None,
Prop::Data { value, .. } => Some(self.read_data(&value, r)?),
Prop::Accessor { .. } => return Err(self.data_error(r, ErrorType::Type, "is a getter, not plain data")),
};
r.path.pop();
if let Some(item) = item {
out.push((name, item));
}
}
Ok(Data::Object(out))
}
/// A host value as a JavaScript value, `frozen` when a script may not change it. A value
/// deeper or longer than the limits throws a `RangeError`.
pub(crate) fn write_data(&mut self, d: Data, depth: usize, frozen: bool) -> JsResult<Value> {
if depth > self.data_limits.depth {
return Err(self.throw(ErrorType::Range, "a host value is nested too deep"));
}
Ok(match d {
Data::Undefined => Value::Undefined,
Data::Null => Value::Null,
Data::Bool(b) => Value::Bool(b),
Data::Number(n) => Value::Number(n),
Data::String(s) => {
let bytes = string_bytes(s.encode_utf16().count());
self.reserve_heap(bytes)?;
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
Value::str(&s)
}
Data::Array(items) => {
self.write_container(items.into_iter().enumerate().map(|(i, d)| (Slot::Index(i), d)).collect(), true, depth, frozen)?
}
Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?,
})
}
fn write_container(&mut self, items: Vec<(Slot, Data)>, array: bool, depth: usize, frozen: bool) -> JsResult<Value> {
if items.len() > self.data_limits.entries {
return Err(self.throw(ErrorType::Range, "a host value has too many entries"));
}
let flags = if frozen { ENUMERABLE } else { crate::heap::OPEN };
self.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(items.len())))?;
let id = if array {
let proto = self.intrinsics.array_proto;
self.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: !frozen }, Some(proto)))
} else {
self.new_object()
};
let mark = self.temp_roots.len();
self.temp_roots.push(Value::Object(id));
let mut result = Ok(());
for (slot, d) in items {
let name = match slot {
Slot::Index(i) => index_key(u32::try_from(i).unwrap_or(u32::MAX)),
Slot::Name(n) => key(&n),
};
result = self.write_data(d, depth + 1, frozen).and_then(|value| self.define(id, name, Prop::Data { value, flags }));
if result.is_err() {
break;
}
}
self.temp_roots.truncate(mark);
result?;
if frozen {
self.object_mut(id)?.extensible = false;
}
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<str>, args: &[Value]) -> JsResult<Value> {
let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() };
let mut data = Vec::with_capacity(args.len());
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)?);
reading.path.pop();
}
match f(data) {
Ok(d) => self.write_data(d, 0, false),
Err(HostError::Abort(message)) => {
self.host_abort = Some(message);
Err(Abrupt::Limit(LimitKind::Host))
}
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)?),
}
}
/// The exception for a host error, charged to the heap.
fn throw_host(&mut self, t: ErrorType, message: &str) -> JsResult<Abrupt> {
let bytes = string_bytes(message.encode_utf16().count());
self.reserve_heap(bytes)?;
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
Ok(self.throw(t, message))
}
/// Adds the frozen object `name` with `items` to the global environment.
pub(crate) fn install_host_object(&mut self, name: &str, items: Vec<(String, HostItem)>) -> JsResult<()> {
let o = self.host_object(name, items)?;
let global = self.global;
self.define(global, key(name), Prop::Data { value: Value::Object(o), flags: 0 })
}
fn host_object(&mut self, path: &str, items: Vec<(String, HostItem)>) -> JsResult<ObjId> {
let o = self.new_object();
let mark = self.temp_roots.len();
self.temp_roots.push(Value::Object(o));
let mut result = Ok(());
for (name, item) in items {
result = self.install_item(o, path, name, item);
if result.is_err() {
break;
}
}
self.temp_roots.truncate(mark);
result?;
self.object_mut(o)?.extensible = false;
Ok(o)
}
fn install_item(&mut self, o: ObjId, path: &str, name: String, item: HostItem) -> JsResult<()> {
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::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE },
};
self.define(o, key(&name), prop)
}
fn host_function(&mut self, f: HostFunction, name: &str) -> ObjId {
let proto = self.intrinsics.function_proto;
self.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into() }), Some(proto)))
}
}
enum Slot {
Index(usize),
Name(String),
}
+288
View File
@@ -0,0 +1,288 @@
//! Resumable runs and the structured values host functions take and give.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use super::*;
fn realm(fuel: u64) -> Realm {
let mut r = Realm::new();
r.set_limits(Limits { fuel, ..Limits::default() });
r
}
/// A realm with `host.take(value)`, which records what it was given and returns it.
fn with_take(r: &mut Realm) -> Rc<RefCell<Vec<Data>>> {
let seen: Rc<RefCell<Vec<Data>>> = Rc::default();
let log = seen.clone();
let f: HostFunction = Rc::new(move |mut args| {
let v = if args.is_empty() { Data::Undefined } else { args.remove(0) };
log.borrow_mut().push(v.clone());
Ok(v)
});
r.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap();
seen
}
fn finish(r: &mut Realm, slice: u64) -> (Result<JsValue, RunError>, u32) {
let mut slices = 0;
loop {
slices += 1;
match r.advance(slice) {
Ok(Progress::Paused) => {}
Ok(Progress::Done(v)) => return (Ok(v), slices),
Err(e) => return (Err(e), slices),
}
}
}
#[test]
fn a_resumed_run_gives_the_result_of_one_run() {
let source = "var t = 0; for (var i = 0; i < 2000; i++) { t += i; } t";
let whole = realm(10_000_000).run(source).unwrap();
let mut r = realm(10_000_000);
r.start(source).unwrap();
assert!(r.is_running());
let (v, slices) = finish(&mut r, 100);
assert_eq!(v.unwrap(), whole);
assert!(slices > 10, "the run paused: {slices} slices");
assert!(!r.is_running());
}
#[test]
fn state_survives_a_pause_and_a_collection_between_slices() {
let mut r = realm(10_000_000);
r.start("var o = {a: [1, 2, 3]}; var n = 0; for (var i = 0; i < 500; i++) { n += o.a.length; } n").unwrap();
assert_eq!(r.advance(50).unwrap(), Progress::Paused);
r.collect_garbage();
assert_eq!(finish(&mut r, 50).0.unwrap(), JsValue::Number(1500.0));
}
#[test]
fn the_fuel_limit_covers_every_slice_together() {
let mut r = realm(5_000);
r.start("while (true) {}").unwrap();
let (v, slices) = finish(&mut r, 100);
assert!(matches!(v, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. })));
assert!((40..=60).contains(&slices), "{slices}");
}
#[test]
fn a_set_flag_stops_a_loop_in_a_getter() {
let mut r = realm(u64::MAX);
r.start("var o = {}; Object.defineProperty(o, 'x', {get: function () { while (true) {} }}); o.x").unwrap();
r.interrupt().set();
let e = r.advance(10).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Interrupted));
}
#[test]
fn a_nested_run_past_the_slice_allowance_is_the_unbroken_limit_and_a_run_with_little_fuel_is_the_fuel_limit() {
for (total, kind) in [(u64::MAX, LimitKind::Unbroken), (1_000, LimitKind::Fuel)] {
for source in [
"var o = {}; Object.defineProperty(o, 'x', {get: function () { while (true) {} }}); o.x",
"[1].forEach(function () { while (true) {} });",
] {
let mut r = realm(total);
r.set_unbroken_fuel(5_000);
r.start(source).unwrap();
let e = finish(&mut r, 1).0.unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(kind), "{source}");
}
}
}
#[test]
fn neither_a_limit_nor_a_stop_can_be_caught() {
let mut r = realm(1_000);
r.start("try { while (true) {} } catch (e) { 'caught' } finally { 'ran' }").unwrap();
assert_eq!(finish(&mut r, 50).0.unwrap_err().kind, RunErrorKind::Limit(LimitKind::Fuel));
let shared = Interrupt::new();
let mut r = realm(1_000_000);
r.share_interrupt(&shared);
r.start("try { while (true) {} } catch (e) { 'caught' }").unwrap();
assert_eq!(r.advance(10).unwrap(), Progress::Paused);
shared.set();
assert_eq!(r.advance(10).unwrap_err().kind, RunErrorKind::Limit(LimitKind::Interrupted));
}
#[test]
fn a_host_function_can_end_the_slice() {
let mut r = realm(1_000_000);
let pause = r.pause_flag();
let f: HostFunction = Rc::new(move |_| {
pause.set(true);
Ok(Data::Null)
});
r.define_host_object("host", vec![("yield".into(), HostItem::Function(f))]).unwrap();
r.start("host.yield(); host.yield(); 7").unwrap();
assert_eq!(r.advance(1_000).unwrap(), Progress::Paused);
assert_eq!(r.advance(1_000).unwrap(), Progress::Paused);
assert_eq!(r.advance(1_000).unwrap(), Progress::Done(JsValue::Number(7.0)));
}
#[test]
fn plain_values_cross_in_both_directions() {
let mut r = realm(1_000_000);
let seen = with_take(&mut r);
let out = r.run("var v = host.take({a: 1, b: 'x', c: [true, null], d: undefined}); v.c[0] === true && v.b === 'x' && v.d === undefined");
assert_eq!(out.unwrap(), JsValue::Bool(true));
let want = Data::Object(vec![
("a".into(), Data::Number(1.0)),
("b".into(), Data::String("x".into())),
("c".into(), Data::Array(vec![Data::Bool(true), Data::Null])),
]);
assert_eq!(seen.borrow().as_slice(), [want]);
}
#[test]
fn a_callback_of_a_built_in_can_call_the_host() {
let mut r = realm(1_000_000);
let seen = with_take(&mut r);
r.start("[1, 2, 3].forEach(function (n) { host.take(n); });").unwrap();
finish(&mut r, 2).0.unwrap();
assert_eq!(seen.borrow().len(), 3);
}
/// `value` passed to the host throws an error of type `name` whose message holds `part`.
fn refused(setup: &str, name: &str, part: &str) {
let mut r = realm(10_000_000);
r.set_data_limits(DataLimits { depth: 8, bytes: 1_000, entries: 100 });
let seen = with_take(&mut r);
let probe = format!("var e; {setup} try {{ host.take(value); }} catch (x) {{ e = x; }} e ? e.name + '|' + e.message : 'none'");
let JsValue::String(out) = r.run(&probe).unwrap() else { panic!("{setup}") };
assert!(out.starts_with(name) && out.contains(part), "{setup}: {out}");
assert!(seen.borrow().is_empty(), "{setup}: the function ran");
}
#[test]
fn values_that_are_not_plain_data_are_refused_with_their_place() {
refused("var value = {}; value.self = value;", "TypeError", ".self refers to itself");
refused("var value = [[1]]; value[0][0] = value;", "TypeError", "[0][0][0] refers to itself");
refused("var value = {f: function () {}};", "TypeError", ".f is a Function");
refused("var value = {n: 1 / 0};", "TypeError", ".n is not a finite number");
refused("var value = {n: 0 / 0};", "TypeError", ".n is not a finite number");
refused("var value = {d: new Date(0)};", "TypeError", ".d is a Date");
refused("var value = {}; Object.defineProperty(value, 'g', {enumerable: true, get: function () { return 1; }});", "TypeError", ".g is a getter");
refused("var value = [1, , 3];", "TypeError", "[0][1] is undefined");
refused("var value = 1; for (var i = 0; i < 20; i++) value = [value];", "RangeError", "nested too deep");
refused("var value = new Array(5000);", "RangeError", "too many entries");
refused("var value = 'x'; for (var i = 0; i < 12; i++) value += value;", "RangeError", "too large");
}
#[test]
fn a_value_nested_ten_thousand_deep_is_refused_with_its_place() {
let mut r = realm(100_000_000);
let seen = with_take(&mut r);
let probe = "var v = 1; for (var i = 0; i < 10000; i++) v = {a: v}; var m = 'none'; \
try { host.take({args: v}); } catch (e) { m = e.name + '|' + e.message; } m";
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
assert!(out.starts_with("RangeError|") && out.contains(".args.a.a.a") && out.contains("nested too deep"), "{out}");
assert!(seen.borrow().is_empty(), "the function ran");
}
#[test]
fn a_shared_object_is_allowed_and_sharing_cannot_multiply_the_work() {
let mut r = realm(10_000_000);
r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 1_000 });
let seen = with_take(&mut r);
r.run("var s = {a: 1}; host.take({x: s, y: s, z: [s, s]});").unwrap();
assert_eq!(seen.borrow().len(), 1);
// Each level doubles the paths to the bottom: the entry limit ends the walk.
let JsValue::String(out) =
r.run("var v = [1]; for (var i = 0; i < 40; i++) v = [v, v]; var m = 'none'; try { host.take(v); } catch (e) { m = e.name; } m").unwrap()
else {
panic!()
};
assert_eq!(out, "RangeError");
}
#[test]
fn a_host_object_cannot_be_changed_by_a_script() {
let mut r = realm(1_000_000);
let args = Data::Object(vec![("list".into(), Data::Array(vec![Data::Number(1.0)]))]);
r.define_host_object("vc", vec![("args".into(), HostItem::Value(args))]).unwrap();
let out = r.run(
"vc.args.list[0] = 2; vc.args.list.push; vc.args.more = 1; vc.extra = 1; var was = vc; vc = 3; \
[was.args.list[0], was.args.more === undefined, was.extra === undefined, Object.isFrozen(was.args.list)].join()",
);
assert_eq!(out.unwrap(), JsValue::String("1,true,true,true".into()));
}
#[test]
fn a_getter_is_read_each_time() {
let mut r = realm(1_000_000);
let count = Rc::new(Cell::new(0.0));
let c = count.clone();
let f: HostFunction = Rc::new(move |_| {
c.set(c.get() + 1.0);
Ok(Data::Number(c.get()))
});
r.define_host_object("host", vec![("n".into(), HostItem::Getter(f))]).unwrap();
assert_eq!(r.run("host.n + host.n").unwrap(), JsValue::Number(3.0));
}
#[test]
fn errors_from_the_host_can_be_caught_and_an_abort_cannot() {
let mut r = realm(1_000_000);
let f: HostFunction = Rc::new(|a| match a.first() {
Some(Data::String(k)) if k == "type" => Err(HostError::Type("bad type".into())),
Some(Data::String(k)) if k == "range" => Err(HostError::Range("bad range".into())),
Some(Data::String(k)) if k == "abort" => Err(HostError::Abort("stopped by the host".into())),
_ => Err(HostError::Error("bad".into())),
});
r.define_host_object("host", vec![("f".into(), HostItem::Function(f))]).unwrap();
let out = r.run(
"var a = []; ['type', 'range', 'x'].forEach(function (k) { try { host.f(k); } catch (e) { a.push(e.name + ':' + e.message); } }); a.join()",
);
assert_eq!(out.unwrap(), JsValue::String("TypeError:bad type,RangeError:bad range,Error:bad".into()));
let e = r.run("try { host.f('abort'); } catch (e) { 'caught' }").unwrap_err();
assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Limit(LimitKind::Host), "stopped by the host"));
}
#[test]
fn an_error_says_where_in_the_source_it_was_raised() {
let mut r = realm(1_000_000);
r.start("var a = 1;\n throw new TypeError('no');").unwrap();
let e = finish(&mut r, 1).0.unwrap_err();
assert_eq!((e.kind, e.line), (RunErrorKind::Thrown, 2));
assert!(e.column >= 3, "{}", e.column);
assert_eq!(e.message, "TypeError: no");
}
#[test]
fn advancing_without_a_run_is_an_error() {
let mut r = realm(1_000);
let e = r.advance(10).unwrap_err();
assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Internal, "no run to advance"));
}
proptest::proptest! {
/// A slice size does not change what a script computes.
#[test]
fn any_slice_size_gives_the_same_result(slice in 1u64..500, n in 0u32..300) {
let source = format!("var a = []; for (var i = 0; i < {n}; i++) a.push(i * 2); a.join().length");
let whole = realm(50_000_000).run(&source).unwrap();
let mut r = realm(50_000_000);
r.start(&source).unwrap();
proptest::prop_assert_eq!(finish(&mut r, slice).0.unwrap(), whole);
}
/// Hostile text for a value never makes the bridge panic.
#[test]
fn hostile_values_end_with_a_value_or_a_script_error(depth in 0usize..120, width in 0usize..6, cycle in proptest::bool::ANY) {
let mut r = realm(5_000_000);
with_take(&mut r);
let mut s = String::from("var v = [];");
for _ in 0..depth {
s.push_str(&format!("v = [v{}];", ",v".repeat(width.min(2))));
}
if cycle {
s.push_str("var c = {}; c.c = c; v = [v, c];");
}
s.push_str("var ok = 'ok'; try { host.take(v); } catch (e) { ok = e.name; } ok");
let JsValue::String(out) = r.run(&s).unwrap() else { panic!() };
proptest::prop_assert!(matches!(out.as_str(), "ok" | "RangeError" | "TypeError"), "{}", out);
}
}
+48 -7
View File
@@ -179,6 +179,12 @@ pub(crate) struct Interp {
pub(crate) date_host: crate::date_builtins::DateHost,
/// The bytes native code holds outside the heap's cells through [`HeldBytes`].
pub(crate) held: Rc<HeldCount>,
/// Set by the host to end the current slice of a resumable run at the next safe point.
pub(crate) pause: Rc<std::cell::Cell<bool>>,
/// The message of the uncatchable error a host function ended the run with.
pub(crate) host_abort: Option<String>,
/// How much a value passed to or from a host function may carry.
pub(crate) data_limits: crate::DataLimits,
}
/// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's
@@ -367,6 +373,9 @@ impl Interp {
install_error: None,
date_host: crate::date_builtins::DateHost::default(),
held: Rc::default(),
pause: Rc::default(),
host_abort: None,
data_limits: crate::DataLimits::default(),
};
crate::builtins::install(&mut interp);
interp.fuel = limits.fuel;
@@ -558,6 +567,28 @@ impl Interp {
}
}
/// Runs the boundary frame on top until it returns (`Some` with its value) or the remaining
/// fuel falls to `pause_at`, or the host asks for a pause (`None`, with the frames left in
/// place for the next call). Only this outermost loop pauses: a nested run has native frames
/// under it and goes on until it returns.
pub(crate) fn execute_slice(&mut self, pause_at: u64) -> JsResult<Option<Value>> {
loop {
match self.step() {
Ok(Some(v)) => return Ok(Some(v)),
Ok(None) => {}
Err(Abrupt::Throw(v)) => self.unwind(v)?,
Err(other) => {
self.note_site();
self.abort_to_boundary();
return Err(other);
}
}
if self.fuel <= pause_at || self.pause.replace(false) {
return Ok(None);
}
}
}
fn step(&mut self) -> JsResult<Option<Value>> {
self.tick()?;
let frame = self.frame_mut()?;
@@ -966,11 +997,11 @@ impl Interp {
// ---- properties ----
fn object(&self, id: ObjId) -> JsResult<&Object> {
pub(crate) fn object(&self, id: ObjId) -> JsResult<&Object> {
self.heap.object(id).ok_or_else(|| Abrupt::Internal("object out of range".into()))
}
fn object_mut(&mut self, id: ObjId) -> JsResult<&mut Object> {
pub(crate) fn object_mut(&mut self, id: ObjId) -> JsResult<&mut Object> {
self.heap.object_mut(id).ok_or_else(|| Abrupt::Internal("object out of range".into()))
}
@@ -1815,6 +1846,11 @@ impl Interp {
self.temp_roots.truncate(mark);
return Ok(Prepared::Done(r?));
}
Func::Data { f, name } => {
// 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)?));
}
Func::Host { f: host, .. } => {
let js_args: Vec<crate::JsValue> = args.iter().map(|v| self.to_js_value(v)).collect();
return match host(&js_args) {
@@ -2135,6 +2171,15 @@ impl Interp {
if is_eval && self.reentry >= self.limits.reentry {
return Err(Abrupt::Limit(LimitKind::Reentry));
}
self.enter_global(code, is_eval)?;
self.reentry += nested;
let r = self.execute();
self.reentry -= nested;
r
}
/// Declares `code`'s variables and functions and pushes its boundary frame, ready to run.
pub(crate) fn enter_global(&mut self, code: Rc<Code>, is_eval: bool) -> JsResult<()> {
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
let (env, global) = (self.global_env, self.global);
let (env, var_env) = if code.strict && is_eval {
@@ -2144,11 +2189,7 @@ impl Interp {
(env, env)
};
self.instantiate_global(&code, var_env, is_eval)?;
self.push_code_frame(code, env, var_env, Value::Object(global), true)?;
self.reentry += nested;
let r = self.execute();
self.reentry -= nested;
r
self.push_code_frame(code, env, var_env, Value::Object(global), true)
}
fn push_code_frame(&mut self, code: Rc<Code>, env: EnvId, var_env: EnvId, this: Value, boundary: bool) -> JsResult<()> {
+5 -1
View File
@@ -47,6 +47,7 @@ mod compiler;
mod date_builtins;
mod error;
mod heap;
mod host;
mod interp;
mod lexer;
mod number;
@@ -65,9 +66,10 @@ pub use ast::{
PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl,
};
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
pub use host::{Data, DataLimits, HostError, HostFunction, HostItem};
pub use lexer::{Goal, Lexer};
pub use number::to_string as number_to_string;
pub use realm::{Interrupt, JsValue, LimitKind, Limits, Realm, RunError, RunErrorKind};
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind};
pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind};
/// How a script is read.
@@ -185,6 +187,8 @@ impl LineTable {
#[cfg(test)]
mod builtins_tests;
#[cfg(test)]
mod host_tests;
#[cfg(test)]
mod interp_tests;
#[cfg(test)]
mod tests;
+122 -8
View File
@@ -51,14 +51,36 @@ pub enum LimitKind {
Reentry,
/// The host set the interrupt flag.
Interrupted,
/// A getter, a callback of a built-in or another nested run spent [`MAX_UNBROKEN_FUEL`]
/// without returning to the point where a resumable run can pause.
Unbroken,
/// A host function ended the run ([`crate::HostError::Abort`]).
Host,
}
/// 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;
/// How far a resumable run got.
#[derive(Clone, Debug, PartialEq)]
pub enum Progress {
/// The slice ended; call [`Realm::advance`] again.
Paused,
/// The script ended, with its completion value.
Done(JsValue),
}
/// A flag the host sets, from any thread, to stop the running script at its next instruction.
/// It stays set until [`Interrupt::clear`].
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub struct Interrupt(Arc<AtomicBool>);
impl Interrupt {
pub fn new() -> Self {
Self::default()
}
pub fn set(&self) {
self.0.store(true, Ordering::Relaxed);
}
@@ -121,6 +143,7 @@ impl From<SyntaxError> for RunError {
/// A global environment with the built-ins, in which scripts run one after another.
pub struct Realm {
interp: Interp,
unbroken_fuel: u64,
}
impl Default for Realm {
@@ -138,7 +161,13 @@ impl Realm {
/// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it
/// counted together.
pub fn with_options(options: Options, limits: Limits) -> Self {
Self { interp: Interp::new(options, limits) }
Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL }
}
/// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default
/// [`MAX_UNBROKEN_FUEL`]).
pub fn set_unbroken_fuel(&mut self, fuel: u64) {
self.unbroken_fuel = fuel;
}
pub fn limits(&self) -> &Limits {
@@ -173,6 +202,13 @@ impl Realm {
/// value of the last expression statement that ran). A realm whose built-ins could not be
/// installed runs nothing and gives an internal error.
pub fn run(&mut self, source: &str) -> Result<JsValue, RunError> {
let code = self.compile(source)?;
let result = self.interp.run_global(code, false);
self.outcome(result)
}
/// Compiles `source` and readies the realm for a run.
fn compile(&mut self, source: &str) -> Result<std::rc::Rc<crate::bytecode::Code>, RunError> {
let interp = &mut self.interp;
if let Some(message) = &interp.install_error {
return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 });
@@ -181,13 +217,18 @@ impl Realm {
interp.source_units = 0;
interp.throw_site = None;
interp.last_thrown = Value::Undefined;
interp.host_abort = None;
let strict = interp.options.strict;
let code = match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) {
Ok(code) => code,
Err(CompileError::Syntax(e)) => return Err(e.into()),
Err(CompileError::Internal(m)) => return Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }),
};
let result = interp.run_global(code, false);
match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) {
Ok(code) => Ok(code),
Err(CompileError::Syntax(e)) => Err(e.into()),
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }),
}
}
/// The end of a run: its completion value or error, with the interpreter's stacks emptied.
fn outcome(&mut self, result: Result<Value, Abrupt>) -> Result<JsValue, RunError> {
let interp = &mut self.interp;
let (line, column) = interp.throw_site.take().map_or((0, 0), |(code, pc)| code.line_column(pc));
interp.stack.clear();
interp.frames.clear();
@@ -200,11 +241,84 @@ impl Realm {
interp.last_thrown = v;
Err(RunError { kind: RunErrorKind::Thrown, message, line, column })
}
Err(Abrupt::Limit(LimitKind::Host)) => {
let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host));
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column })
}
Err(Abrupt::Limit(kind)) => Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column }),
Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column }),
}
}
/// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it.
pub fn start(&mut self, source: &str) -> Result<(), RunError> {
let code = self.compile(source)?;
match self.interp.enter_global(code, false) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one
/// 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.
pub fn advance(&mut self, slice: u64) -> Result<Progress, RunError> {
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 });
}
let total = interp.fuel;
let cap = slice.saturating_add(self.unbroken_fuel).min(total);
interp.fuel = cap;
let r = interp.execute_slice(cap - slice.min(cap));
let used = cap - interp.fuel;
interp.fuel = total - used;
match r {
Ok(None) => Ok(Progress::Paused),
Ok(Some(v)) => self.outcome(Ok(v)).map(Progress::Done),
// The run's own fuel is not used up, so it was the allowance of this slice.
Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(Progress::Done),
Err(e) => self.outcome(Err(e)).map(Progress::Done),
}
}
/// Is a run begun with [`Realm::start`] still going?
pub fn is_running(&self) -> bool {
!self.interp.frames.is_empty()
}
/// The flag a host function sets to end the current slice at the next point it can pause.
pub fn pause_flag(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
self.interp.pause.clone()
}
/// 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();
}
/// Fuel the run has left.
pub fn fuel_left(&self) -> u64 {
self.interp.fuel
}
/// Sets how much a value passed to or from a host function may carry.
pub fn set_data_limits(&mut self, limits: crate::DataLimits) {
self.interp.data_limits = limits;
}
/// Adds the frozen object `name`, with `items`, to the global environment. Scripts cannot add
/// to it, change it or replace it. A heap too small for it ends with the error the realm's
/// next run would give.
pub fn define_host_object(&mut self, name: &str, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> {
match self.interp.install_host_object(name, items) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// 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) {
+7 -2
View File
@@ -28,7 +28,8 @@ const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
const INTERNAL_ERROR: i64 = -32603;
const RESOURCE_NOT_FOUND: i64 = -32002;
/// The engine is running a long call and this request was not run (implementation-defined range).
/// The engine is running a long call or a script and this request was not run
/// (implementation-defined range).
pub(crate) const SERVER_BUSY: i64 = -32003;
/// How long a call runs before a request that would have to wait behind it is refused as busy
@@ -435,7 +436,11 @@ impl Server {
if let Some(arguments) = args.as_object() {
crate::tools::check_tool_arguments(name, arguments).map_err(|e| (INVALID_PARAMS, e))?;
}
Ok(call_tool(self.backend.as_mut(), name, &args).to_value())
let result = call_tool(self.backend.as_mut(), name, &args);
match result.script_busy() {
Some(message) => Err((SERVER_BUSY, message)),
None => Ok(result.to_value()),
}
}
"resources/read" => {
let uri = params.get("uri").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing `uri`".to_string()))?;
+54
View File
@@ -1463,6 +1463,60 @@ fn pointer_gesture_forwards_backquote_on_each_event() {
assert_eq!(rect["bounds"]["x"], 100.0, "{doc}");
}
/// The documented Rotate View calls reach the desktop control methods, preserving document
/// coordinates and modifiers, and a successful null reset remains a successful MCP response.
#[test]
fn rotate_view_calls_forward_to_desktop_control() {
use std::cell::RefCell;
use std::rc::Rc;
struct Recording(Rc<RefCell<Vec<(String, Value)>>>);
impl Backend for Recording {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
self.0.borrow_mut().push((method.into(), params));
Ok(Value::Null)
}
fn has_ui(&self) -> bool {
true
}
fn describe(&self) -> String {
"desktop control contract".into()
}
}
let seen = Rc::new(RefCell::new(Vec::new()));
let mut s = Server::new(Box::new(Recording(seen.clone())));
let selected = call(&mut s, 1, "select_tool", json!({"tool": "rotateView"}));
let turned = call(
&mut s,
2,
"pointer_gesture",
json!({"events": [
{"kind": "down", "x": 300, "y": 150}, {"kind": "drag", "x": 200, "y": 250}, {"kind": "up", "x": 200, "y": 250}
], "mods": {"shift": true}}),
);
let reset = call(&mut s, 3, "command_run", json!({"id": "view.rotateReset", "params": {}}));
for reply in [&selected, &turned, &reset] {
assert_eq!(reply["isError"], false, "{reply}");
}
assert_eq!(text_of(&reset), "null");
assert_eq!(
*seen.borrow(),
vec![
("ui.tool.select".into(), json!({"tool": "rotateView"})),
(
"ui.pointer".into(),
json!({"events": [
{"kind": "down", "x": 300, "y": 150, "space": "doc"},
{"kind": "drag", "x": 200, "y": 250, "space": "doc"},
{"kind": "up", "x": 200, "y": 250, "space": "doc"}
], "mods": {"shift": true}})
),
("engine.execute".into(), json!({"command": "view.rotateReset", "params": {}}))
]
);
}
/// A `backquote` that is not a boolean is an error, and none of the gesture's events runs.
#[test]
fn pointer_gesture_rejects_a_backquote_that_is_not_a_boolean() {
+17
View File
@@ -344,6 +344,23 @@ fn a_cancelled_export_through_the_real_engine_writes_nothing_and_leaves_the_sess
thread.join().unwrap();
}
#[test]
fn a_change_while_a_script_runs_is_refused_as_busy() {
let mut backend = crate::Headless::with_document();
backend.session.script_frames = true;
backend.session.execute("script.run", &json!({"source": "while (true) {}"})).unwrap();
let mut s = Server::new(Box::new(backend));
let call = |id: &str, params: Value| json!({"name": "command_run", "arguments": {"id": id, "params": params}});
let reply = super::rpc(&mut s, 1, "tools/call", call("shape.rectangle", json!({"x": 0, "y": 0, "width": 1, "height": 1})));
assert_eq!(reply["error"]["code"], -32003, "{reply}");
assert!(reply["error"]["message"].as_str().unwrap().contains("a script is running"), "{reply}");
let reply = super::rpc(&mut s, 2, "tools/call", json!({"name": "doc_inspect", "arguments": {}}));
assert_eq!(reply["result"]["isError"], false, "reading the document is not refused: {reply}");
let reply = super::rpc(&mut s, 3, "tools/call", call("no.such", json!({})));
assert_eq!(reply["result"]["isError"], true, "any other failure stays a tool error: {reply}");
assert!(reply.get("error").is_none(), "{reply}");
}
#[test]
fn a_remote_call_stops_waiting_for_the_app_when_cancelled() {
use std::io::BufRead;
+5
View File
@@ -36,4 +36,9 @@ impl ToolResult {
pub fn to_value(&self) -> Value {
json!({"content": self.content, "isError": self.is_error})
}
/// The error's text, when the engine refused the call because a script is running.
pub(crate) fn script_busy(&self) -> Option<String> {
let text = self.content.first()?.get("text")?.as_str()?;
(self.is_error && text.ends_with(vectorcraft_engine::SCRIPT_BUSY)).then(|| text.to_string())
}
}
+6
View File
@@ -52,3 +52,9 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] }
serde_json = { workspace = true }
# `draw_text`, to write test files with live text as other writers do.
krilla = { workspace = true, features = ["simple-text"] }
# An independent raster oracle for gradient placement in PDF forms. These are test-only macOS
# bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer.
[target.'cfg(target_os = "macos")'.dev-dependencies]
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFData"] }
objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGBitmapContext", "CGColorSpace", "CGContext", "CGDataProvider", "CGImage", "CGPDFDocument", "CGPDFPage"] }
+3 -3
View File
@@ -9,12 +9,11 @@ use craft_pdf::write::{self, Metadata};
use krilla::color::separation::{Color as SepColor, SeparationColorant, SeparationSpace};
use krilla::color::{cmyk, luma, rgb};
use krilla::configure::{Archival, PdfVersion};
use krilla::geom::{Path, PathBuilder, Size, Transform};
use krilla::geom::{Path, PathBuilder, Size};
use krilla::image::Image;
use krilla::num::NormalizedF32;
use krilla::page::PageSettings;
use krilla::paint::{Fill, LinearGradient, RadialGradient, SpreadMethod, Stop, Stroke, StrokeDash};
use krilla::surface::Surface;
use krilla::text::{Glyph, GlyphId, KrillaGlyph};
use kurbo::{PathEl, Shape, Vec2};
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
@@ -28,6 +27,7 @@ use crate::forms::Mark;
use crate::lab_spot::{find, rfind};
use crate::marks::PageBoxes;
use crate::output::ColorOut;
use crate::surface::Surface;
use crate::{Compatibility, ExportReport, PdfError, PdfOptions, Standard};
mod entry;
@@ -131,7 +131,7 @@ mod tests {
fn writable_bounds_values_the_transform_and_values_through_it() {
let mut pdf = krilla::Document::new();
let mut page = pdf.start_page_with(PageSettings::new(Size::from_wh(100.0, 100.0).unwrap()));
let mut s = page.surface();
let mut s = Surface::page(page.surface(), 100.0);
let r = Rect::new(0.0, 0.0, 10.0, 10.0);
assert!(writable(&s, Affine::IDENTITY, r));
assert!(!writable(&s, Affine::IDENTITY, Rect::new(-2_147_483_649.0, 0.0, 10.0, 10.0)));
+7 -7
View File
@@ -3,9 +3,11 @@ use vectorcraft_geom::Point;
use super::entry::RgbInCmyk;
use super::{
Affine, Arc, BezPath, BlendMode, Color, Compatibility, Document, Exporter, Fill, FillRule, HashMap, HashSet, Node, NormalizedF32, Path,
PathBuilder, PathEl, Rect, Shape, Standard, Surface, Transform, cmyk, krilla, luma, rgb,
PathBuilder, PathEl, Rect, Shape, Standard, Surface, cmyk, krilla, luma, rgb,
};
pub(super) use crate::surface::xf;
/// How deep inline graphics nest before they are left out.
pub(super) const MAX_INLINE_DEPTH: u32 = 4;
@@ -96,11 +98,6 @@ pub(super) const MAX_GRADIENT_PX: f64 = 4096.0;
/// with overflow checks it panics on -2,147,483,648.
pub(super) const MAX_COORD: f64 = 1e9;
pub(super) fn xf(a: Affine) -> Transform {
let c = a.as_coeffs();
Transform::from_row(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32, c[4] as f32, c[5] as f32)
}
/// The current transform of surface `s` in the content stream it draws into, without that stream's
/// root transform (a page's y flip).
pub(super) fn ctm(s: &Surface) -> Affine {
@@ -203,9 +200,12 @@ pub(super) fn cover(s: &mut Surface, page: Rect, level: u8, opacity: f32) {
/// group of that opacity that, unlike the writer's opacity groups, is not isolated.
/// The cover is white, so a reader that takes every soft mask as a luminosity mask shows the same.
pub(super) fn constant_mask(s: &mut Surface, page: Rect, alpha: f32) -> krilla::mask::Mask {
let transform = s.group_transform();
let mut sb = s.stream_builder();
let mut ms = sb.surface();
let mut ms = Surface::stream(sb.surface());
ms.push_transform(&transform);
cover(&mut ms, page, 255, alpha);
ms.pop();
ms.finish();
krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Alpha)
}
+14 -3
View File
@@ -22,8 +22,10 @@ impl Exporter<'_> {
/// Opacity mask → luminosity soft mask. Outside the art the backdrop is black (clip) or white;
/// invert is a white Difference rect on top (luminance is linear, so luma(1 − c) = 1 − luma(c)).
fn soft_mask(&mut self, s: &mut Surface, m: &vectorcraft_doc::OpacityMask, page: Rect) -> Option<krilla::mask::Mask> {
let transform = s.group_transform();
let mut sb = s.stream_builder();
let mut ms = sb.surface();
let mut ms = Surface::stream(sb.surface());
ms.push_transform(&transform);
// An opaque backdrop when it matters: white outside the art (no clip), or black for the
// inverting Difference pass below to turn white.
if !m.clip || m.invert {
@@ -39,6 +41,8 @@ impl Exporter<'_> {
self.image_left_out = image_left_out.map(|outer| outer || incomplete);
(self.knockout, self.overprint) = (knockout, overprint);
if incomplete {
ms.pop();
ms.finish();
return None;
}
if m.invert {
@@ -46,6 +50,7 @@ impl Exporter<'_> {
cover(&mut ms, page, 255, 1.0);
ms.pop();
}
ms.pop();
ms.finish();
Some(krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity))
}
@@ -96,21 +101,27 @@ impl Exporter<'_> {
s.opacity = 1.0;
s
};
let transform = s.group_transform();
let mut sb = s.stream_builder();
let mut ms = sb.surface();
let mut ms = Surface::stream(sb.surface());
ms.push_transform(&transform);
cover(&mut ms, page, 255, 1.0);
let alpha = {
let transform = ms.group_transform();
let mut ab = ms.stream_builder();
let mut als = ab.surface();
let mut als = Surface::stream(ab.surface());
als.push_transform(&transform);
let overprint = std::mem::take(&mut self.overprint);
self.measured_node(&mut als, &shape, page, false, Some(measured));
self.overprint = overprint;
als.pop();
als.finish();
krilla::mask::Mask::new(ab.finish(), krilla::mask::MaskType::Alpha)
};
ms.push_mask(alpha);
cover(&mut ms, page, 0, 1.0);
ms.pop();
ms.pop();
ms.finish();
krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity)
}
+1 -1
View File
@@ -351,7 +351,7 @@ impl Exporter<'_> {
let cell = Rect::new(0.0, 0.0, pw, ph);
let tiles = def.instances_in(Affine::IDENTITY, cell);
let mut sb = s.stream_builder();
let mut cs = sb.surface();
let mut cs = Surface::stream(sb.surface());
let reaches_out = tiles.iter().any(|t| t.visual_bounds().is_some_and(|b| cell.intersect(b) != b));
let clip = reaches_out.then(|| to_path(&cs, &cell.to_path(0.1))).flatten();
if let Some(c) = &clip {
+2 -2
View File
@@ -2,7 +2,7 @@ use super::entry::RgbInCmyk;
use super::exporter::{constant_mask, cover, to_path, writable, xf};
use super::{
Affine, Arc, Archival, ColorOut, Compatibility, Document, Exporter, HashSet, Image, Metadata, Node, PageSettings, PdfError, PdfVersion, Rect,
Shape, Size, Standard, Vec2, find, krilla, rfind, write,
Shape, Size, Standard, Surface, Vec2, find, krilla, rfind, write,
};
/// A PDF being written, shared by export and print: the file's configuration and metadata, then
@@ -125,7 +125,7 @@ impl Writer {
let size = Size::from_wh(w.max(least) as f32, h.max(least) as f32).ok_or_else(|| PdfError::BadSetting(format!("page size {w} × {h}")))?;
let at = |b: Rect| krilla::geom::Rect::from_ltrb(b.x0 as f32, b.y0 as f32, b.x1 as f32, b.y1 as f32);
let mut page = self.pdf.document_mut().start_page_with(PageSettings::new(size).with_trim_box(at(sheet.trim)).with_bleed_box(at(sheet.bleed)));
let mut s = page.surface();
let mut s = Surface::page(page.surface(), size.height());
let paper = Rect::new(0.0, 0.0, w, h);
if sheet.negative {
cover(&mut s, paper, 255, 1.0);
+10 -2
View File
@@ -13,7 +13,6 @@ use std::io::Read;
use craft_pdf::write::backend as krilla;
use krilla::geom::PathBuilder;
use krilla::graphic::Graphic;
use krilla::surface::Surface;
use std::sync::Arc;
use vectorcraft_doc::{Document, Node, NodeKind};
@@ -21,6 +20,7 @@ use vectorcraft_doc::{Document, Node, NodeKind};
use crate::encrypt::{Lexer, Obj, StreamSpans, Tok, int, stream_spans};
use crate::output::{deflate, text_string};
use crate::patch::{Patch, Xref};
use crate::surface::{Surface, affine};
use crate::{PdfError, PdfSettings, Standard};
/// What a marked form is.
@@ -87,6 +87,9 @@ pub(crate) fn form(s: &mut Surface, mark: Mark, draw: impl FnOnce(&mut Surface))
/// form's drawing space), rounded outwards to whole units: [`finish`] gives the form a box that
/// covers the paper and the art.
pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rect, draw: impl FnOnce(&mut Surface)) {
// The art and its box move into page space together; keeping the old local paper here
// would clip layers on translated artboards or give the importer a spurious clipping group.
let paper = affine(s.group_transform()).transform_rect_bbox(paper);
let corner = |x: f64, y: f64| (x as f32, y as f32);
marked(s, Mark::Layer(i), [corner(paper.x0.floor(), paper.y0.floor()), corner(paper.x1.ceil(), paper.y1.ceil())], draw);
}
@@ -94,8 +97,9 @@ pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rec
/// Draw `draw` as a form of its own, marked `mark`: an empty clip from the mark's first point
/// through `rest`.
fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce(&mut Surface)) {
let transform = s.group_transform();
let mut sb = s.stream_builder();
let mut fs = sb.surface();
let mut fs = Surface::stream(sb.surface());
let (x, y) = mark.at();
let mut pb = PathBuilder::new();
pb.move_to(x, y);
@@ -108,10 +112,14 @@ fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce(
fs.push_clip_path(&p, &krilla::paint::FillRule::NonZero);
fs.pop();
}
fs.push_transform(&transform);
draw(&mut fs);
fs.pop();
fs.finish();
let stream = sb.finish();
s.push_transform(&transform.invert().unwrap_or_default());
s.draw_graphic(Graphic::new(stream, false));
s.pop();
}
// ---------- finishing the written file ----------
+16
View File
@@ -865,6 +865,9 @@ impl<'p> Builder<'p> {
let vx = self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph));
m * kurbo::Point::new(vx, 880.0)
});
// A horizontal line is gathered in visual order and put back in logical order as a whole:
// a ligature's characters (lam-alef, lam-lam-heh) go in visual order too (#6072).
let text = if top.is_none() { visual_glyph_text(text) } else { text };
let place = |line: &mut TextLine| match top {
Some(top) => line.push_upright(&look, at, opacity, Upright { top }, &text),
None => line.push(&look, at, opacity, advance, &text),
@@ -894,3 +897,16 @@ impl<'p> Builder<'p> {
true
}
}
/// The characters of one glyph in the order they are drawn: a PDF names a ligature's characters
/// in logical order (lam then alef for لا), while a horizontal line of type is gathered glyph by
/// glyph in visual order and only then put back in logical order. Right-to-left characters are
/// turned round here so that putting the line back restores them.
fn visual_glyph_text(text: String) -> String {
if text.chars().nth(1).is_none() {
return text;
}
let Some((order, _)) = vectorcraft_text::logical_order(&text) else { return text };
let chars: Vec<char> = text.chars().collect();
order.iter().filter_map(|&i| chars.get(i)).collect()
}
+1
View File
@@ -70,6 +70,7 @@ mod presets;
mod print;
mod settings;
mod streams;
mod surface;
mod syntax;
pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with};
+140
View File
@@ -0,0 +1,140 @@
//! Keep form XObjects in page space. Quartz resolves shading patterns inside a form against the
//! page's initial space, whereas other readers also apply the transform at the form's invocation.
//! Moving that transform inside the form makes both interpretations agree (including gradients
//! in opacity groups, masks, layers and overprinting art), without rasterizing the art.
//!
//! krilla's page surface has an implicit y flip which `ctm()` does not include. Remember that
//! root separately; a form's surface has an identity root. A group still counts as one push/pop
//! for the drawing code, even though moving its transform takes three krilla pushes.
use std::ops::{Deref, DerefMut};
use craft_pdf::write::backend as krilla;
use krilla::blend::BlendMode;
use krilla::geom::{Path, Transform};
use krilla::mask::Mask;
use krilla::num::NormalizedF32;
use krilla::paint::FillRule;
use vectorcraft_geom::Affine;
pub(crate) fn xf(a: Affine) -> Transform {
let c = a.as_coeffs();
Transform::from_row(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32, c[4] as f32, c[5] as f32)
}
pub(crate) fn affine(t: Transform) -> Affine {
Affine::new([t.sx(), t.ky(), t.kx(), t.sy(), t.tx(), t.ty()].map(f64::from))
}
struct Push {
count: usize,
root: Affine,
}
/// A drawing surface whose form groups keep gradients and masks in the same page space.
pub(crate) struct Surface<'a> {
inner: krilla::surface::Surface<'a>,
root: Affine,
pushes: Vec<Push>,
}
impl<'a> Surface<'a> {
/// Wrap a page while recording the writer's implicit Y flip outside its reported CTM.
pub fn page(inner: krilla::surface::Surface<'a>, height: f32) -> Self {
Self { inner, root: Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, height.into()]), pushes: vec![] }
}
/// Wrap a form or pattern stream, which starts without a page's implicit Y flip.
pub fn stream(inner: krilla::surface::Surface<'a>) -> Self {
Self { inner, root: Affine::IDENTITY, pushes: vec![] }
}
/// Current drawing space → page space, for both a form's art and its mask. A singular
/// enclosing transform draws no area: keep that form local rather than trying to invert it.
pub fn group_transform(&self) -> Transform {
let t = xf(self.root * affine(self.inner.ctm()));
if t.invert().is_some() { t } else { Transform::identity() }
}
/// Move the enclosing transform inside a form and record its three pushes as one group.
fn group(&mut self, push: impl FnOnce(&mut krilla::surface::Surface)) {
let t = self.group_transform();
self.inner.push_transform(&t.invert().unwrap_or_default());
push(&mut self.inner);
self.inner.push_transform(&t);
self.pushes.push(Push { count: 3, root: self.root });
self.root = Affine::IDENTITY;
}
/// Apply opacity in page space when it creates a form; full opacity is a plain push.
pub fn push_opacity(&mut self, opacity: NormalizedF32) {
if opacity == NormalizedF32::ONE {
// krilla does not create a form for full opacity.
self.inner.push_opacity(opacity);
self.plain_push();
} else {
self.group(|s| s.push_opacity(opacity));
}
}
pub fn push_isolated(&mut self) {
self.group(|s| s.push_isolated());
}
/// The mask's stream is already in [`Self::group_transform`]'s space, like the group's art.
pub fn push_mask(&mut self, mask: Mask) {
self.group(|s| s.push_mask(mask));
}
fn plain_push(&mut self) {
self.pushes.push(Push { count: 1, root: self.root });
}
pub fn push_transform(&mut self, transform: &Transform) {
self.inner.push_transform(transform);
self.plain_push();
}
pub fn push_clip_path(&mut self, path: &Path, rule: &FillRule) {
self.inner.push_clip_path(path, rule);
self.plain_push();
}
pub fn push_blend_mode(&mut self, mode: BlendMode) {
self.inner.push_blend_mode(mode);
self.plain_push();
}
/// Restore the enclosing coordinate space, undoing every writer push for the last group.
/// An unmatched pop is logged rather than forwarded to the writer's stack.
pub fn pop(&mut self) {
let Some(push) = self.pushes.pop() else {
log::error!("PDF surface pop without a matching push");
return;
};
for _ in 0..push.count {
self.inner.pop();
}
self.root = push.root;
}
pub fn finish(self) {
self.inner.finish();
}
}
// Drawing operations use krilla directly; every push/pop above keeps our coordinate state in
// step. Stream builders are wrapped with `Surface::stream` when their surfaces are created.
impl<'a> Deref for Surface<'a> {
type Target = krilla::surface::Surface<'a>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for Surface<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
+40
View File
@@ -477,3 +477,43 @@ fn hebrew_comes_back_in_logical_order() {
assert_eq!(shown(&t[0]), shown(&original), "{text}");
}
}
/// The text objects a PDF of `text` set in `face` imports as.
fn imported_texts(face: &vectorcraft_text::FontFace, text: &str) -> Vec<String> {
let mut pdf = krilla::Document::new();
let mut page = pdf.start_page_with(PageSettings::from_wh(300.0, 200.0).unwrap());
let mut s = page.surface();
let font = Font::new(face.file_data().to_vec().into(), face.face_index()).unwrap();
s.draw_text(KPoint::from_xy(20.0, 50.0), font, 24.0, text, false, TextDirection::Auto);
s.finish();
page.finish();
let r = import_with_report(&pdf.finish().unwrap(), &ImportOptions::default()).unwrap();
texts(&r.document).iter().map(|t| t.plain_text()).collect()
}
#[test]
fn arabic_ligatures_keep_their_letters_in_order() {
// A lam-alef ligature is one glyph whose text is lam then alef: it must not be turned round
// with the line it sits in (#6072).
let db = vectorcraft_text::FontDb::global();
let preferred = ["DejaVu Sans", "Arial", "Times New Roman", "Noto Sans Arabic", "Noto Naskh Arabic"].map(String::from);
// Whether `face` draws lam-alef as one glyph, the ligature the fix is about.
let ligates = |face: &vectorcraft_text::FontFace| {
let style = vectorcraft_doc::CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), ..Default::default() };
let t = TextObject::point(kurbo::Point::ORIGIN, "لا", style);
vectorcraft_text::layout(db, &t).glyphs.len() == 1
};
// An installed Arabic font with a lam-alef ligature whose glyphs come back as live type.
let Some(face) = preferred
.iter()
.chain(&db.families())
.filter_map(|f| db.face(f, "Regular"))
.filter(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f))
.find(|f| !imported_texts(f, "بب").is_empty())
else {
return; // No such font on this host.
};
for text in ["لا", "بلال", "السلام عليكم", "لا إله إلا الله"] {
assert_eq!(imported_texts(&face, text), [text], "in {}", face.family);
}
}
+215
View File
@@ -0,0 +1,215 @@
//! Gradients in forms must follow the art, including on pages with a nonzero origin. Quartz
//! exposed a failure the import/render round trip did not: it resolved a form's shading pattern
//! in page space, leaving off-centre gradients painted entirely in their last stop's colour.
//! These fixtures are original, generated geometry; no user artwork or external files are used.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::Arc;
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{Appearance, ColorMode, Document, Knockout, Node, OpacityMask};
use vectorcraft_geom::{Affine, Point, Rect, shapes};
use vectorcraft_pdf::{PdfOptions, export, import};
use vectorcraft_testkit::raster::{assert_similar, render_artboard};
#[derive(Clone, Copy, Debug)]
enum Form {
Page,
Opacity,
Isolated,
Nested,
PassThrough,
Mask,
Knockout,
Layer,
Overprint,
}
const FORMS: [Form; 9] =
[Form::Page, Form::Opacity, Form::Isolated, Form::Nested, Form::PassThrough, Form::Mask, Form::Knockout, Form::Layer, Form::Overprint];
fn rect(d: &mut Document, bounds: Rect, paint: Paint) -> Node {
Node::path(d.alloc_id(), shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0))
}
fn group(d: &mut Document, n: Node) -> Node {
Node::group(d.alloc_id(), vec![Arc::new(n)])
}
/// Generate off-centre gradient art in each form type, moving the art and artboard together.
fn fixture(form: Form, kind: GradientKind, mode: ColorMode, origin: Point) -> (Document, PdfOptions) {
let mut d = Document::new_with_mode(120.0, 180.0, mode);
let color = |k| if mode == ColorMode::Cmyk { Color::cmyk(0.0, 0.0, 0.0, k) } else { Color::gray(k) };
let mut gradient = GradientPaint::new(Gradient {
kind,
stops: vec![GradientStop::new(0.0, color(1.0)), GradientStop::new(0.6, color(0.4)), GradientStop::new(1.0, color(0.0))],
..Default::default()
});
let (start, end) = match kind {
GradientKind::Radial => (Point::new(32.0, 35.0), Point::new(60.0, 35.0)),
_ => (Point::new(10.0, 10.0), Point::new(70.0, 70.0)),
};
gradient.geom = Some(GradientGeom { start, end, aspect: 0.8, focal: None });
let mut n = rect(&mut d, Rect::new(10.0, 10.0, 70.0, 70.0), Paint::Gradient(Box::new(gradient)));
let mut opts = PdfOptions::default();
match form {
Form::Page => d.page_isolate = true,
Form::Opacity => n.opacity = 0.6,
Form::Isolated => {
n = group(&mut d, n);
n.isolate = true;
}
Form::Nested => {
n.opacity = 0.75;
n = group(&mut d, n);
n.opacity = 0.8;
}
Form::PassThrough => {
n.blend = BlendMode::Multiply;
n = group(&mut d, n);
n.opacity = 0.6;
}
Form::Mask => {
let mask = rect(&mut d, Rect::new(10.0, 10.0, 44.0, 70.0), Paint::solid(Color::WHITE));
n.extras_mut().mask = Some(Box::new(OpacityMask::new(mask, true)));
}
Form::Knockout => {
let top = rect(&mut d, Rect::new(50.0, 50.0, 80.0, 80.0), Paint::solid(Color::WHITE));
n = Node::group(d.alloc_id(), vec![Arc::new(n), Arc::new(top)]);
n.knockout = Knockout::On;
}
Form::Layer => opts.settings.create_layers = true,
Form::Overprint => n.appearance.fill_mut().unwrap().overprint = true,
}
n.transform(Affine::translate(origin.to_vec2()), false);
d.artboards[0].rect = d.artboards[0].rect + origin.to_vec2();
let layer = d.default_layer().unwrap();
d.insert(Some(layer), 0, n).unwrap();
(d, opts)
}
/// Round trips preserve gradient placement for the form types the importer supports.
#[test]
fn gradients_in_forms_keep_their_position_when_read_back() {
// The importer has a pre-existing mismatch on the knockout's synthesized nested masks;
// Quartz below checks its actual PDF output, along with the other forms.
for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Knockout)) {
for kind in [GradientKind::Linear, GradientKind::Radial] {
for origin in [Point::ORIGIN, Point::new(125.0, -80.0)] {
let (d, opts) = fixture(form, kind, ColorMode::Rgb, origin);
let back = import(&export(&d, &opts).unwrap()).unwrap();
assert_similar(&render_artboard(&back), &render_artboard(&d), 5.0, 0.01);
}
}
}
}
/// Layer form bounds stay page-sized after translation, without extra imported clipping groups.
#[test]
fn translated_layer_forms_cover_the_paper_in_their_new_space() {
// The layer-box repair added upstream must move with the gradient fix's form transform.
// A local-space paper box would otherwise introduce a clipping group on import.
for origin in [Point::ORIGIN, Point::new(125.0, -80.0), Point::new(-250.0, 450.0)] {
let (d, mut opts) = fixture(Form::Layer, GradientKind::Radial, ColorMode::Rgb, origin);
opts.settings.compression.compress_text = false;
let bytes = export(&d, &opts).unwrap();
let text = String::from_utf8_lossy(&bytes);
let boxes: Vec<Vec<f64>> = text
.split("/Subtype/Form")
.skip(1)
.map(|form| {
form.split("/BBox[").nth(1).unwrap().split(']').next().unwrap().split_ascii_whitespace().map(|v| v.parse().unwrap()).collect()
})
.collect();
assert_eq!(boxes, [vec![0.0, 0.0, 120.0, 180.0]], "{origin:?}: the layer covers exactly the page");
let back = import(&bytes).unwrap();
let children = back.layers[0].children().unwrap();
assert_eq!(children.len(), 1);
assert!(children[0].path_data().is_some(), "{origin:?}: no clipping group wraps the layer's art");
}
}
// Test the renderer that exhibited the fault, not just our own importer (which accepted the
// old files). OS bindings are confined to this integration-test module.
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
mod quartz {
use objc2_core_foundation::CFData;
use objc2_core_graphics::{CGBitmapContextCreate, CGColorSpace, CGContext, CGDataProvider, CGImageAlphaInfo, CGPDFDocument};
use vectorcraft_testkit::raster::Image;
use super::*;
/// Render the first PDF page through Quartz as an oracle independent of our importer.
fn render(bytes: &[u8]) -> Image {
let data = CFData::from_bytes(bytes);
let provider = CGDataProvider::with_cf_data(Some(&data)).unwrap();
let doc = CGPDFDocument::with_provider(Some(&provider)).unwrap();
let page = CGPDFDocument::page(Some(&doc), 1).unwrap();
let space = CGColorSpace::new_device_rgb().unwrap();
let (width, height) = (120, 180);
let mut rgba = vec![255u8; width * height * 4];
// SAFETY: the buffer holds every RGBA row, stays allocated and is not accessed until the
// context is dropped. All inputs are the small, generated fixtures above.
let context = unsafe {
CGBitmapContextCreate(rgba.as_mut_ptr().cast(), width, height, 8, width * 4, Some(&space), CGImageAlphaInfo::PremultipliedLast.0)
}
.unwrap();
CGContext::draw_pdf_page(Some(&context), Some(&page));
drop(context);
Image { width: width as u32, height: height as u32, rgba }
}
/// Quartz places RGB and CMYK radial centres, edges and masks with their translated art.
#[test]
fn quartz_keeps_off_centre_radials_in_transparency_and_layer_forms() {
for mode in [ColorMode::Rgb, ColorMode::Cmyk] {
for form in FORMS {
for origin in [Point::ORIGIN, Point::new(125.0, -80.0)] {
let (d, opts) = fixture(form, GradientKind::Radial, mode, origin);
let img = render(&export(&d, &opts).unwrap());
let centre = img.over_white(32, 35)[0];
let edge = img.over_white(32, 55)[0];
assert!(centre < 150 && edge.saturating_sub(centre) > 40, "{mode:?} {form:?} {origin:?}: centre {centre}, edge {edge}");
assert_eq!(img.over_white(90, 100), [255; 3], "art stays in its bounds");
if matches!(form, Form::Mask) {
assert_eq!(img.over_white(46, 35), [255; 3], "the mask moves with the gradient");
}
}
}
}
}
/// Quartz retains the linear ramp's direction inside forms on a translated artboard.
#[test]
fn quartz_keeps_linear_gradient_directions_in_forms() {
for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Mask | Form::Knockout)) {
let (d, opts) = fixture(form, GradientKind::Linear, ColorMode::Rgb, Point::new(-30.0, 45.0));
let img = render(&export(&d, &opts).unwrap());
let (start, end) = (img.over_white(20, 20)[0], img.over_white(60, 60)[0]);
assert!(end.saturating_sub(start) > 60, "{form:?}: start {start}, end {end}");
}
}
/// A gradient's stop-opacity mask remains aligned with its colour through nested forms.
#[test]
fn quartz_keeps_gradient_stop_opacity_aligned_inside_nested_forms() {
let (mut d, opts) = fixture(Form::Nested, GradientKind::Radial, ColorMode::Rgb, Point::ORIGIN);
let mut leaves = vec![];
d.walk(|n| {
if n.path_data().is_some() {
leaves.push(n.id);
}
});
for id in leaves {
let fill = d.node_mut(id).unwrap().appearance.fill_mut().unwrap();
let Paint::Gradient(g) = &mut fill.paint else { panic!("gradient fixture") };
for stop in &mut g.gradient.stops {
stop.opacity = 0.6 * (1.0 - stop.offset);
}
}
let img = render(&export(&d, &opts).unwrap());
let (centre, edge) = (img.over_white(32, 35)[0], img.over_white(32, 55)[0]);
assert!(centre > 145 && centre < 205 && edge > 240, "centre {centre}, edge {edge}");
}
}
+10 -3
View File
@@ -98,7 +98,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
brushes: None,
knockout: doc.page_knockout,
anonymous: false,
knockout_filter: None,
knockout_filters: HashMap::new(),
region_boxes: None,
art_reach: HashMap::new(),
warnings: vec![],
id_prefix,
linked: Vec::new(),
@@ -255,8 +257,13 @@ struct Writer<'a> {
knockout: bool,
/// Writing a copy of an object (a knockout mask): no object ids, so they stay unique.
anonymous: bool,
/// The filter that paints art black keeping its alpha (knockout masks), once defined.
knockout_filter: Option<String>,
/// The filters that paint art black keeping its alpha (knockout masks), by the region
/// attributes they were defined with.
knockout_filters: HashMap<String, String>,
/// The document's symbol boxes, measured once for every mask and filter region.
region_boxes: Option<vectorcraft_doc::SymbolBoxes<'a>>,
/// How far each symbol's art paints past its box, by name, once measured for a region.
art_reach: HashMap<String, f64>,
/// The brush library, parsed when the first brushed stroke is written.
brushes: Option<Vec<vectorcraft_brush::Brush>>,
/// Features written approximately (once each).
+148 -16
View File
@@ -2,8 +2,8 @@ use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_vali
use super::paint::{StrokePlan, has_raster, pixel_gradient};
use super::text::OUTLINE_TOLERANCE;
use super::{
Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, Writer,
Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape,
Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, HashMap, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer,
Writer, Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape,
};
/// A symbol's `<symbol>` def and the instance transforms that can `<use>` it.
@@ -143,9 +143,12 @@ fn pin_to_page(n: &mut Node, m: Affine) {
const TINY_MASKS: &str = "SVG Tiny 1.2 has no masks: opacity masks are left out and knockout groups written as plain groups";
pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture";
/// A region covering any artwork (mask and filter extents).
/// The region of a mask or filter over art that has no box to measure: one covering any artwork.
const BIG: &str = "x=\"-100000\" y=\"-100000\" width=\"200000\" height=\"200000\"";
/// How deep [`Writer::paint_reach`] looks into members and symbol art.
const MAX_REACH_DEPTH: u32 = 64;
/// Attributes of every `<mask>`: user-space units, and luminance taken from the sRGB values (as the
/// canvas and PDF take it) rather than from linearised ones.
pub(super) const MASK: &str = "maskUnits=\"userSpaceOnUse\" color-interpolation=\"sRGB\"";
@@ -354,13 +357,18 @@ impl Writer<'_> {
return self.node_body(&bare);
}
let mid = self.fresh_id("mask");
let mut bare = n.clone();
bare.extras_mut().mask = None;
// The region covers what the object and the mask art paint: readers draw the mask into an
// image of the region's size.
let region = self.region_attrs(&[&bare, &m.art]);
// Mask art is a picture of its own: it takes no part in a knockout group around the object.
let knockout = std::mem::take(&mut self.knockout);
let art = self.detached(2, |w| w.node(&m.art));
self.knockout = knockout;
let inv = m.invert.then(|| {
let fid = self.fresh_id("invert");
self.def(1, &format!("<filter id=\"{fid}\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\" {BIG}>"));
self.def(1, &format!("<filter id=\"{fid}\" filterUnits=\"userSpaceOnUse\" color-interpolation-filters=\"sRGB\" {region}>"));
self.def(2, "<feColorMatrix type=\"matrix\" values=\"-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0\"/>");
self.def(1, "</filter>");
fid
@@ -368,13 +376,13 @@ impl Writer<'_> {
// The mask's options, so import restores them (and its art without backdrop and filter).
let flags: Vec<&str> = [(!m.clip).then_some("noclip"), m.invert.then_some("invert")].into_iter().flatten().collect();
let data = if flags.is_empty() { String::new() } else { format!(" {MASK_FLAGS}=\"{}\"", flags.join(" ")) };
self.def(1, &format!("<mask id=\"{mid}\" {MASK} {BIG}{data}>"));
self.def(1, &format!("<mask id=\"{mid}\" {MASK} {region}{data}>"));
if let Some(fid) = &inv {
self.def(1, &format!("<g filter=\"url(#{fid})\">"));
}
if !m.clip || m.invert {
let c = if m.clip { "black" } else { "white" };
self.def(1, &format!("<rect {BIG} fill=\"{c}\"/>"));
self.def(1, &format!("<rect {region} fill=\"{c}\"/>"));
}
self.defs.push_str(&art);
if inv.is_some() {
@@ -383,8 +391,6 @@ impl Writer<'_> {
self.def(1, "</mask>");
self.line(&format!("<g mask=\"url(#{mid})\">"));
self.depth += 1;
let mut bare = n.clone();
bare.extras_mut().mask = None;
self.node_body(&bare);
self.depth -= 1;
self.line("</g>");
@@ -399,6 +405,127 @@ impl Writer<'_> {
std::mem::replace(&mut self.body, body)
}
/// The `x`, `y`, `width` and `height` of a mask or filter region over `nodes`, in the current
/// user space: the box of everything they paint ([`Self::paint_reach`]), 2 larger on each
/// side for antialiasing. [`BIG`] when none of them has a box, when one holds type (a reader
/// sets live type in its own font, which can be wider, and type on a path is measured by its
/// path), or when one nests deeper than [`MAX_REACH_DEPTH`]. The art of a symbol instance
/// written in place keeps its strokes and effects at their own size while the instance scales
/// its geometry, so the region also covers the geometry's box, placed, grown by the strokes'
/// and effects' reach unscaled.
fn region_attrs(&mut self, nodes: &[&Node]) -> String {
let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes());
let mut art_reach = std::mem::take(&mut self.art_reach);
let region = self.region_of(&symbols, &mut art_reach, nodes);
self.region_boxes = Some(symbols);
self.art_reach = art_reach;
region
}
/// [`Self::region_attrs`] with the document's symbol boxes and the symbols' art reach so far.
fn region_of(&self, symbols: &vectorcraft_doc::SymbolBoxes, art_reach: &mut HashMap<String, f64>, nodes: &[&Node]) -> String {
let mut painted: Option<Rect> = None;
for n in nodes {
let Some(v) = n.visual_bounds_with(symbols) else { continue };
let Some(r) = self.paint_reach(symbols, art_reach, n, v, 0) else {
return BIG.to_string();
};
let g = n.geometric_bounds_with(symbols).unwrap_or(v);
let stroke = [g.x0 - v.x0, g.y0 - v.y0, v.x1 - g.x1, v.y1 - g.y1].into_iter().fold(0.0, f64::max);
let scaled = self.xf.transform_rect_bbox(v.inflate(r, r));
let unscaled = self.xf.transform_rect_bbox(g).inflate(stroke + r, stroke + r);
let both = scaled.union(unscaled);
painted = Some(painted.map_or(both, |p| p.union(both)));
}
let Some(b) = painted.map(|b| b.inflate(2.0, 2.0)).filter(|b| b.is_finite()) else {
return BIG.to_string();
};
format!("x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"", self.num(b.x0), self.num(b.y0), self.num(b.width()), self.num(b.height()))
}
/// How far what `n` paints reaches past its visual box `b`: the reach of its own raster effects
/// and of those of its fills and strokes (measured as [`Self::open_filters`] measures them),
/// how far brush art can paint past its brushed strokes (`16 × w + 8` for the widest brushed
/// stroke `w`, as the canvas allows for it), and the most that one of its members or its
/// symbol's art reaches past its own box, spread by its own effects. `art_reach` keeps each
/// symbol's art reach by name once measured, so art used many times is measured once. A live
/// object is measured as the art it is written as: expanded on its own, as [`Self::node`]
/// expands it, so with the same limits. `None` when `n`, its members or its symbol's art hold
/// type, or nest deeper than [`MAX_REACH_DEPTH`].
fn paint_reach(
&self,
symbols: &vectorcraft_doc::SymbolBoxes,
art_reach: &mut HashMap<String, f64>,
n: &Node,
b: Rect,
depth: u32,
) -> Option<f64> {
use vectorcraft_effects::RasterFx;
// Type draws past its measured box in a reader's own font.
if matches!(n.kind, NodeKind::Text(_)) {
return None;
}
// An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first.
let grow = 18.0 / self.doc.raster_ppi();
let reach = |effects: &[vectorcraft_doc::Effect]| -> f64 {
vectorcraft_effects::raster_effects(effects)
.iter()
.map(|f| f.outset(b) + if matches!(f, RasterFx::OuterGlow { .. }) { grow } else { 0.0 })
.sum()
};
let items = n.appearance.items.iter().map(|i| reach(i.effects())).fold(0.0, f64::max);
let brush = if vectorcraft_brush::has_brush(n) {
let w =
n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max);
16.0 * w + 8.0
} else {
0.0
};
let own = reach(&n.appearance.effects) + items + brush;
if vectorcraft_doc::live::is_live(n) {
if depth >= MAX_REACH_DEPTH {
return None;
}
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
let Some(gb) = g.visual_bounds_with(symbols) else { return Some(own) };
let past = [b.x0 - gb.x0, b.y0 - gb.y0, gb.x1 - b.x1, gb.y1 - b.y1].into_iter().fold(0.0, f64::max);
return Some(own + past + self.paint_reach(symbols, art_reach, &g, gb, depth + 1)?);
}
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, xf } => self.doc.symbols.iter().find(|s| s.name == *symbol).map(|s| (s, xf)),
_ => None,
};
if n.children().is_none_or(|c| c.is_empty()) && symbol.is_none() {
return Some(own);
}
if depth >= MAX_REACH_DEPTH {
return None;
}
let mut inner: f64 = 0.0;
for c in n.children().into_iter().flatten() {
if let Some(cb) = c.visual_bounds_with(symbols) {
inner = inner.max(self.paint_reach(symbols, art_reach, c, cb, depth + 1)?);
}
}
if let Some((s, xf)) = symbol {
let art = match art_reach.get(&s.name) {
Some(r) => *r,
None => {
let r = match s.art.visual_bounds_with(symbols) {
Some(ab) => self.paint_reach(symbols, art_reach, &s.art, ab, depth + 1)?,
None => 0.0,
};
art_reach.insert(s.name.clone(), r);
r
}
};
// The art's reach, measured in symbol space, as far as the instance can stretch it.
let [xx, xy, yx, yy, _, _] = xf.as_coeffs();
inner = inner.max(art * xx.hypot(xy).max(yx.hypot(yy)).max(1.0));
}
Some(own + inner)
}
/// Props of a group (or layer): a knockout group is isolated, a hidden one not displayed.
fn group_props(&self, n: &Node) -> Props {
let mut p = css::transparency(n);
@@ -450,9 +577,12 @@ impl Writer<'_> {
written.push((before, self.detached(depth + nest - 1 - i, |w| w.node(c))));
}
let after = self.symbol_nodes;
// Each mask covers what the group's elements paint.
let all: Vec<&Node> = elements.iter().map(|c| &***c).collect();
let region = self.region_attrs(&all);
for (c, (before, _)) in rest.iter().zip(&written).rev() {
self.symbol_nodes = *before;
let mid = self.knockout_mask(c);
let mid = self.knockout_mask(c, &region);
self.line(&format!("<g mask=\"url(#{mid})\">"));
self.depth += 1;
}
@@ -466,16 +596,18 @@ impl Writer<'_> {
}
/// A mask that is 1 − the knockout shape of `c`: white, then `c` painted black (at full object
/// opacity without its own mask, unless those define its shape). Returns the mask id.
fn knockout_mask(&mut self, c: &Node) -> String {
let filter = match &self.knockout_filter {
/// opacity without its own mask, unless those define its shape). `region` is the attributes of
/// the mask's region ([`Self::region_attrs`]), which the filter that paints `c` black shares.
/// Returns the mask id.
fn knockout_mask(&mut self, c: &Node, region: &str) -> String {
let filter = match self.knockout_filters.get(region) {
Some(f) => f.clone(),
None => {
let f = self.fresh_id("knockout-shape");
self.def(1, &format!("<filter id=\"{f}\" filterUnits=\"userSpaceOnUse\" {BIG}>"));
self.def(1, &format!("<filter id=\"{f}\" filterUnits=\"userSpaceOnUse\" {region}>"));
self.def(2, "<feColorMatrix type=\"matrix\" values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0\"/>");
self.def(1, "</filter>");
self.knockout_filter = Some(f.clone());
self.knockout_filters.insert(region.to_string(), f.clone());
f
}
};
@@ -490,8 +622,8 @@ impl Writer<'_> {
let art = self.detached(3, |w| w.node(&shape));
self.anonymous = anonymous;
let mid = self.fresh_id("knockout");
self.def(1, &format!("<mask id=\"{mid}\" {MASK} {BIG}>"));
self.def(2, &format!("<rect {BIG} fill=\"white\"/>"));
self.def(1, &format!("<mask id=\"{mid}\" {MASK} {region}>"));
self.def(2, &format!("<rect {region} fill=\"white\"/>"));
self.def(2, &format!("<g filter=\"url(#{filter})\">"));
self.defs.push_str(&art);
self.def(2, "</g>");
+126 -2
View File
@@ -1,10 +1,11 @@
//! Blend modes and opacity masks in SVG export look as on the canvas: every mode follows the
//! reference formulas when resvg draws the file, and masks take luminance the canvas's way.
use usvg::roxmltree;
use vectorcraft_color::blend::blend_rgb;
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, OpacityMask};
use vectorcraft_geom::{Rect, shapes};
use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeKind, OpacityMask, TextObject};
use vectorcraft_geom::{Point, Rect, shapes};
use vectorcraft_svg::{ExportOptions, export};
use vectorcraft_testkit::raster::{Image, render_artboard};
@@ -138,3 +139,126 @@ fn a_knockout_group_with_a_brushed_stroke_keeps_its_masks() {
let svg = export(&d, &ExportOptions::default());
assert!(svg.contains("<mask"), "{svg}");
}
/// The `x`, `y`, `width` and `height` of each `<mask>` and `<filter>` element in `svg`.
fn regions(svg: &str) -> Vec<[f64; 4]> {
let xml = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).unwrap();
xml.descendants()
.filter(|n| matches!(n.tag_name().name(), "mask" | "filter"))
.map(|n| ["x", "y", "width", "height"].map(|a| n.attribute(a).and_then(|v| v.parse().ok()).unwrap_or(f64::NAN)))
.collect()
}
/// Mask and filter regions cover the art they apply to and no more: readers draw a mask into an
/// image of its region's size, and one drawn at 200,000 units square runs out of memory.
#[test]
fn mask_and_filter_regions_cover_their_art() {
let knockout = {
let mut d = Document::new(40.0, 20.0);
let below = rect(&mut d, Rect::new(0.0, 0.0, 40.0, 20.0), [200, 0, 0]);
let mut top = rect(&mut d, Rect::new(5.0, 5.0, 15.0, 15.0), [0, 0, 200]);
top.opacity = 0.5;
let mut group = Node::group(d.alloc_id(), vec![below.into(), top.into()]);
group.knockout = vectorcraft_doc::Knockout::On;
add(&mut d, group);
d
};
for (what, d) in [("clip", masked(true, false)), ("no clip, inverted", masked(false, true)), ("knockout", knockout)] {
let svg = export(&d, &ExportOptions::default());
let found = regions(&svg);
assert!(!found.is_empty(), "{what}: {svg}");
for [x, y, w, h] in found {
// The art is 40 × 20, with 2 to spare on each side.
assert!(x >= -2.5 && y >= -2.5 && w <= 45.0 && h <= 25.0 && w >= 40.0 && h >= 20.0, "{what}: {x} {y} {w} {h} in {svg}");
}
}
}
/// A mask's region reaches as far as the masked art paints: a drop shadow of the object, or of an
/// object in the masked group, shows past the object as on the canvas.
#[test]
fn a_mask_region_keeps_the_shadows_of_the_masked_art() {
let shadow = vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 15, "y": 15, "blur": 0, "opacity": 100}),
visible: true,
};
for in_group in [false, true] {
let mut d = Document::new(60.0, 60.0);
let mut red = rect(&mut d, Rect::new(10.0, 10.0, 30.0, 30.0), [255, 0, 0]);
red.appearance.effects.push(shadow.clone());
let mut masked = if in_group { Node::group(d.alloc_id(), vec![red.into()]) } else { red };
// An unclipped mask lets the art show outside the mask art: all of the shadow shows.
let art = rect(&mut d, Rect::new(10.0, 10.0, 20.0, 30.0), [255, 255, 255]);
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
add(&mut d, masked);
let svg = export(&d, &ExportOptions::default());
let (canvas, written) = (render_artboard(&d), resvg_render(&svg, 60, 60));
for (x, y) in [(15, 15), (40, 40), (35, 28)] {
let (c, w) = (canvas.over_white(x, y), written.over_white(x, y));
assert!(within(c, w, 3), "in a group {in_group}, at {x},{y}: canvas {c:?}, svg {w:?}\n{svg}");
}
assert!(canvas.over_white(40, 40)[0] < 100, "the shadow shows on the canvas: {:?}", canvas.over_white(40, 40));
}
}
/// Type is measured by its layout or its path, and a reader sets live type in its own font, so a
/// mask or knockout over type keeps the region that covers any artwork.
#[test]
fn mask_and_filter_regions_over_type_cover_any_artwork() {
let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() };
let text = |d: &mut Document| Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 30.0), "Wide", style.clone()))));
let masked = {
let mut d = Document::new(80.0, 40.0);
let mut t = text(&mut d);
let art = rect(&mut d, Rect::new(0.0, 0.0, 40.0, 40.0), [255, 255, 255]);
t.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
add(&mut d, t);
d
};
let knockout = {
let mut d = Document::new(80.0, 40.0);
let below = rect(&mut d, Rect::new(0.0, 0.0, 80.0, 40.0), [200, 0, 0]);
let mut top = text(&mut d);
top.opacity = 0.5;
let mut group = Node::group(d.alloc_id(), vec![below.into(), top.into()]);
group.knockout = vectorcraft_doc::Knockout::On;
add(&mut d, group);
d
};
for (what, d) in [("masked type", masked), ("type in a knockout group", knockout)] {
let svg = export(&d, &ExportOptions::default());
let found = regions(&svg);
assert!(!found.is_empty(), "{what}: {svg}");
for [x, y, w, h] in found {
assert!(x <= -100000.0 && y <= -100000.0 && w >= 200000.0 && h >= 200000.0, "{what}: {x} {y} {w} {h} in {svg}");
}
}
}
/// A live object under a mask is measured as it is written, expanded: the mask's region covers
/// the drop shadows of a blend's steps.
#[test]
fn a_mask_region_covers_a_blend_as_written() {
let shadow = vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 15, "y": 15, "blur": 0, "opacity": 100}),
visible: true,
};
let mut d = Document::new(100.0, 50.0);
let mut a = rect(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), [255, 0, 0]);
let mut b = rect(&mut d, Rect::new(70.0, 10.0, 80.0, 20.0), [0, 0, 255]);
a.appearance.effects.push(shadow.clone());
b.appearance.effects.push(shadow);
let mut blend = Node::new(d.alloc_id(), NodeKind::Blend { children: vec![a.into(), b.into()], spec: Default::default() });
let art = rect(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0), [255, 255, 255]);
blend.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
add(&mut d, blend);
let svg = export(&d, &ExportOptions::default());
// The steps' drop shadows are filters with regions of their own; the mask's covers them all:
// the steps run from 10 to 80 across, and their shadows 15 further.
let xml = roxmltree::Document::parse_with_options(&svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).unwrap();
let mask = xml.descendants().find(|n| n.has_tag_name("mask")).unwrap();
let [x, y, w, h] = ["x", "y", "width", "height"].map(|a| mask.attribute(a).and_then(|v| v.parse::<f64>().ok()).unwrap_or(f64::NAN));
assert!(x <= 0.0 && y <= 0.0 && x + w >= 95.0 && y + h >= 35.0 && w < 200.0 && h < 200.0, "{x} {y} {w} {h} in {svg}");
}
+23
View File
@@ -645,3 +645,26 @@ fn nested_svg_images_past_count_cap_are_left_out() {
let (_d, warnings) = import_with(&svg, &ImportOptions::default()).unwrap();
assert!(warnings.iter().any(|w| w.contains(&format!("more than {MAX_NESTED_SVG_IMAGES} nested SVG images"))));
}
/// #3566: entity references in element content count toward the expansion limit, as in
/// attributes. A 10 KB entity, a second entity that refers to it 250 times, and eight references
/// to the second inside `<desc>` would expand to about 20 MB from a file of a few KB: the import
/// refuses it before the XML reader expands anything. The namespace entities drawing apps write
/// (`&ns_svg;`) still import.
#[test]
fn entities_repeated_in_element_content_are_refused_and_namespace_entities_import() {
let bomb = format!(
r#"<!DOCTYPE svg [<!ENTITY a "{}"><!ENTITY b "{}">]><svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><desc>{}</desc><rect width="5" height="5"/></svg>"#,
"x".repeat(10_000),
"&a;".repeat(250),
"&b;".repeat(8)
);
assert!(bomb.len() < 20_000, "{} bytes", bomb.len());
match import_with(&bomb, &ImportOptions::default()) {
Err(SvgError::Parse(e)) => assert!(e.contains("entities"), "{e}"),
other => panic!("refused as a parse error, not {:?}", other.map(|(_, w)| w)),
}
let ns = r#"<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY ns_svg "http://www.w3.org/2000/svg">]><svg xmlns="&ns_svg;" width="10" height="10"><rect width="5" height="5"/></svg>"#;
let (d, _) = import_with(ns, &ImportOptions::default()).unwrap();
assert_eq!(art(&d).len(), 1, "the rectangle");
}
+21
View File
@@ -55,6 +55,27 @@ fn an_inverted_unclipped_mask_round_trips() {
}
}
/// Mask art that reaches past the masked object comes back whole: the mask's region covers the art
/// as well as the object, so import does not clip the art to the region.
#[test]
fn mask_art_larger_than_its_object_round_trips_unclipped() {
let mut d = Document::new(200.0, 200.0);
let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
let white = Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0);
let mut n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(50.0, 50.0, 100.0, 100.0)), red);
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 20.0, 180.0, 170.0)), white);
n.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
let l = d.layers[0].id;
d.insert(Some(l), 0, n).unwrap();
let s = export(&d, &ExportOptions::default());
let (back, warnings) = import_with_report(&s).unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
let [m] = &masks(&back)[..] else { panic!("one masked object: {s}") };
assert!(m.art.path_data().is_some(), "the art alone, not clipped by the region: {:?}\n{s}", m.art.kind);
let b = m.art.geometric_bounds().unwrap();
assert!((b.x0 - 10.0).abs() < 1e-6 && (b.y0 - 20.0).abs() < 1e-6 && (b.x1 - 180.0).abs() < 1e-6 && (b.y1 - 170.0).abs() < 1e-6, "{b:?}");
}
#[test]
fn foreign_masks_keep_their_art() {
// Without the attribute a white backdrop is part of the mask art (another app's file).
+25
View File
@@ -296,6 +296,31 @@ fn masks_in_symbols_move_with_the_art_when_linked() {
}
}
/// A masked object in a symbol's art, drawn by an instance that scales it down: its stroke keeps
/// its weight, and the mask's region still covers all of it.
#[test]
fn a_mask_in_a_scaled_instance_covers_the_strokes_at_their_weight() {
let mut d = Document::new(120.0, 120.0);
let stroked = Appearance::basic(Paint::solid(Color::rgb8(200, 0, 0)), Paint::solid(Color::BLACK), 20.0);
let mut art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), stroked);
let shape = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)),
Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0),
);
art.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(shape, false)));
d.symbols.push(Symbol { dynamic: false, name: "Framed".into(), art: Arc::new(art) });
instance(&mut d, "Framed", Affine::translate((50.0, 50.0)) * Affine::scale(0.2));
let svg = export(&d, &ExportOptions::default());
let (canvas, written) = (render_artboard(&d), resvg_render(&svg, 120, 120));
// The stroke runs 10 either side of the 20 × 20 square's edge at (50, 50).
for (x, y) in [(43, 60), (77, 60), (60, 43), (60, 77)] {
let (c, w) = (canvas.over_white(x, y), written.over_white(x, y));
assert!(c.iter().all(|v| *v < 60), "the stroke shows on the canvas at {x},{y}: {c:?}");
assert!(c.iter().zip(w).all(|(a, b)| (*a as i32 - b as i32).abs() <= 8), "at {x},{y}: canvas {c:?}, svg {w:?}\n{svg}");
}
}
#[test]
fn symbols_inside_themselves_end() {
let mut d = symbol_doc(1.0, &[Affine::translate((50.0, 50.0))]);
+41 -3
View File
@@ -512,6 +512,43 @@ fn assert_authored_ownership(t: &TextObject, text: &str, l: &TextLayout, what: &
}
}
/// Repeated glyphs in one cluster can belong to differently painted runs. Match each authored
/// occurrence in order, without needing an installed font, and still reject a changed owner.
#[test]
fn duplicate_authored_glyphs_keep_occurrence_order() {
let mut text = TextObject::point(Point::ZERO, "\u{0651}", style(FAMILY));
text.runs.push(vectorcraft_doc::TextRun::new("\u{0651}", CharStyle { fill: red(), ..style(FAMILY) }));
let glyph = |run| PositionedGlyph {
outline: Default::default(),
run,
byte: 0,
origin: Point::ZERO,
advance: 0.0,
len: 4,
angle: 0.0,
line: 0,
font_id: 0,
gid: 7,
xf: Affine::IDENTITY,
rtl: true,
scale: 1.0,
image: None,
colour: None,
bend: None,
unturned: Affine::IDENTITY,
pivot: Point::ZERO,
carets: Vec::new(),
width: 0.0,
width_start: 0.0,
};
let before = TextLayout { glyphs: vec![glyph(0), glyph(1)], ..TextLayout::default() };
assert_eq!(assert_kashida_ownership(&text, &before, &before, &red(), "duplicate glyphs", false), 0);
let mut wrong = before.clone();
wrong.glyphs[0].run = 1;
assert!(std::panic::catch_unwind(|| assert_kashida_ownership(&text, &before, &wrong, &red(), "changed owner", false)).is_err());
}
/// Compare authored glyph run indices before/after Insert Kashidas (matched by byte and gid;
/// layout order can differ between point and justified area), and assert every inserted tatweel
/// uses the base letter's paint at the cluster start—not `mark_fill`. When `require_mark_last`,
@@ -525,16 +562,17 @@ fn assert_kashida_ownership(
what: &str,
require_mark_last: bool,
) -> usize {
let mut before_runs: std::collections::HashMap<(usize, u32), Vec<usize>> = std::collections::HashMap::new();
let mut before_runs: std::collections::HashMap<(usize, u32), std::collections::VecDeque<usize>> = std::collections::HashMap::new();
for g in before.glyphs.iter().filter(|g| g.len > 0) {
before_runs.entry((g.byte, g.gid)).or_default().push(g.run);
before_runs.entry((g.byte, g.gid)).or_default().push_back(g.run);
}
let mut after_n = 0;
for g in with_kashida.glyphs.iter().filter(|g| g.len > 0) {
after_n += 1;
let runs =
before_runs.get_mut(&(g.byte, g.gid)).unwrap_or_else(|| panic!("{what}: authored glyph {} at {} missing before kashida", g.gid, g.byte));
let want_run = runs.pop().unwrap_or_else(|| panic!("{what}: no remaining before-run for {} at {}", g.gid, g.byte));
// Duplicate glyphs at the same cluster byte retain their occurrence order.
let want_run = runs.pop_front().unwrap_or_else(|| panic!("{what}: no remaining before-run for {} at {}", g.gid, g.byte));
assert_eq!(g.run, want_run, "{what}: authored run at {} gid {}", g.byte, g.gid);
let want_fill = coloured.runs.get(want_run).map(|r| &r.style.fill).unwrap_or_else(|| panic!("{what}: missing run {want_run}"));
assert_eq!(&run_of(coloured, g).style.fill, want_fill, "{what}: authored fill at {}", g.byte);
+5
View File
@@ -547,6 +547,11 @@ impl Tool for SmartPenTool {
key == ToolKey::Tab && (self.press.is_some() || self.active(cx).is_some())
}
/// A path being drawn: Escape ends it.
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
self.path.is_some()
}
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.stop();
self.marquee = None;
+124 -12
View File
@@ -67,8 +67,13 @@ pub struct DimensionTool {
snap: crate::guides::DrawSnap,
/// Where the next Linear pick lands, as last worked out for the pointer (for the overlays).
snapped: Option<(Point, Option<PointRef>)>,
/// Whether the press under way began on an anchor a Linear click picks.
press_on_anchor: bool,
}
/// How near an anchor (screen pixels) a pick snaps to it.
const ANCHOR_REACH: f64 = 8.0;
/// `at` as a Shift click picks it: the direction from `last` snapped to 45° steps (from the
/// constrain angle), the distance kept.
fn constrained(cx: &ToolContext, last: Point, at: Point) -> Point {
@@ -119,10 +124,45 @@ fn anchor_near(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<(usize,
[edge.segment, next]
.into_iter()
.filter_map(|i| Some((i, sp.anchors.get(i)?.p)))
.filter(|(_, a)| a.distance(p) <= cx.tol(8.0))
.filter(|(_, a)| a.distance(p) <= cx.tol(ANCHOR_REACH))
.min_by(|(_, a), (_, b)| a.distance(p).total_cmp(&b.distance(p)))
}
/// The anchor nearest `p` within reach, on any editable path (the topmost on a tie), as a link to
/// its path. Bounded work, and dimension artwork is skipped, as in [`pick`].
fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> {
type Best = Option<(f64, Point, PointRef)>;
fn visit(n: &Node, p: Point, reach: f64, budget: &mut usize, best: &mut Best) {
if *budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() {
return;
}
if let Some(path) = n.path_data() {
for (subpath, sp) in path.subpaths.iter().enumerate() {
for (anchor, a) in sp.anchors.iter().enumerate() {
if *budget == 0 {
return;
}
*budget -= 1;
let d = a.p.distance(p);
if d <= reach && best.as_ref().is_none_or(|(nearest, ..)| d < *nearest) {
*best = Some((d, a.p, PointRef { node: n.id, subpath, anchor }));
}
}
}
}
if let Some(ch) = n.children() {
for c in ch.iter().rev() {
visit(c, p, reach, budget, best);
}
}
}
let (reach, mut budget, mut best) = (cx.tol(ANCHOR_REACH), 20_000usize, None);
for n in cx.doc.layers.iter().rev() {
visit(n, p, reach, &mut budget, &mut best);
}
best.map(|(_, at, r)| (at, r))
}
/// The point of `edge` closest to `p`.
fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<Point> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
@@ -138,25 +178,22 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<Point> {
}
impl DimensionTool {
/// Where a Linear pick at `p` lands: on an anchor of the line under the pointer, within reach
/// (kept as a link to its path); else where Smart Guides put it (another object's anchor or
/// centre, in line with one, or for the second point on a construction guide through the
/// first), its guides showing; else on the closest point of that line; else `p` itself.
/// 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
/// line with one, or for the second point on a construction guide through the first), its
/// guides showing; else on the closest point of the line under the pointer; else `p` itself.
fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option<PointRef>) {
let leave = self.points.last().map(|(first, _)| crate::guides::Leave::segment(cx, *first, false));
let guided = self.snap.hover(cx, p, &[], leave.as_ref());
let edge = pick(cx, p);
if let Some(edge) = &edge
&& let Some((anchor, point)) = anchor_near(cx, edge, p)
{
if let Some((point, reference)) = anchor_under(cx, p) {
self.snap.clear();
return (point, Some(PointRef { node: edge.node, subpath: edge.subpath, anchor }));
return (point, Some(reference));
}
if guided.distance(p) > 1e-9 {
return (guided, None);
}
// Not on an anchor or a guide: snap to the closest point of the line (#2432).
(edge.and_then(|e| nearest_on(cx, &e, p)).unwrap_or(p), None)
(pick(cx, p).and_then(|e| nearest_on(cx, &e, p)).unwrap_or(p), None)
}
fn target(&self, cx: &ToolContext, p: Point) -> Option<Target> {
let edge = pick(cx, p)?;
@@ -243,6 +280,7 @@ impl DimensionTool {
fn reset(&mut self) {
self.pending = None;
self.press = None;
self.press_on_anchor = false;
self.points.clear();
self.lines.clear();
self.dragging = false;
@@ -355,6 +393,10 @@ impl Tool for DimensionTool {
self.press = Some((ev.pos, None));
return self.preview(cx, ev.pos);
}
// A Linear press on an anchor picks the anchor unless it drags past the anchor's
// reach: moving a few pixels before the release does not drag out the dimension of
// a segment under the pointer.
self.press_on_anchor = self.kind == Kind::Linear && anchor_under(cx, ev.pos).is_some();
self.press = Some((ev.pos, self.target(cx, ev.pos)));
vec![]
}
@@ -364,7 +406,7 @@ impl Tool for DimensionTool {
}
if self.pending.is_none()
&& let Some((start, Some(target))) = self.press.clone()
&& start.distance(ev.pos) > cx.tol(3.0)
&& start.distance(ev.pos) > cx.tol(if self.press_on_anchor { ANCHOR_REACH } else { 3.0 })
&& self.points.is_empty()
&& self.lines.is_empty()
{
@@ -543,6 +585,76 @@ mod tests {
assert!(matches!(placed.last(), Some(Action::Commit)), "{placed:?}");
}
/// A Linear press on an anchor picks that anchor even when the pointer moves a few pixels
/// before the release: it does not drag out the dimension of a segment that ends there. Both
/// picks keep their links to the path, so the dimension measures between the two anchors.
#[test]
fn a_press_on_an_anchor_picks_it_when_the_pointer_moves() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y);
let mut t = DimensionTool::default();
for ((x, y), (dx, dy)) in [((100.0, 100.0), (3.5, 1.0)), ((200.0, 200.0), (-4.0, -2.0))] {
assert!(t.pointer(&c, &ev(PointerKind::Down, x, y)).is_empty());
assert!(t.pointer(&c, &ev(PointerKind::Drag, x + dx, y + dy)).is_empty(), "no segment dimension is dragged out");
assert!(t.pointer(&c, &ev(PointerKind::Up, x + dx, y + dy)).is_empty(), "nothing is committed");
}
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 }));
// 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));
assert!(t.pointer(&c, &ev(PointerKind::Drag, 103.0, 106.0)).is_empty());
let acts = t.pointer(&c, &ev(PointerKind::Drag, 100.0, 60.0));
assert!(matches!(acts.first(), Some(Action::Begin(_))), "{acts:?}");
assert!(matches!(t.pointer(&c, &ev(PointerKind::Up, 100.0, 60.0)).last(), Some(Action::Commit)));
}
/// The anchors of a live rectangle are picked the same way.
#[test]
fn a_press_on_a_live_shapes_anchor_picks_it() {
let (d, id) = doc_with_live_rect();
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let mut t = DimensionTool::default();
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 100.0));
t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 197.0, 102.0));
t.pointer(&c, &PointerEvent::new(PointerKind::Up, 197.0, 102.0));
let [(at, Some(r))] = t.points.as_slice() else { panic!("{:?}", t.points) };
assert_eq!((*at, r.node), (Point::new(200.0, 100.0), id));
}
/// An anchor of a compound path inside nested groups, lying just inside another object's
/// edge, is picked and linked, though that edge is nearer the pointer than any of the
/// compound path's own segments. A press there that moves a few pixels picks it too.
#[test]
fn an_anchor_under_another_objects_edge_is_picked() {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, NodeKind};
use vectorcraft_geom::Rect;
let (mut d, _) = doc_with_rect();
let l = d.layers[0].id;
let (outer, inner, compound) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
let mut path = vectorcraft_geom::shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0));
path.subpaths.extend(vectorcraft_geom::shapes::rectangle(Rect::new(150.0, 103.0, 180.0, 130.0)).subpaths);
let art = Node::path(compound, path, Appearance::default_art());
let inner_group = Node::new(inner, NodeKind::Group { children: vec![Arc::new(art)], clip: false });
let group = Node::new(outer, NodeKind::Group { children: vec![Arc::new(inner_group)], clip: false });
d.insert(Some(l), 0, group).unwrap();
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let corner = (Point::new(150.0, 103.0), Some(PointRef { node: compound, subpath: 1, anchor: 0 }));
let mut t = DimensionTool::default();
assert_eq!(t.snap_linear(&c, Point::new(151.0, 101.0)), corner);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 151.0, 101.0));
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 155.0, 100.0)).is_empty(), "no segment dimension is dragged out");
t.pointer(&c, &PointerEvent::new(PointerKind::Up, 155.0, 100.0));
assert_eq!(t.points, vec![corner]);
}
#[test]
fn placement_press_previews_without_a_prior_move() {
let (d, _) = doc_with_rect();
+31 -2
View File
@@ -557,7 +557,7 @@ fn hit_frame_edge(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Vec<A
fn handle_anchors(cx: &ToolContext) -> Vec<(NodeId, usize, usize, Anchor)> {
let mut v = vec![];
for &id in &cx.selection.objects {
let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue };
let Some(pd) = cx.doc.node(id).and_then(handle_path) else { continue };
let shown = cx.selection.partial(id);
v.extend(pd.anchors().filter(|(si, ai, _)| shown.is_none_or(|set| set.contains(&(*si, *ai)))).map(|(si, ai, a)| {
let mut a = *a;
@@ -579,6 +579,33 @@ fn handle_anchors(cx: &ToolContext) -> Vec<(NodeId, usize, usize, Anchor)> {
v
}
/// The path whose direction handles Direct Selection shows and drags on `n` once it is selected:
/// a path's, or type on a path's path (#3565), in document space.
fn handle_path(n: &Node) -> Option<Cow<'_, PathData>> {
match &n.kind {
NodeKind::Path { path, .. } => Some(Cow::Borrowed(path)),
NodeKind::Text(t) if is_path_type(n) => t.type_path().map(Cow::Owned),
_ => None,
}
}
/// The direction handles of selected type on a path ([`handle_anchors`]), drawn by the tool:
/// the canvas draws only a path's own (#3565).
fn type_path_handles(cx: &ToolContext) -> Vec<Overlay> {
let mut out = vec![];
for (id, _, _, a) in handle_anchors(cx) {
if !cx.doc.node(id).is_some_and(is_path_type) {
continue;
}
let color = cx.doc.layer_color(id);
for h in [a.h_in, a.h_out].into_iter().filter(|h| h.distance(a.p) > 1e-6) {
out.push(Overlay::Line { a: a.p, b: h, color, dashed: false });
out.push(Overlay::Handle { p: h, color });
}
}
out
}
/// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and
/// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path,
/// subpath, anchor, is_out).
@@ -897,8 +924,9 @@ impl Tool for DirectSelectionTool {
let (q, guides) = self.handle_snap.snap(cx, (id, si, ai), p, ev.mods.shift);
self.snapped = snapped(q.to_vec2(), p.to_vec2(), ev.mods.shift, &guides);
self.guides = guides;
let cmd = if cx.doc.node(id).is_some_and(is_path_type) { "text.setPathHandle" } else { "path.setHandle" };
vec![Action::Preview(
"path.setHandle".into(),
cmd.into(),
json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}),
)]
}
@@ -1001,6 +1029,7 @@ impl Tool for DirectSelectionTool {
out.push(Overlay::Path { path, color: cx.doc.layer_color(sp.instance), width: 1.0, dashed: false });
}
out.extend(frame_overlays(cx, &self.frame_anchors(cx)));
out.extend(type_path_handles(cx));
let drag = if let State::Bracket(b) = &self.state { Some(b) } else { None };
out.extend(pathtype::overlays(cx, self.bracket_hover, drag));
}
+35
View File
@@ -2334,3 +2334,38 @@ fn a_press_on_a_clipping_path_in_a_dynamic_instance_picks_it() {
outline.iter().find_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::kurbo::Shape::bounding_box(path)) } else { None });
assert_eq!(drawn, Some(Rect::new(310.0, 310.0, 320.0, 320.0)));
}
/// #3565: selected type on a path shows its path's direction handles, as a path selected whole
/// shows its own, and a press on one drags it with `text.setPathHandle` (Shift: 45° steps round
/// its anchor; Alt: that side only); none with Show handles when multiple anchors are selected off.
#[test]
fn type_on_a_path_shows_and_drags_its_paths_handles() {
let (mut d, text) = doc_with_path_type();
let Some(vectorcraft_doc::NodeKind::Text(t)) = d.node_mut(text).map(|n| &mut n.kind) else { panic!("type") };
let vectorcraft_doc::TextKind::OnPath { path, .. } = &mut t.kind else { panic!("on a path") };
path.subpaths[0].anchors[0].h_out = Point::new(100.0, 200.0);
path.subpaths[0].anchors[1].h_in = Point::new(400.0, 200.0);
let p = paint();
let mut s = Selection::default();
s.add(text);
let c = cx(&d, &s, &p);
let handles = |c: &ToolContext| -> Vec<Point> {
DirectSelectionTool::new(false).overlays(c).iter().filter_map(|o| if let Overlay::Handle { p, .. } = o { Some(*p) } else { None }).collect()
};
assert_eq!(handles(&c), vec![Point::new(100.0, 200.0), Point::new(400.0, 200.0)]);
let mut t = DirectSelectionTool::new(false);
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 101.0, 201.0)), vec![Action::Begin("Reshape".into())]);
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 210.0).with_mods(Mods { alt: true, ..Mods::default() }));
assert!(
matches!(&a[..], [Action::Preview(n, v)] if n == "text.setPathHandle" && v["id"] == text.0 && v["subpath"] == 0 && v["anchor"] == 0 && v["which"] == "out" && v["independent"] == true),
"{a:?}"
);
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 210.0)), vec![Action::Commit]);
let mut t = DirectSelectionTool::new(false);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 399.0, 201.0));
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 390.0, 120.0).with_mods(Mods { shift: true, ..Mods::default() }));
let Some(Action::Preview(n, v)) = a.first() else { panic!("{a:?}") };
assert_eq!((n.as_str(), &v["anchor"], &v["which"]), ("text.setPathHandle", &json!(1), &json!("in")));
assert!((v["x"].as_f64().unwrap() - 400.0).abs() < 1e-9, "Shift keeps it straight above its anchor: {v}");
assert!(handles(&ToolContext { handles_multiple: false, ..cx(&d, &s, &p) }).is_empty());
}
+4
View File
@@ -649,6 +649,10 @@ impl Tool for CurvatureTool {
self.id = Some(cx.selection.objects[0]);
}
}
/// A path being drawn: Escape ends it.
fn ends_on_escape(&self, cx: &ToolContext) -> bool {
self.active(cx).is_some()
}
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
matches!(key, ToolKey::Backspace | ToolKey::Delete)
&& self.drag.is_none()
+6 -2
View File
@@ -428,8 +428,12 @@ impl HandleSnap {
/// Where the handle of anchor `ai` of subpath `si` of path `id` goes with the pointer at `p`,
/// and the guides showing why.
pub fn snap(&mut self, cx: &ToolContext, (id, si, ai): (NodeId, usize, usize), p: Point, shift: bool) -> (Point, Vec<Overlay>) {
let path = cx.doc.node(id).and_then(|n| n.path_data());
if shift && let Some(a) = path.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) {
// A path's anchor, or one of type on a path's path (#3565), in document space.
let anchor = cx.doc.node(id).and_then(|n| match &n.kind {
vectorcraft_doc::NodeKind::Text(t) => t.type_path()?.subpaths.get(si)?.anchors.get(ai).copied(),
_ => n.path_data()?.subpaths.get(si)?.anchors.get(ai).copied(),
});
if shift && let Some(a) = anchor {
return (a.p + constrain_angle_from(p - a.p, 45.0, cx.constrain_angle), vec![]);
}
if self.0.targets.is_none() {
+6
View File
@@ -162,6 +162,12 @@ pub trait Tool: Send {
fn claims_key(&self, _cx: &ToolContext, _key: ToolKey) -> bool {
false
}
/// Has the tool started something that Escape ends while no button is pressed (a path being
/// drawn, the Blend tool's first pick)? That Escape ends nothing else, such as isolation mode or
/// a rotated view.
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
false
}
/// Does the tool want typed text (Type tool editing)? Single-key shortcuts are suppressed.
fn wants_text(&self) -> bool {
false
+6
View File
@@ -153,6 +153,10 @@ impl Tool for BlendTool {
fn busy(&self) -> bool {
self.first.is_some()
}
/// A first pick, or adding to the blend just made: Escape ends either.
fn ends_on_escape(&self, cx: &ToolContext) -> bool {
self.first(cx).is_some()
}
/// Escape drops the object picked first and stops adding to the blend just made, so the next
/// click picks a new first object. The document and the selection stay as they are.
fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec<Action> {
@@ -525,8 +529,10 @@ mod tests {
let c = cx(&d, &s, &p);
let mut t = BlendTool { first: None, chained: true, ..Default::default() };
assert!(t.first(&c).is_some());
assert!(!t.busy() && t.ends_on_escape(&c), "Escape has adding to the blend to end");
assert!(t.key(&c, crate::ToolKey::Escape, Mods::default()).is_empty());
assert!(t.first(&c).is_none(), "Escape ends adding to the blend just made");
assert!(!t.ends_on_escape(&c), "and then has nothing to end");
assert_eq!(t.pointer(&c, &down(150.0, 150.0)), picks(a));
assert!(esc(&mut BlendTool::default()).is_empty(), "nothing to drop");
}
+4
View File
@@ -242,6 +242,10 @@ impl Tool for PenTool {
fn busy(&self) -> bool {
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 pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let tol = cx.tol(5.0).max(cx.point_tol());
// The path a press began is the selected one by the next event.
+27 -6
View File
@@ -53,6 +53,8 @@ impl VectorcraftApp {
// The place cursor's clicks and drags place their files through the app
// ([`place::place_from_cursor`]).
session.place_cursor_requests = true;
// A script runs a slice per frame, so the window keeps drawing and Stop can be pressed.
session.script_frames = true;
let views = session.documents().iter().map(View::of).collect();
let view_uids = session.documents().iter().map(|d| d.uid).collect();
let known = session.documents().iter().map(|d| d.uid).collect();
@@ -124,6 +126,7 @@ impl VectorcraftApp {
updates_rt: Default::default(),
frame_rate: Default::default(),
canvas_rect: None,
control_rotate_press: None,
hover_doc: None,
titlebar_from_env: false,
custom_titlebar: false,
@@ -232,6 +235,19 @@ impl VectorcraftApp {
/// eframe isn't a dependency of this crate (the host owns the event loop); these entry points are
/// called from the host's `eframe::App` impl.
impl VectorcraftApp {
/// Applies the work that finished off the UI thread. It stays pending while a script runs, since
/// every change to the documents ends in a busy error until the script ends.
pub(crate) fn poll_finished_work(&mut self) {
if self.session.script_running() {
return;
}
background::poll(self);
opening::poll(self);
plugin_runs::poll(self);
trace_runs::poll(self);
placing::poll(self);
}
/// The language the UI is drawn in: the Preferences dialog's choice while it is open (so a
/// change shows before OK), else the `interfaceLanguage` preference (`auto` = the system's).
pub fn ui_language(&self) -> i18n::Lang {
@@ -321,12 +337,12 @@ impl VectorcraftApp {
// A Paste the host read before this iteration's formats were written must still wait for
// them, even if the worker below finishes them during this same tick.
ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending()));
background::poll(self);
screen_color::poll(self, ctx);
opening::poll(self);
plugin_runs::poll(self);
trace_runs::poll(self);
placing::poll(self);
self.poll_finished_work();
crate::script_runs::poll(self);
if self.session.script_running() && !self.session.script_waiting() {
ctx.request_repaint();
}
#[cfg(not(target_arch = "wasm32"))]
self.tick_link_updates(ctx, now);
crate::addons::select::link_status::refresh(self, now);
@@ -351,7 +367,12 @@ impl VectorcraftApp {
crate::ime::close_viewport(self, ctx);
self.ime_context.end_viewport(ctx.viewport_id());
unsaved::finish_pending(self);
if self.file_sheet_open() {
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!({})));
}
} else if self.file_sheet_open() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
self.status(picks::busy());
} else if unsaved::any_dirty(self) {
+4
View File
@@ -404,6 +404,10 @@ impl VectorcraftApp {
if let Err(e) = switched {
self.ui.status = e.to_string();
}
if before != self.session.tool_id() {
// A control gesture cannot resume after another tool has owned the pointer.
self.control_rotate_press = None;
}
// A newly chosen Artboard tool starts on the active artboard (the view's).
if before != "artboard"
&& self.session.tool_id() == "artboard"
+33 -14
View File
@@ -77,6 +77,7 @@ use tool_overlays::{
print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays,
};
pub(crate) use view::animated_zoom;
pub(crate) use view::drag_rotation;
pub use view::fit;
use view::scroll_bars;
#[cfg(test)]
@@ -543,8 +544,9 @@ fn ruler_bands(app: &VectorcraftApp, ui: &Ui, xf: &Xf, (full, rect): (egui::Rect
let painter = ui.painter_at(rect);
if let Some(origin) = origin_preview {
let at = xf.to_screen(origin);
painter.line_segment([pos2(at.x, rect.top()), pos2(at.x, rect.bottom())], Stroke::new(1.0, t.text_dim));
painter.line_segment([pos2(rect.left(), at.y), pos2(rect.right(), at.y)], Stroke::new(1.0, t.text_dim));
let color = dim_on_canvas(t, app.outline_view());
painter.line_segment([pos2(at.x, rect.top()), pos2(at.x, rect.bottom())], Stroke::new(1.0, color));
painter.line_segment([pos2(rect.left(), at.y), pos2(rect.right(), at.y)], Stroke::new(1.0, color));
}
// View › Rulers › Show Video Rulers counts the active artboard in video pixels.
let video = app.ui.view.video_rulers.then(|| crate::dialogs::artboard_options::active_index(app));
@@ -793,8 +795,17 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
}
}
/// The pasteboard, the artboards' shadows and paper, and the outline mode's white artboards, of
/// document `st`, in Outline when `outline`.
/// The canvas color in Outline, whatever the interface brightness and Canvas Color: the paths draw
/// as black hairlines, and the artboards as their edges only.
const OUTLINE_CANVAS: Color32 = Color32::WHITE;
/// The color of the artboards' names and the ruler origin's crosshair in Outline, on
/// [`OUTLINE_CANVAS`].
const OUTLINE_DIM: Color32 = Color32::from_gray(0x4b);
/// The pasteboard and the artboards' shadows and paper of document `st`, or in Outline (`outline`)
/// the whole canvas in [`OUTLINE_CANVAS`], with no paper drawn for the artboards: no Simulate
/// Colored Paper color, no artboard background color, and no paper with View › Hide Artboards.
fn paint_paper(
app: &VectorcraftApp,
st: &vectorcraft_engine::DocState,
@@ -805,6 +816,12 @@ fn paint_paper(
(t, outline): (&Tokens, bool),
) {
let doc = &st.doc;
if outline {
// The art draws in black on white over the pasteboard and the artboards alike, and the
// artboards show as their edges (`artboard_outlines`).
painter.rect_filled(rect, 0.0, OUTLINE_CANVAS);
return;
}
// Pasteboard, artboard shadows and paper (Document Setup: the transparency grid's look, the
// simulated paper colour; a white Background Contents hides the grid).
// An artboard with a background color draws its paper in that color. With Simulate Colored Paper
@@ -815,7 +832,7 @@ fn paint_paper(
// View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038).
let setup = &doc.setup;
painter.rect_filled(rect, 0.0, if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE });
} else if !outline {
} else {
let setup = &doc.setup;
let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent).then(|| checker_texture(ui.ctx(), setup));
let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE };
@@ -833,10 +850,6 @@ fn paint_paper(
}
}
}
} else {
for ab in &doc.artboards {
painter.add(Shape::convex_polygon(xf.quad(ab.rect), Color32::WHITE, Stroke::NONE));
}
}
}
@@ -1007,16 +1020,22 @@ fn artboard_outlines(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf:
let tool_selected = artboards::tool_labelled(app);
let editing_name = ui.data(|d| d.get_temp::<ArtboardNameEdit>(name_edit_id()).map(|e| e.index));
let unlabelled = |i: usize| editing_name == Some(i) || u64::try_from(i).ok().is_some_and(|idx| tool_selected.contains(&idx));
artboard_edges(app, doc, (painter, xf, t), active_ab, unlabelled);
artboard_edges(app, doc, (painter, xf, t), (active_ab, dim_on_canvas(t, app.outline_view())), unlabelled);
}
/// The edges, bleeds, marks and names of `doc`'s artboards, `active_ab` the active one; the
/// artboards `unlabelled` gives are not named.
/// The color of the artboards' names and the ruler origin's crosshair over the pasteboard, or over
/// [`OUTLINE_CANVAS`] in Outline (`outline`).
fn dim_on_canvas(t: &Tokens, outline: bool) -> Color32 {
if outline { OUTLINE_DIM } else { t.text_dim }
}
/// The edges, bleeds, marks and names of `doc`'s artboards, `active_ab` the active one, the names
/// in `label`; the artboards `unlabelled` gives are not named.
fn artboard_edges(
app: &VectorcraftApp,
doc: &vectorcraft_doc::Document,
(painter, xf, t): (&egui::Painter, &Xf, &Tokens),
active_ab: usize,
(active_ab, label): (usize, Color32),
unlabelled: impl Fn(usize) -> bool,
) {
let artboard_tool = app.session.tool_id() == "artboard";
@@ -1034,7 +1053,7 @@ fn artboard_edges(
// At the artboard's own top-left corner, which a rotated view turns away from its
// bounding box's (#1095).
let corner = xf.to_screen(Point::new(ab.rect.x0, ab.rect.y0));
artboard_label(painter, corner, (ab.rect.width() * xf.zoom) as f32, &format!("{:02} - {}", i + 1, ab.name), t.text_dim);
artboard_label(painter, corner, (ab.rect.width() * xf.zoom) as f32, &format!("{:02} - {}", i + 1, ab.name), label);
}
}
}
+1 -7
View File
@@ -337,14 +337,8 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2)
}
}
Drag::RotateView { start_angle, start_rot, snaps } => {
let c = rect.center();
let a = (p.y - c.y).atan2(p.x - c.x) as f64;
let mut deg = start_rot + (a - start_angle).to_degrees();
if snaps && m.shift {
deg = (deg / 15.0).round() * 15.0;
}
if let Some(vm) = app.view_mut() {
vm.rotation = vectorcraft_geom::normalize_deg(deg);
vm.rotation = super::view::drag_rotation(rect.center(), p, start_angle, start_rot, snaps && m.shift);
}
}
Drag::ZoomBox { start } => {
+3 -2
View File
@@ -12,7 +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,
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, pos2, rulers, shows_artboards, textured_quad, vec2,
view_rects,
};
use crate::doc_windows::Win;
use crate::thumb_worker::ThumbWorker;
@@ -315,7 +316,7 @@ pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect)
grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look);
}
if shows_artboards(app) {
artboard_edges(app, &st.doc, (&painter, &xf, &t), v.artboard, |_| false);
artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false);
}
if app.ui.view.guides {
guides_of(app, st, (&painter, &xf, &t), rect);
+218
View File
@@ -210,6 +210,27 @@ fn command_cursor_settings_refresh_hover_cursor_while_view_moves() {
assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Crosshair));
}
/// A script that changes Caps Lock refreshes the pointer when its run ends.
#[test]
fn a_script_run_refreshes_hover_cursor_while_view_moves() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.session.select_tool("pen", vectorcraft_engine::ViewInfo::default()).unwrap();
app.hover_doc = Some(Point::new(200.0, 150.0));
let mods = Mods::default();
let view = vectorcraft_engine::ViewInfo::default();
assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Pen));
app.run("script.run", json!({"source": "vc.run('view.capsLock', {on: true});"})).unwrap();
for _ in 0..1_000 {
if !app.session.script_running() {
break;
}
crate::script_runs::poll(&mut app);
}
assert!(app.session.caps_lock);
assert_eq!(hover_cursor(&mut app, mods, view, false), Some(Cursor::Crosshair));
}
/// #826: in a turned view each ruler still has ticks along its whole length; at 0° the top one
/// reads x where the canvas has it.
#[test]
@@ -4189,6 +4210,203 @@ fn outline_is_per_document_and_new_documents_start_in_preview() {
assert!(app.run("view.outline", json!({})).is_err());
}
/// One headless canvas frame → (the colors of the filled rectangles that cover the canvas, the
/// fills of the shapes laid over an artboard, the artboards' edges drawn, the colors of the
/// artboards' names).
fn canvas_look(app: &mut VectorcraftApp, ctx: &egui::Context) -> (Vec<Color32>, Vec<Color32>, usize, Vec<Color32>) {
let s = shapes(app, ctx);
let canvas = app.canvas_rect.unwrap();
let xf = Xf::new(canvas, app.view().unwrap());
let quads: Vec<Vec<Pos2>> = app.session.active().unwrap().doc.artboards.iter().map(|a| xf.quad(a.rect).to_vec()).collect();
let on = |p: &[Pos2]| quads.iter().any(|q| q.len() == p.len() && q.iter().zip(p).all(|(a, b)| (*a - *b).length() < 0.01));
let covers: Vec<Color32> = s
.iter()
.filter_map(|s| match s {
Shape::Rect(r) if r.rect.contains_rect(canvas) => Some(r.fill),
_ => None,
})
.collect();
let papers: Vec<Color32> = s
.iter()
.filter_map(|s| match s {
Shape::Path(p) if p.fill != Color32::TRANSPARENT && on(&p.points) => Some(p.fill),
_ => None,
})
.collect();
let edges = s.iter().filter(|s| matches!(s, Shape::Path(p) if p.closed && p.fill == Color32::TRANSPARENT && on(&p.points))).count();
let names: Vec<Color32> = s
.iter()
.filter_map(|s| match s {
Shape::Text(t) if names_an_artboard(t.galley.text()) => Some(t.fallback_color),
_ => None,
})
.collect();
(covers, papers, edges, names)
}
/// In Outline, in every interface brightness, color scheme and User Interface › Canvas Color, the
/// whole canvas is white, pasteboard included, so the black outlines of art on the pasteboard show.
/// The artboards draw no paper there, only their edges, and their names draw in a dark gray. In
/// Preview the pasteboard keeps its color and the artboards their white paper.
#[test]
fn outline_draws_on_a_white_canvas_with_artboards_as_edges() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
for brightness in crate::theme::Brightness::ALL {
for scheme in crate::theme::Scheme::ALL {
// Canvas Color: matching the brightness, Dark Gray and Medium Gray, as `prefs_dialog` sets it.
for canvas_color in [None, Some(Color32::from_gray(0x5a)), Some(Color32::from_gray(0x96))] {
let ctx = egui::Context::default();
crate::theme::apply_with(&ctx, brightness, Default::default(), scheme);
if let Some(c) = canvas_color {
let mut t = Tokens::get(&ctx);
t.pasteboard = c;
ctx.data_mut(|d| d.insert_temp(egui::Id::NULL, t));
}
let case = format!("{brightness:?} {scheme:?} {canvas_color:?}");
let pasteboard = Tokens::get(&ctx).pasteboard;
assert_ne!(pasteboard, Color32::WHITE, "{case}");
app.view_mut().unwrap().outline = false;
let (covers, papers, edges, names) = canvas_look(&mut app, &ctx);
assert_eq!(covers.last(), Some(&pasteboard), "{case}: Preview keeps the pasteboard");
assert_eq!(papers, [Color32::WHITE; 2], "{case}: and the artboards' paper");
assert_eq!(edges, 2, "{case}");
assert_eq!(names, [Tokens::get(&ctx).text_dim; 2], "{case}");
app.view_mut().unwrap().outline = true;
let (covers, papers, edges, names) = canvas_look(&mut app, &ctx);
assert_eq!(covers.last(), Some(&Color32::WHITE), "{case}: the canvas is white in Outline");
assert!(!covers.contains(&pasteboard), "{case}: no pasteboard in Outline");
assert!(papers.is_empty(), "{case}: no paper over the artboards in Outline: {papers:?}");
assert_eq!(edges, 2, "{case}: the artboards show as their edges");
assert_eq!(names, [OUTLINE_DIM; 2], "{case}: names readable on white");
}
}
}
}
/// In Outline the canvas stays white with Simulate Colored Paper on, with an artboard's own
/// background color, and with View › Hide Artboards, which in Preview show the paper color, the
/// artboard's color and the paper color over the whole canvas.
#[test]
fn outline_draws_no_colored_paper() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
{
let doc = std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc);
doc.setup.simulate_paper = true;
doc.setup.grid_colors = [vectorcraft_color::Color::rgb(0.9, 0.8, 0.6), vectorcraft_color::Color::rgb(0.5, 0.5, 0.5)];
doc.artboards[1].color = Some(vectorcraft_color::Color::rgb(0.6, 0.8, 1.0));
}
let paper = crate::panels::c32(&app.session.active().unwrap().doc.setup.paper());
let ctx = egui::Context::default();
crate::theme::apply(&ctx, crate::theme::Brightness::Dark);
app.view_mut().unwrap().outline = false;
let (_, papers, _, _) = canvas_look(&mut app, &ctx);
assert_eq!(papers.len(), 2);
assert_eq!(papers[0], paper, "Preview: the simulated paper");
assert_ne!(papers[1], paper, "Preview: the artboard's own color");
app.view_mut().unwrap().outline = true;
let (covers, papers, edges, _) = canvas_look(&mut app, &ctx);
assert_eq!(covers.last(), Some(&Color32::WHITE));
assert!(papers.is_empty(), "{papers:?}");
assert_eq!(edges, 2);
app.ui.view.artboards = false;
app.view_mut().unwrap().outline = false;
let (covers, _, edges, _) = canvas_look(&mut app, &ctx);
assert_eq!(covers.last(), Some(&paper), "Preview with Hide Artboards: the paper over the whole canvas");
assert_eq!(edges, 0);
app.view_mut().unwrap().outline = true;
let (covers, papers, edges, _) = canvas_look(&mut app, &ctx);
assert_eq!(covers.last(), Some(&Color32::WHITE), "Outline with Hide Artboards");
assert!(!covers.contains(&paper));
assert!(papers.is_empty());
assert_eq!(edges, 0);
}
/// A split-view pane or floating window draws its own view's Outline, whatever the current view
/// shows: the white canvas and dark gray artboard names in Outline, and the pasteboard and the
/// theme's names in Preview.
#[test]
fn a_pane_draws_its_own_views_outline() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
crate::doc_windows::new_window(&mut app).unwrap();
let ctx = egui::Context::default();
crate::theme::apply(&ctx, crate::theme::Brightness::Dark);
let t = Tokens::get(&ctx);
let other = (0, 1);
for pane_outline in [true, false] {
crate::doc_windows::view_mut(&mut app, other).unwrap().outline = pane_outline;
app.view_mut().unwrap().outline = !pane_outline;
let cell = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 400.0));
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
panes::pane(&mut app, ui, other, cell);
});
out.textures_delta.clear();
let mut s = vec![];
fn flat(s: Shape, out: &mut Vec<Shape>) {
match s {
Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)),
s => out.push(s),
}
}
out.shapes.into_iter().for_each(|c| flat(c.shape, &mut s));
let fills: Vec<Color32> = s.iter().filter_map(|s| if let Shape::Rect(r) = s { Some(r.fill) } else { None }).collect();
let names: Vec<Color32> = s
.iter()
.filter_map(|s| if let Shape::Text(x) = s { names_an_artboard(x.galley.text()).then_some(x.fallback_color) } else { None })
.collect();
let (canvas, name) = if pane_outline { (Color32::WHITE, OUTLINE_DIM) } else { (t.pasteboard, t.text_dim) };
assert_eq!(fills.first(), Some(&canvas), "pane in Outline: {pane_outline}");
assert_eq!(names, [name; 2], "pane in Outline: {pane_outline}");
}
}
/// While the rulers' origin is dragged out of their corner, its crosshair draws over the canvas in
/// the theme's dim text color in Preview, and in Outline in the dark gray that shows on the white
/// canvas.
#[test]
fn the_ruler_origin_crosshair_shows_on_the_outline_canvas() {
use egui::Event;
for outline in [false, true] {
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.view_mut().unwrap().outline = outline;
let ctx = egui::Context::default();
crate::theme::apply(&ctx, crate::theme::Brightness::Dark);
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let corner = pos2(rect.left() - RULER / 2.0, rect.top() - RULER / 2.0);
let to = rect.center();
let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, &ctx, vec![Event::PointerMoved(corner)]);
frame(&mut app, &ctx, vec![button(corner, true)]);
frame(&mut app, &ctx, vec![Event::PointerMoved(to)]);
let (s, mut delta) = frame_output(&mut app, &ctx);
delta.clear();
let lines: Vec<Color32> = s
.iter()
.filter_map(|s| match s {
Shape::LineSegment { points, stroke }
if (points[0].x - to.x).abs() < 1.5
&& (points[1].x - to.x).abs() < 1.5
&& points[0].y <= rect.top() + 1.0
&& points[1].y >= rect.bottom() - 1.0 =>
{
Some(stroke.color)
}
_ => None,
})
.collect();
let want = if outline { OUTLINE_DIM } else { Tokens::get(&ctx).text_dim };
assert_eq!(lines, [want], "Outline: {outline}");
frame(&mut app, &ctx, vec![button(to, false)]);
}
}
/// #3797: a preferences file saved while View › Outline was an interface setting still loads, with
/// its other view settings, and its Outline value does not put a document in Outline.
#[test]
+10
View File
@@ -1,6 +1,16 @@
use super::drag::{drag_id, drop_press};
use super::{CornerRadius, Drag, Point, Pos2, Rect, SCROLL_BAR, Sense, Stroke, Tokens, Ui, VectorcraftApp, View, Xf, pos2, vec2};
/// The mouse and control-channel Rotate View gestures use the same angle and Shift snapping.
pub(crate) fn drag_rotation(center: Pos2, point: Pos2, start_angle: f64, start_rotation: f64, snap: bool) -> f64 {
let angle = (point.y - center.y).atan2(point.x - center.x) as f64;
let mut degrees = start_rotation + (angle - start_angle).to_degrees();
if snap {
degrees = (degrees / 15.0).round() * 15.0;
}
vectorcraft_geom::normalize_deg(degrees)
}
/// Fit the view (View → Fit Artboard / Fit All / Actual Size, Arrange Tools › Zoom to Selection).
pub fn fit(app: &mut VectorcraftApp, how: &str) {
let Some(rect) = app.canvas_rect else {
+12 -6
View File
@@ -179,12 +179,18 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) {
}
right = left - gap;
}
let busy: Vec<&str> = app
.background
.jobs
.iter()
.filter(|j| !j.label.is_empty() && !j.cancelled())
.map(|j| j.label.as_str())
let script = app.session.script_running().then_some("Running a script");
if script.is_some() {
let left = (right - 52.0).max(area.left());
let stop = egui::Rect::from_min_max(egui::pos2(left, area.top() + 1.0), egui::pos2(right, area.bottom() - 1.0));
if ui.put(stop, egui::Button::new(tl!("Stop")).small()).clicked() {
app.session.script_interrupt().set();
}
right = left - gap;
}
let busy: Vec<&str> = script
.into_iter()
.chain(app.background.jobs.iter().filter(|j| !j.label.is_empty() && !j.cancelled()).map(|j| j.label.as_str()))
.chain(app.opening.pending.iter().map(|p| p.label.as_str()))
.chain(app.placing.pending.iter().map(|p| p.label.as_str()))
.collect();
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more