mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 17:05:55 +01:00
M5: reconcile upstream documentation with thread overlay filtering
This commit is contained in:
commit
e56efa8d6e
136 files changed
+12308
-356
No files matched your search
Generated
+3
-2
@@ -1070,7 +1070,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1080,6 +1080,7 @@ dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
"plist",
|
||||
"rustix 1.1.6",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1096,7 +1097,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
|
||||
+2
-2
@@ -21,9 +21,9 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
|
||||
@@ -870,10 +870,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
on_type_path(n, t, p, opt.tol).then_some(HitKind::Outline)
|
||||
}
|
||||
// An image is hit within its frame (on the frame's edge only with Selection by Path Only,
|
||||
// #3291), and where its own fills and strokes paint ([`image_paint`]) except in outline
|
||||
// mode.
|
||||
// #3291, and in outline mode where the frame is all that is drawn, #6437), and where its
|
||||
// own fills and strokes paint ([`image_paint`]) except in outline mode.
|
||||
NodeKind::Image(im) => {
|
||||
if opt.path_only {
|
||||
if opt.path_only || (opt.outline && !symbols.document().setup.outline_images) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let mut frame = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1);
|
||||
frame.apply_affine(im.xf);
|
||||
@@ -909,6 +909,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if stroke_contains(&bp, 0.0, opt.tol, p) {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
// Outline mode draws the mesh lines, not the colours between them (#6437).
|
||||
if opt.outline {
|
||||
return stroke_contains(&m.lines().to_bezpath(), 0.0, opt.tol, p).then_some(HitKind::Outline);
|
||||
}
|
||||
(!opt.path_only && fill_contains(&bp, vectorcraft_geom::FillRule::NonZero, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
_ => None,
|
||||
|
||||
@@ -880,6 +880,45 @@ fn path_only_picks_paths_through_images() {
|
||||
assert_eq!(hit(image_edge, path_only), Some(image), "path only: the image's frame");
|
||||
}
|
||||
|
||||
/// #6437: in outline mode an image is drawn as its frame and a gradient mesh as its mesh lines,
|
||||
/// so a click inside them, on the outline of a path behind, picks that path, and a click on the
|
||||
/// frame or a mesh line picks the image or the mesh. In Preview they cover the path as before,
|
||||
/// and an image whose pixels show in outline mode (Show Images in Outline Mode) still does.
|
||||
#[test]
|
||||
fn outline_mode_picks_paths_through_images_and_meshes() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (path, image, under, mesh) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(path, shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
let xf = vectorcraft_geom::Affine::translate((10.0, 10.0));
|
||||
let im = crate::ImageObject { key: "k".into(), width: 80, height: 80, xf, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(l), 1, Node::new(image, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
d.insert(Some(l), 2, Node::path(under, shapes::rectangle(Rect::new(120.0, 120.0, 160.0, 160.0)), Appearance::default_art())).unwrap();
|
||||
let area = shapes::rectangle(Rect::new(110.0, 110.0, 190.0, 190.0));
|
||||
let m = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap();
|
||||
d.insert(Some(l), 3, Node::new(mesh, NodeKind::Mesh(m))).unwrap();
|
||||
let outline = HitOptions { outline: true, ..Default::default() };
|
||||
let hit = |d: &Document, p: Point, opt| hit_test(d, p, opt).map(|h| h.leaf);
|
||||
// The image: the path's edge and the inside, then the frame.
|
||||
let (path_edge, inside, frame) = (Point::new(20.5, 40.0), Point::new(80.0, 80.0), Point::new(89.5, 50.0));
|
||||
assert_eq!(hit(&d, path_edge, HitOptions::default()), Some(image), "Preview: the image covers the path");
|
||||
assert_eq!(hit(&d, inside, HitOptions::default()), Some(image));
|
||||
assert_eq!(hit(&d, path_edge, outline), Some(path), "outline: the path through the image");
|
||||
assert_eq!(hit(&d, inside, outline), None, "outline: not inside the image");
|
||||
assert_eq!(hit(&d, frame, outline), Some(image), "outline: the image's frame");
|
||||
// The mesh: the path's edge and the inside, then its edge and a mesh line inside it.
|
||||
let (under_edge, inside, edge, line) = (Point::new(120.5, 130.0), Point::new(130.0, 170.0), Point::new(189.5, 130.0), Point::new(150.0, 170.0));
|
||||
assert_eq!(hit(&d, under_edge, HitOptions::default()), Some(mesh), "Preview: the mesh covers the path");
|
||||
assert_eq!(hit(&d, inside, HitOptions::default()), Some(mesh));
|
||||
assert_eq!(hit(&d, under_edge, outline), Some(under), "outline: the path through the mesh");
|
||||
assert_eq!(hit(&d, inside, outline), None, "outline: not between the mesh lines");
|
||||
assert_eq!(hit(&d, edge, outline), Some(mesh), "outline: the mesh's edge");
|
||||
assert_eq!(hit(&d, line, outline), Some(mesh), "outline: a mesh line");
|
||||
// Show Images in Outline Mode: the image's pixels are drawn, and it covers the path again.
|
||||
d.setup.outline_images = true;
|
||||
assert_eq!(hit(&d, path_edge, outline), Some(image));
|
||||
}
|
||||
|
||||
/// Type Object Selection by Path Only: point type is picked on its baseline, area type on its
|
||||
/// frame and type on a path on its path, no longer anywhere in its bounds.
|
||||
#[test]
|
||||
|
||||
@@ -25,17 +25,33 @@ const MAX_OVERLAP_TESTS: usize = 1 << 22;
|
||||
/// The width of the stroke around each face that covers the seams between faces.
|
||||
const SEAM_WIDTH: f64 = 0.75;
|
||||
|
||||
/// About the bytes one copy of `paint` takes.
|
||||
/// About the bytes one copy of `paint` takes, with the strings it owns (swatch and pattern names).
|
||||
fn paint_bytes(paint: &Paint) -> usize {
|
||||
use std::mem::size_of;
|
||||
use vectorcraft_doc::color::{FreeformPoint, GradientStop};
|
||||
let own = size_of::<Paint>();
|
||||
let Paint::Gradient(g) = paint else { return own };
|
||||
let freeform = g
|
||||
.freeform
|
||||
.as_ref()
|
||||
.map_or(0, |f| f.points.len() * size_of::<FreeformPoint>() + f.lines.iter().map(|l| l.len() * size_of::<usize>()).sum::<usize>());
|
||||
own + size_of::<vectorcraft_doc::color::GradientPaint>() + g.gradient.stops.len() * size_of::<GradientStop>() + freeform
|
||||
let name = |s: &Option<String>| s.as_ref().map_or(0, String::len);
|
||||
let g = match paint {
|
||||
Paint::Solid { swatch, .. } => return own + name(swatch),
|
||||
Paint::Pattern { pattern, .. } => return own + pattern.len(),
|
||||
Paint::Gradient(g) => g,
|
||||
_ => return own,
|
||||
};
|
||||
let freeform = g.freeform.as_ref().map_or(0, |f| {
|
||||
// Each line is a Vec: its header too, not only its indices.
|
||||
f.points.len() * size_of::<FreeformPoint>()
|
||||
+ f.lines.len() * size_of::<Vec<usize>>()
|
||||
+ f.lines.iter().map(|l| l.len() * size_of::<usize>()).sum::<usize>()
|
||||
});
|
||||
let stops: usize = g.gradient.stops.iter().map(|s| size_of::<GradientStop>() + name(&s.swatch)).sum();
|
||||
own + size_of::<vectorcraft_doc::color::GradientPaint>() + name(&g.swatch) + stops + freeform
|
||||
}
|
||||
|
||||
/// Add `copies` copies of `paint` to the running byte total `used`; whether it still fits within
|
||||
/// [`MAX_PAINT_COPIES`] (for the solid surfaces, whose items' copies count together).
|
||||
pub(crate) fn paint_copies_add(used: &mut usize, copies: usize, paint: &Paint) -> bool {
|
||||
*used = used.saturating_add(copies.saturating_mul(paint_bytes(paint)));
|
||||
*used <= MAX_PAINT_COPIES
|
||||
}
|
||||
|
||||
fn visible(fx: &[Effect]) -> bool {
|
||||
|
||||
@@ -275,23 +275,30 @@ impl Scope {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `scope` draw its members' faces other than plainly: does it have an opacity mask or a
|
||||
/// blending mode other than Normal?
|
||||
fn composites(scope: &Scope) -> bool {
|
||||
scope.mask.is_some() || scope.blend != BlendMode::Normal
|
||||
}
|
||||
|
||||
/// `surfaces`, each with the scopes of the member it was built from, in groups with the opacity
|
||||
/// masks of those scopes, so each mask applies to the faces of the members it holds. The members'
|
||||
/// opacity is already in their paint ([`Profile::opacity`]), so these groups are opaque.
|
||||
/// masks and blending modes of those scopes, so each applies to the faces of the members it holds.
|
||||
/// The members' opacity is already in their paint ([`Profile::opacity`]), so these groups are
|
||||
/// opaque.
|
||||
fn masked(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>) -> Vec<Arc<Node>> {
|
||||
let masks: Vec<(Vec<Scope>, Arc<Node>)> = surfaces
|
||||
.into_iter()
|
||||
.map(|(scopes, s)| {
|
||||
let masks = scopes.iter().filter(|s| s.mask.is_some()).map(|s| Scope { opacity: 1.0, blend: BlendMode::Normal, ..s.clone() }).collect();
|
||||
let masks = scopes.iter().filter(|s| composites(s)).map(|s| Scope { opacity: 1.0, ..s.clone() }).collect();
|
||||
(masks, s)
|
||||
})
|
||||
.collect();
|
||||
crate::revolve::scoped(id, masks.iter().map(|(scopes, s)| (scopes.as_slice(), s.clone())).collect(), 0)
|
||||
}
|
||||
|
||||
/// Does any of `shapes` sit in a scope with an opacity mask?
|
||||
/// Does any of `shapes` sit in a scope with an opacity mask or a blending mode other than Normal?
|
||||
fn has_masks(shapes: &[Profile]) -> bool {
|
||||
shapes.iter().any(|s| s.scopes.iter().any(|s| s.mask.is_some()))
|
||||
shapes.iter().any(|s| s.scopes.iter().any(composites))
|
||||
}
|
||||
|
||||
/// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint
|
||||
@@ -484,6 +491,21 @@ fn paint_of(item: &AppearanceItem, member: f32) -> (Paint, f32, BlendMode) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `item`'s paint, borrowed (for checks that must not copy it).
|
||||
fn paint_ref(item: &AppearanceItem) -> &Paint {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => &f.paint,
|
||||
AppearanceItem::Stroke(s) => &s.paint,
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), six when colored
|
||||
/// lights give each facet derived paints (`lighting::solid_surface`).
|
||||
fn facet_copies(facets: &[Facet], paint: &Paint, colored: bool) -> usize {
|
||||
let derived = colored && paint.color().is_some() && facets.iter().any(|f| f.rgb_gradient.is_some());
|
||||
facets.len().saturating_mul(if derived { 6 } else { 2 })
|
||||
}
|
||||
|
||||
/// The area `item` paints on `path`, and the rule that fills it: the path itself for a fill, the
|
||||
/// stroke's outline (whose contours nest as its holes do) for a stroke.
|
||||
fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, FillRule) {
|
||||
@@ -535,14 +557,17 @@ pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile
|
||||
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
|
||||
/// a surface one composite or masks it, their faces are drawn in one back-to-front order (where
|
||||
/// depths tie, as for the caps turned toward the viewer, in the order of the appearance);
|
||||
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask, or that of
|
||||
/// a group it is in, masks the surfaces of the members it holds ([`masked`]).
|
||||
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
|
||||
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
|
||||
/// ([`masked`]).
|
||||
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
let b = union_bounds(shapes)?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let classic = fx.id == CLASSIC_EXTRUDE;
|
||||
let colored = !classic && view_options(&p).has_colored_lights();
|
||||
let masks = has_masks(shapes);
|
||||
// The paint copies of every solid together: past the allowance the source path is drawn.
|
||||
let mut paint_bytes = 0usize;
|
||||
if fx.id == ROTATE {
|
||||
// Every part turns about the centre of the object's own bounds (a group's members about
|
||||
// the centre of theirs), so they stay together.
|
||||
@@ -552,6 +577,9 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
|
||||
let (paint, opacity, blend) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
let f = facets(ROTATE, &area, rule, b, &p).ok()?;
|
||||
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
|
||||
return None;
|
||||
}
|
||||
out.push((s.scopes.as_slice(), Arc::new(surface(n, f, &paint, opacity, blend, colored))));
|
||||
}
|
||||
}
|
||||
@@ -569,6 +597,7 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
|
||||
for ((item, opacity, _, _, scopes), f) in parts.iter().zip(built) {
|
||||
let item: &AppearanceItem = item;
|
||||
match f {
|
||||
Ok(f) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => return None,
|
||||
Ok(f) => solids.push((item, *opacity, *scopes, f)),
|
||||
// A stroke's outline past the limits is left out; the fill's solid still draws.
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
|
||||
@@ -523,6 +523,52 @@ fn an_opacity_mask_on_a_member_or_a_group_in_a_three_d_group_masks_its_solids()
|
||||
}
|
||||
}
|
||||
|
||||
/// The leaf faces of `art` that draw something, each with its visual bounds and whether it is drawn
|
||||
/// inside a group with blending mode `mode`.
|
||||
fn faces_in_mode(art: &Node, mode: BlendMode) -> Vec<(Rect, bool)> {
|
||||
fn walk(n: &Node, inside: bool, mode: BlendMode, out: &mut Vec<(Rect, bool)>) {
|
||||
let inside = inside || (n.children().is_some() && n.blend == mode);
|
||||
match n.children() {
|
||||
Some(children) => children.iter().for_each(|c| walk(c, inside, mode, out)),
|
||||
None => out.extend(n.visual_bounds().map(|b| (b, inside))),
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(art, false, mode, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blending_mode_on_a_member_or_a_group_in_a_three_d_group_applies_to_its_solids() {
|
||||
let d = document();
|
||||
let mode = |mut n: Node, mode: BlendMode| {
|
||||
n.blend = mode;
|
||||
n
|
||||
};
|
||||
let other = || Arc::new(rect(91, 600.0, 600.0, 650.0, 650.0, 0.0));
|
||||
let member = || rect(1, 100.0, 100.0, 150.0, 200.0, 2.0);
|
||||
let cases = [
|
||||
("a multiplied member", Node::group(NodeId(90), vec![Arc::new(mode(member(), BlendMode::Multiply)), other()])),
|
||||
(
|
||||
"a member of a multiplied group",
|
||||
Node::group(NodeId(90), vec![Arc::new(mode(Node::group(NodeId(80), vec![Arc::new(member())]), BlendMode::Multiply)), other()]),
|
||||
),
|
||||
];
|
||||
for (what, g) in cases {
|
||||
for id in TYPES {
|
||||
let g = with(g.clone(), id, json!({}));
|
||||
// The member spans y 100 to 200 and the other member y 600 to 650, and every type keeps
|
||||
// its faces near those heights (Revolve turns them around a vertical axis): a face whose
|
||||
// center is above y 400 belongs to the member.
|
||||
let (mine, others): (Vec<_>, Vec<_>) =
|
||||
faces_in_mode(&art(&d, &g, id).expect("drawn"), BlendMode::Multiply).into_iter().partition(|(b, _)| b.center().y < 400.0);
|
||||
assert!(!mine.is_empty() && !others.is_empty(), "{id}: both members draw faces ({} and {})", mine.len(), others.len());
|
||||
assert!(mine.iter().all(|(_, m)| *m), "{id}: every face of {what} is drawn in Multiply");
|
||||
assert!(others.iter().all(|(_, m)| !m), "{id}: no face of the other member is drawn in Multiply");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolved_objects_and_groups_in_a_three_d_group_keep_their_geometry_effects() {
|
||||
let mut d = document();
|
||||
|
||||
@@ -14,6 +14,10 @@ use super::{ARCLEN_ACCURACY, kink, push_seg, segments, subpaths, tangent};
|
||||
|
||||
/// More dashes than this (a tiny pattern on a long path) draws the line solid instead.
|
||||
const MAX_DASHES: f64 = 200_000.0;
|
||||
/// Pattern entries walked in all (every subpath and every corner restart starts the pattern over, and
|
||||
/// zero-length entries cost no path length, so a long pattern is walked in full even on a short
|
||||
/// run); past this the line is drawn solid. About 100x what real art needs.
|
||||
const MAX_STEPS: f64 = 20_000_000.0;
|
||||
/// A pattern whose longest entry is shorter than this can't advance along the path (each entry
|
||||
/// ends within the generator's tolerance of where it starts), so it draws the line solid.
|
||||
const MIN_ENTRY: f64 = 1e-6;
|
||||
@@ -80,6 +84,10 @@ pub fn dash_kept(bp: &BezPath, d: &Dash, keep: &dyn Fn(&PathSeg) -> bool) -> Opt
|
||||
if plans.iter().map(|p| p.periods).sum::<f64>() * pat.len() as f64 > MAX_DASHES {
|
||||
return None;
|
||||
}
|
||||
let restarts = |p: &Plan| p.restart.iter().filter(|r| **r).count() as f64;
|
||||
if plans.iter().map(|p| (p.periods.ceil().max(1.0) + restarts(p)) * pat.len() as f64).sum::<f64>() > MAX_STEPS {
|
||||
return None;
|
||||
}
|
||||
// Where an exact pattern starts: `offset` into it.
|
||||
let mut off = d.offset.rem_euclid(period);
|
||||
let mut ix0 = 0;
|
||||
@@ -89,8 +97,13 @@ pub fn dash_kept(bp: &BezPath, d: &Dash, keep: &dyn Fn(&PathSeg) -> bool) -> Opt
|
||||
}
|
||||
let phase = Phase { ix: ix0, rem: pat[ix0] - off, on: ix0 % 2 == 0 };
|
||||
let mut out = Dashed::default();
|
||||
// The estimates above trust the fitted scales; this counts the pattern entries actually walked,
|
||||
// so entries that fit down to nothing can't keep a subpath looping.
|
||||
let mut budget = MAX_STEPS as usize;
|
||||
for plan in &plans {
|
||||
dash_subpath(&mut out, plan, &pat, phase, keep);
|
||||
if !dash_subpath(&mut out, plan, &pat, phase, keep, &mut budget) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
@@ -183,7 +196,8 @@ impl Piece {
|
||||
}
|
||||
}
|
||||
|
||||
fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep: &dyn Fn(&PathSeg) -> bool) {
|
||||
/// Dash one subpath; `false` when `budget` (pattern entries left to walk, shared by all subpaths) runs out.
|
||||
fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep: &dyn Fn(&PathSeg) -> bool, budget: &mut usize) -> bool {
|
||||
let first_dot = out.dots.len();
|
||||
let total: f64 = plan.lens.iter().sum();
|
||||
// Fraction of the subpath's length at `x` along the plan.
|
||||
@@ -244,6 +258,8 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep:
|
||||
push_dot(out, first_dot, Dot { at: seg.eval(t), dir: tangent(seg, t), t: frac(acc + end) });
|
||||
}
|
||||
}
|
||||
let Some(rest) = budget.checked_sub(1) else { return false };
|
||||
*budget = rest;
|
||||
cuts += 1;
|
||||
s = end;
|
||||
ph.ix = (ph.ix + 1) % pat.len();
|
||||
@@ -273,7 +289,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep:
|
||||
write(&mut out.path, &d.segs);
|
||||
out.path.close_path();
|
||||
out.spans.push((frac(0.0), frac(0.0) + 1.0));
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
if starts_on && ends_on && dashes.len() > 1 {
|
||||
// The dash running through the start point is one dash.
|
||||
@@ -291,6 +307,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep:
|
||||
let t0 = frac(d.start);
|
||||
out.spans.push((t0, if total > 0.0 { t0 + (d.end - d.start) / total } else { t0 }));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Add `dot` unless the subpath's last dot (from index `first`) is already there: a run ending on
|
||||
|
||||
@@ -222,3 +222,17 @@ fn smooth_points_of_curves_stay_smooth_with_any_join() {
|
||||
assert!((a - want).abs() / want < 0.005, "{join:?}: {a} vs {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_pattern_restarted_on_many_short_subpaths_draws_solid() {
|
||||
// Each subpath walks the zero-length entries in full although it is far shorter than a period.
|
||||
let mut pattern = vec![0.0; 2000];
|
||||
pattern[0] = 1.0;
|
||||
let mut b = BezPath::new();
|
||||
for i in 0..20_000 {
|
||||
b.move_to((i as f64 * 2.0, 0.0));
|
||||
b.line_to((i as f64 * 2.0 + 0.01, 0.0));
|
||||
}
|
||||
let d = Dash { pattern, offset: 0.0, align_corners: false };
|
||||
assert!(dash(&b, &d).is_none());
|
||||
}
|
||||
@@ -1101,8 +1101,9 @@ pub fn with_id(xml: &str, id: &str) -> Option<String> {
|
||||
let f = filter_element(&doc).ok()?;
|
||||
let at = f.attributes().find(|a| a.name() == "id" && a.namespace().is_none())?.range_value();
|
||||
let (start, end) = (at.start.checked_sub(head)?, at.end.checked_sub(head)?);
|
||||
// The value may sit in single quotes: those are escaped too.
|
||||
let id = escaped(id).replace('\'', "'");
|
||||
// The value may sit in single quotes: those are escaped too. A tab, line feed or carriage
|
||||
// return is written as a character reference, which attribute-value normalization keeps.
|
||||
let id = escaped(id).replace('\'', "'").replace('\t', "	").replace('\n', " ").replace('\r', " ");
|
||||
Some(format!("{}{}{}", xml.get(..start)?, id, xml.get(end..)?))
|
||||
}
|
||||
|
||||
|
||||
@@ -218,34 +218,66 @@ fn visible(sources: &[TrapSource]) -> Vec<PathData> {
|
||||
/// The pairs `(i, j)`, `i < j`, in ascending order, of `rects` (`None`: left out) that come within
|
||||
/// `reach_x` of each other across x and `reach_y` across y. A sweep over the rects sorted by their
|
||||
/// left edge, so shapes spread over the page cost about one check each rather than one per pair.
|
||||
fn near_pairs(rects: &[Option<Rect>], reach_x: f64, reach_y: f64) -> Vec<(usize, usize)> {
|
||||
/// `None` when there are more than [`MAX_NEAR_PAIRS`] (many shapes all within reach of each other
|
||||
/// make the pair list grow with the square of their count) or the sweep examines more than
|
||||
/// `MAX_NEAR_SCAN` pairs (many shapes sharing an x range, far apart in y).
|
||||
fn near_pairs(rects: &[Option<Rect>], reach_x: f64, reach_y: f64) -> Option<Vec<(usize, usize)>> {
|
||||
near_pairs_within(rects, reach_x, reach_y, MAX_NEAR_SCAN)
|
||||
}
|
||||
|
||||
fn near_pairs_within(rects: &[Option<Rect>], reach_x: f64, reach_y: f64, max_scan: usize) -> Option<Vec<(usize, usize)>> {
|
||||
let mut order: Vec<(usize, Rect)> = rects.iter().enumerate().filter_map(|(i, r)| r.map(|r| (i, r))).collect();
|
||||
order.sort_unstable_by(|a, b| a.1.x0.total_cmp(&b.1.x0).then(a.0.cmp(&b.0)));
|
||||
let mut pairs = vec![];
|
||||
let mut scanned = 0usize;
|
||||
for (k, &(i, a)) in order.iter().enumerate() {
|
||||
// Later rects start at or right of `a`, so only how far right they start can rule them out.
|
||||
for &(j, b) in order[k + 1..].iter().take_while(|(_, b)| b.x0 <= a.x1 + reach_x) {
|
||||
// Rects sharing an x range but far apart in y are examined without being stored.
|
||||
scanned += 1;
|
||||
if scanned > max_scan {
|
||||
return None;
|
||||
}
|
||||
if b.y0 <= a.y1 + reach_y && a.y0 <= b.y1 + reach_y {
|
||||
if pairs.len() >= MAX_NEAR_PAIRS {
|
||||
return None;
|
||||
}
|
||||
pairs.push((i.min(j), i.max(j)));
|
||||
}
|
||||
}
|
||||
}
|
||||
pairs.sort_unstable();
|
||||
pairs
|
||||
Some(pairs)
|
||||
}
|
||||
|
||||
/// Most pairs the sweep in `near_pairs` examines, stored or not (a plain bounds check each).
|
||||
const MAX_NEAR_SCAN: usize = 1 << 27;
|
||||
|
||||
/// Most candidate pairs one trap evaluation keeps; past it no traps are made (the art draws as is).
|
||||
/// Each pair costs a boolean trap band, so real art stays far below this.
|
||||
pub const MAX_NEAR_PAIRS: usize = 1 << 20;
|
||||
|
||||
/// The traps between `sources` (back to front) with options `o`: for each two sources of
|
||||
/// different solid colours whose visible parts meet, the strip of the darker one's visible part
|
||||
/// next to the lighter one's (the other way round with [`TrapOptions::reverse`]), painted per
|
||||
/// [`trap_paint`]. Empty when no visible edges of different colours meet.
|
||||
/// [`trap_paint`]. Empty when no visible edges of different colours meet, or when there are more
|
||||
/// than [`MAX_NEAR_PAIRS`] candidate pairs or the pair scan is too long (see [`try_traps`] to tell
|
||||
/// those apart).
|
||||
pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec<TrapPiece> {
|
||||
try_traps(sources, o).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`traps`], but `None` when there are more than [`MAX_NEAR_PAIRS`] candidate pairs or the scan for
|
||||
/// them is too long (`MAX_NEAR_SCAN` pairs examined), as opposed to
|
||||
/// `Some` of an empty list when no edges meet.
|
||||
pub fn try_traps(sources: &[TrapSource], o: &TrapOptions) -> Option<Vec<TrapPiece>> {
|
||||
let colors: Vec<Option<Color>> = sources.iter().map(|s| trap_color(&s.fill)).collect();
|
||||
if colors.iter().flatten().count() < 2 {
|
||||
return vec![];
|
||||
return Some(vec![]);
|
||||
}
|
||||
let (w, r) = (o.thickness, o.height_width);
|
||||
if !(w.is_finite() && w > 0.0 && r.is_finite() && r > 0.0) {
|
||||
return vec![]; // `trap_band` cuts nothing with these.
|
||||
return Some(vec![]); // `trap_band` cuts nothing with these.
|
||||
}
|
||||
let vis = visible(sources);
|
||||
// Only pairs whose visible parts come within the trap's reach can trap (`trap_band` rejects
|
||||
@@ -257,7 +289,8 @@ pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec<TrapPiece> {
|
||||
let extent = rects.iter().flatten().flat_map(|b| [b.x0, b.y0, b.x1, b.y1]).fold(0.0_f64, |m, v| m.max(v.abs()));
|
||||
let hair = 1e-9 * (1.0 + extent + w * r.max(1.0));
|
||||
let mut out = vec![];
|
||||
for (i, j) in near_pairs(&rects, w + hair, w * r + hair) {
|
||||
let pairs = near_pairs(&rects, w + hair, w * r + hair)?;
|
||||
for (i, j) in pairs {
|
||||
let (Some(ci), Some(cj)) = (colors[i], colors[j]) else { continue };
|
||||
if vis[i].is_empty() || vis[j].is_empty() || same_color(&sources[i].fill, &sources[j].fill, ci, cj) {
|
||||
continue;
|
||||
@@ -276,7 +309,7 @@ pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec<TrapPiece> {
|
||||
let Some(color) = colors[from] else { continue };
|
||||
out.push(TrapPiece { path: band, paint: trap_paint(&sources[from].fill, color, o), from, into });
|
||||
}
|
||||
out
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A trap's appearance: one overprinting fill of `paint`, no stroke.
|
||||
@@ -379,10 +412,19 @@ mod tests {
|
||||
assert!(near(po::area(&t[0].path, FillRule::NonZero), 22.0 * 22.0 - 400.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pair_scan_is_bounded_even_when_no_pair_is_near() {
|
||||
// Eleven rects share an x range but lie far apart in y: 55 pairs are examined, none stored.
|
||||
let rects: Vec<Option<Rect>> = (0..11).map(|k| Some(Rect::new(0.0, k as f64 * 1000.0, 10.0, k as f64 * 1000.0 + 10.0))).collect();
|
||||
assert_eq!(near_pairs_within(&rects, 1.0, 1.0, 100), Some(vec![]));
|
||||
assert_eq!(near_pairs_within(&rects, 1.0, 1.0, 54), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_trap_without_adjoining_edges_of_different_colours() {
|
||||
let apart = vec![src(Rect::new(0.0, 0.0, 10.0, 10.0), yellow()), src(Rect::new(30.0, 0.0, 40.0, 10.0), blue())];
|
||||
assert!(traps(&apart, &TrapOptions::default()).is_empty());
|
||||
assert_eq!(try_traps(&apart, &TrapOptions::default()).map(|t| t.len()), Some(0), "no edges meet: empty, not over the cap");
|
||||
let same = vec![src(Rect::new(0.0, 0.0, 10.0, 10.0), blue()), src(Rect::new(10.0, 0.0, 20.0, 10.0), blue())];
|
||||
assert!(traps(&same, &TrapOptions::default()).is_empty());
|
||||
let mut unfilled = abutting();
|
||||
@@ -431,10 +473,13 @@ mod tests {
|
||||
fn only_shapes_within_reach_are_paired() {
|
||||
let s = many_apart_and_one_abutting();
|
||||
let rects: Vec<Option<Rect>> = s.iter().map(|t| t.path.bounds()).collect();
|
||||
assert_eq!(near_pairs(&rects, 1.0, 1.0), vec![(0, 2000)], "the squares 10 pt apart are never paired");
|
||||
assert_eq!(near_pairs(&rects, 1.0, 1.0), Some(vec![(0, 2000)]), "the squares 10 pt apart are never paired");
|
||||
// Reaching 10 pt, neighbours in a row pair, in ascending order; left-out rects never do.
|
||||
let row: Vec<Option<Rect>> = [3, 1, 0, 2].iter().map(|&k| s[k].path.bounds()).chain([None]).collect();
|
||||
assert_eq!(near_pairs(&row, 10.0, 10.0), vec![(0, 3), (1, 2), (1, 3)]);
|
||||
assert_eq!(near_pairs(&row, 10.0, 10.0), Some(vec![(0, 3), (1, 2), (1, 3)]));
|
||||
// Past the allowance the pair list stops growing instead of being built.
|
||||
let packed = vec![Some(Rect::new(0.0, 0.0, 1.0, 1.0)); 1500];
|
||||
assert_eq!(near_pairs(&packed, 1.0, 1.0), None);
|
||||
let t = traps(&s, &TrapOptions { thickness: 1.0, ..Default::default() });
|
||||
assert_eq!(t.len(), 1, "only the abutting pair traps");
|
||||
assert_eq!((t[0].from, t[0].into), (2000, 0));
|
||||
|
||||
@@ -774,8 +774,9 @@ fn divide_dashes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
let only = (segs.len() < sp.segment_count()).then_some(&segs);
|
||||
let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made))
|
||||
.ok_or_else(|| bad(C, "that makes too many pieces (at most 100000): make the dashes longer"))?;
|
||||
let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made)).ok_or_else(|| {
|
||||
bad(C, "that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer")
|
||||
})?;
|
||||
made += out.len();
|
||||
for (piece, kind) in out.into_iter().filter(|(_, k)| !(remove_gaps && *k == pt::Piece::Gap)) {
|
||||
dashes += usize::from(kind == pt::Piece::Dash);
|
||||
@@ -825,7 +826,7 @@ fn dashed_paths(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
|
||||
fn expand_dashes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.pathtools.expandDashes";
|
||||
let too_many = || bad(C, "that makes too many pieces (at most 100000): make the dashes longer");
|
||||
let too_many = || bad(C, "that makes too many pieces (at most 100000) or dash steps: simplify the dash pattern or make the dashes longer");
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Each dashed path and its dashes, as the canvas draws them.
|
||||
|
||||
@@ -496,7 +496,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// nothing to apply is no edit, and a click that only applies brushes the document has is
|
||||
// named for that.
|
||||
let mut probe = (*st.doc).clone();
|
||||
let imported = clip.import_into(&mut probe, &choices, false);
|
||||
let imported = clip.import_into(&mut probe, &choices, false)?;
|
||||
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
|
||||
let paths = if apply { brush_targets(&st.doc, &roots(s, p)?) } else { vec![] };
|
||||
let paint = stroke_paint(s);
|
||||
|
||||
@@ -28,7 +28,7 @@ use vectorcraft_doc::{
|
||||
use super::super::brushsym::{set_natural_size, stored_natural_size};
|
||||
|
||||
use super::super::patterncmds::add_pattern;
|
||||
use super::super::{Result, bad, unique_name};
|
||||
use super::super::{EngineError, Result, bad, unique_name};
|
||||
use super::Clipboard;
|
||||
|
||||
/// A resource kind objects refer to (graphic styles by id, the others by name).
|
||||
@@ -165,6 +165,23 @@ fn node_filters(n: &Node, out: &mut BTreeSet<(String, String)>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The names the SVG filter effects of appearance `a` give (its own and its fills' and strokes').
|
||||
fn appearance_filter_names(a: &Appearance, out: &mut BTreeSet<String>) {
|
||||
let items = a.items.iter().flat_map(|i| i.effects().iter());
|
||||
let named = a.effects.iter().chain(items).filter(|e| e.id == Appearance::SVG_FILTER);
|
||||
out.extend(named.filter_map(|e| e.params.get("name").and_then(Value::as_str)).map(str::to_string));
|
||||
}
|
||||
|
||||
/// The names the SVG filter effects in the subtree of `n` give (opacity-mask art included).
|
||||
fn node_filter_names(n: &Node, out: &mut BTreeSet<String>) {
|
||||
n.walk(&mut |m| {
|
||||
appearance_filter_names(&m.appearance, out);
|
||||
if let Some(mask) = &m.extras().mask {
|
||||
node_filter_names(&mask.art, out);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A global or spot colour of its own (not a tint of another swatch): what colours link to.
|
||||
fn is_base(w: &Swatch) -> bool {
|
||||
(w.global || w.spot) && matches!(w.paint, Paint::Solid { swatch: None, .. })
|
||||
@@ -1038,8 +1055,9 @@ impl Clipboard {
|
||||
}
|
||||
|
||||
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
|
||||
/// pasted copies relink to them.
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Imported {
|
||||
/// pasted copies relink to them. An error, with `d` unchanged, when a pasted SVG filter finds no
|
||||
/// free name ([`Self::filter_links`]).
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
|
||||
self.import_used(d, &self.used(), choices, same_doc, false)
|
||||
}
|
||||
|
||||
@@ -1048,9 +1066,9 @@ impl Clipboard {
|
||||
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
|
||||
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
|
||||
/// of definitions that use each other is matched on its own ([`loop_groups`]).
|
||||
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Imported {
|
||||
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Result<Imported> {
|
||||
let mut out = Imported::default();
|
||||
out.relink.filters = self.filter_links(d, same_doc);
|
||||
out.relink.filters = self.filter_links(d, same_doc)?;
|
||||
self.import_images(d, used, same_doc, &mut out);
|
||||
self.import_swatches(d, used, choices, same_doc, &mut out);
|
||||
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
|
||||
@@ -1213,16 +1231,16 @@ impl Clipboard {
|
||||
&& out.relink.styles.is_empty()
|
||||
&& out.relink.colors.is_empty()
|
||||
&& used.styles.is_empty());
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's
|
||||
/// filter of its name; one that draws another definition than that filter takes the document's
|
||||
/// filter when pasted back into the document it came from, and elsewhere keeps its own under a
|
||||
/// free name, so editing or deleting the document's filter leaves it alone. When that name would
|
||||
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would
|
||||
/// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else
|
||||
/// a free letter or digit; the filter's id is always its name.
|
||||
fn filter_links(&self, d: &Document, same_doc: bool) -> BTreeMap<(String, String), (String, String)> {
|
||||
/// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits.
|
||||
fn filter_links(&self, d: &Document, same_doc: bool) -> Result<BTreeMap<(String, String), (String, String)>> {
|
||||
let mut found = BTreeSet::new();
|
||||
for n in &self.nodes {
|
||||
node_filters(n, &mut found);
|
||||
@@ -1240,31 +1258,57 @@ impl Clipboard {
|
||||
appearance_filters(&g.appearance, &mut found);
|
||||
}
|
||||
let mut taken: BTreeSet<String> = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect();
|
||||
let mut effects_read = false;
|
||||
let mut links = BTreeMap::new();
|
||||
for (name, xml) in found {
|
||||
let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue };
|
||||
let to = if same_doc {
|
||||
(name.clone(), held.xml.clone())
|
||||
} else {
|
||||
// The names the document's effects give are taken too, those whose filter was
|
||||
// deleted included: defining a filter of that name later changes every effect that
|
||||
// names it. They are read at the first rename only.
|
||||
if !effects_read {
|
||||
effects_read = true;
|
||||
for root in d.art_roots() {
|
||||
node_filter_names(root, &mut taken);
|
||||
}
|
||||
for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) {
|
||||
node_filter_names(a, &mut taken);
|
||||
}
|
||||
for g in &d.graphic_styles {
|
||||
appearance_filter_names(&g.appearance, &mut taken);
|
||||
}
|
||||
}
|
||||
// Free names made from the starts of the name, longest first, then free letters and
|
||||
// digits: the first under which the filter still draws.
|
||||
// digits, then other single printable ASCII characters: the first under which the
|
||||
// filter still draws.
|
||||
let mut ends: Vec<usize> = name.char_indices().map(|(i, _)| i).skip(1).collect();
|
||||
ends.push(name.len());
|
||||
let starts = ends.iter().rev().filter_map(|&end| name.get(..end).map(str::trim_end)).filter(|b| !b.is_empty());
|
||||
let shorter = starts.map(|b| unique_name(b, |n| taken.contains(n)));
|
||||
let single = ('a'..='z').chain('0'..='9').map(String::from).filter(|n| !taken.contains(n));
|
||||
let single = ('a'..='z')
|
||||
.chain('0'..='9')
|
||||
.chain('A'..='Z')
|
||||
.chain(('!'..='~').filter(|c| !c.is_ascii_alphanumeric()))
|
||||
.map(String::from)
|
||||
.filter(|n| !taken.contains(n));
|
||||
let renamed = shorter.chain(single).find_map(|new| {
|
||||
let drawn = vectorcraft_render::effects::svg_filter::with_id(&xml, &new)
|
||||
.filter(|x| vectorcraft_render::effects::svg_filter::check(x).is_ok())?;
|
||||
.filter(|x| vectorcraft_render::effects::svg_filter::check(x).is_ok_and(|id| id == new))?;
|
||||
Some((new, drawn))
|
||||
});
|
||||
let Some((new, drawn)) = renamed else { continue };
|
||||
let Some((new, drawn)) = renamed else {
|
||||
return Err(EngineError::Other(format!(
|
||||
"the pasted SVG filter {name:?} draws differently from the document's filter of that name, and no free name fits it"
|
||||
)));
|
||||
};
|
||||
taken.insert(new.clone());
|
||||
(new, drawn)
|
||||
};
|
||||
links.insert((name, xml), to);
|
||||
}
|
||||
links
|
||||
Ok(links)
|
||||
}
|
||||
|
||||
/// Image blobs: a different blob under a key the document uses gets a new key.
|
||||
@@ -1379,13 +1423,13 @@ pub(crate) struct LoadedStyle {
|
||||
/// a pattern added under a free name and a pattern follows a style renamed on the way in. A style
|
||||
/// `d` has under its name, or a numbered copy of it ("Body 2"), that is the same once relinked is
|
||||
/// used; any other is added under a free name. → each style of `src` placed, in order, character
|
||||
/// styles first.
|
||||
pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Vec<LoadedStyle> {
|
||||
/// styles first. An error, as [`Clipboard::import_into`] gives.
|
||||
pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Result<Vec<LoadedStyle>> {
|
||||
let library = OnceCell::new();
|
||||
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true);
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true)?;
|
||||
let mut placed: Vec<LoadedStyle> = vec![];
|
||||
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
|
||||
for s in list {
|
||||
@@ -1395,7 +1439,7 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
|
||||
placed.push(LoadedStyle { para, name, added });
|
||||
}
|
||||
}
|
||||
placed
|
||||
Ok(placed)
|
||||
}
|
||||
|
||||
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
|
||||
|
||||
@@ -1332,7 +1332,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
vec![Affine::IDENTITY]
|
||||
};
|
||||
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
|
||||
let imported = clip.import_into(d, choices, same_doc);
|
||||
let imported = clip.import_into(d, choices, same_doc)?;
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
|
||||
let artboards: Vec<usize> = boards
|
||||
|
||||
@@ -63,6 +63,7 @@ impl Loaded {
|
||||
|
||||
/// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG
|
||||
/// (what browsers, PDF and SVG viewers show).
|
||||
#[derive(Clone)]
|
||||
pub struct RasterImage {
|
||||
/// Content key for `Document::images` (identical files share one blob).
|
||||
pub key: String,
|
||||
|
||||
@@ -80,19 +80,28 @@ fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Whose gradient a selected stop belongs to: the active document, its first selected object
|
||||
/// (None: the default paint), the proxy in front and the Appearance panel's active item.
|
||||
/// Selecting other art, toggling the proxy or picking another item leaves no stop selected.
|
||||
/// (None: the default paint), whether a part of a symbol instance's art is picked, the proxy in
|
||||
/// front and the Appearance panel's active item. Selecting other art, picking a part of the
|
||||
/// instance, toggling the proxy or picking another item leaves no stop selected.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct StopOwner {
|
||||
doc: Option<usize>,
|
||||
object: Option<NodeId>,
|
||||
part: bool,
|
||||
fill: bool,
|
||||
item: Option<usize>,
|
||||
}
|
||||
|
||||
impl StopOwner {
|
||||
pub(crate) fn of(s: &Session) -> Self {
|
||||
Self { doc: s.active, object: s.active().and_then(|d| d.selection.objects.first().copied()), fill: s.fill_active, item: s.appearance_item() }
|
||||
let st = s.active();
|
||||
Self {
|
||||
doc: s.active,
|
||||
object: st.and_then(|d| d.selection.objects.first().copied()),
|
||||
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
|
||||
fill: s.fill_active,
|
||||
item: s.appearance_item(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1303,7 +1303,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
|
||||
let choices = SwatchChoices::default();
|
||||
// The pattern's name in the document, worked out on a copy: nothing to add is no edit.
|
||||
let mut probe = (*s.doc()?.doc).clone();
|
||||
let imported = clip.import_into(&mut probe, &choices, false);
|
||||
let imported = clip.import_into(&mut probe, &choices, false)?;
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str());
|
||||
let target = renamed.unwrap_or(&name).to_string();
|
||||
let paint = vectorcraft_doc::pattern::pattern_paint(&target);
|
||||
@@ -1315,7 +1315,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
|
||||
in_one_step(s, |s| {
|
||||
if added {
|
||||
s.edit("Add to Swatches", |d, _| {
|
||||
clip.import_into(d, &choices, false);
|
||||
clip.import_into(d, &choices, false)?;
|
||||
if !has_swatch(d) {
|
||||
let swatch = d.free_swatch_name(&target);
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: swatch, paint: paint.clone(), global: false, spot: false });
|
||||
|
||||
@@ -521,10 +521,25 @@ fn linked_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
/// The file read for a link: the link to it and its image.
|
||||
type FileRead = (LinkInfo, RasterImage);
|
||||
|
||||
/// The file at `f` read for a link like `base` (its image decoded).
|
||||
fn read_image(f: &mut Found, base: &LinkInfo) -> Result<FileRead> {
|
||||
/// The images read in one operation, by the path of the file and its content hash: groups whose
|
||||
/// image keys differ but whose file is the same share one decoded image (and its encoded bytes)
|
||||
/// instead of each keeping a copy.
|
||||
type ImageReads = BTreeMap<String, (String, RasterImage)>;
|
||||
|
||||
/// The file at `f` read for a link like `base` (its image decoded, or the one `reads` holds for
|
||||
/// the same file content).
|
||||
fn read_image(f: &mut Found, base: &LinkInfo, reads: &mut ImageReads) -> Result<FileRead> {
|
||||
let bytes = f.read()?;
|
||||
Ok((f.link(&bytes, base), linked_image(&bytes)?))
|
||||
let hash = hash_bytes(&bytes);
|
||||
let img = match reads.get(&f.path) {
|
||||
Some((h, img)) if *h == hash => img.clone(),
|
||||
_ => {
|
||||
let img = linked_image(&bytes)?;
|
||||
reads.insert(f.path.clone(), (hash.clone(), img.clone()));
|
||||
img
|
||||
}
|
||||
};
|
||||
Ok((f.link_hashed(hash, base), img))
|
||||
}
|
||||
|
||||
/// A linked file read for the objects that show it.
|
||||
@@ -536,8 +551,8 @@ enum Read {
|
||||
}
|
||||
|
||||
/// The file at `f` read for group `g`: its image, or the artboard or page `g` shows.
|
||||
fn read_for(f: &mut Found, g: &Group, cmd: &str) -> Result<Read> {
|
||||
let Some((bounding, page_box)) = g.document else { return read_image(f, &g.link).map(Read::Image) };
|
||||
fn read_for(f: &mut Found, g: &Group, cmd: &str, reads: &mut ImageReads) -> Result<Read> {
|
||||
let Some((bounding, page_box)) = g.document else { return read_image(f, &g.link, reads).map(Read::Image) };
|
||||
let bytes = f.read()?;
|
||||
let page = g.link.page.unwrap_or(1);
|
||||
let src = super::place::document::source(&f.path, &bytes, Some(&f.path), page, bounding, page_box, cmd)?;
|
||||
@@ -922,6 +937,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
|
||||
// (the path as it was, the content shown, a placed document?, the link now) of each file found
|
||||
// away from its path or read again.
|
||||
let mut moved: Vec<(String, String, bool, LinkInfo)> = vec![];
|
||||
let mut image_reads = ImageReads::new();
|
||||
for g in groups(d, None) {
|
||||
let row = rows(std::iter::once(&g), base.doc);
|
||||
let shows_preview = match g.document {
|
||||
@@ -934,7 +950,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
|
||||
(Status::Missing, _) => out.missing.extend(row),
|
||||
(Status::Modified, Some(mut f)) if update || unread => {
|
||||
let force = unread.then_some(Preserve::Bounds);
|
||||
match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, force, Some(&g))) {
|
||||
match read_for(&mut f, &g, "document.open", &mut image_reads).and_then(|read| install_read(d, &g.ids, read, force, Some(&g))) {
|
||||
Ok(()) if unread => {}
|
||||
Ok(()) => out.updated.extend(row),
|
||||
Err(_) => out.missing.extend(row),
|
||||
@@ -943,7 +959,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
|
||||
(Status::Modified, _) => out.modified.extend(row),
|
||||
// A placed document keeps its file's bytes: only lost ones are read again.
|
||||
(Status::Ok, Some(mut f)) if g.document.is_some() => {
|
||||
let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open")) } else { None };
|
||||
let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open", &mut image_reads)) } else { None };
|
||||
match read {
|
||||
Some(Ok(read)) => {
|
||||
if install_read(d, &g.ids, read, Some(Preserve::Bounds), Some(&g)).is_err() {
|
||||
@@ -1196,6 +1212,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let (mut reads, mut missing) = (vec![], vec![]);
|
||||
let mut image_reads = ImageReads::new();
|
||||
let asked = ids.is_some() || path.is_some();
|
||||
for g in groups(&st.doc, ids.as_deref()).into_iter().filter(|g| path.is_none_or(|p| g.document.is_some() && g.link.path == p)) {
|
||||
match probe(&g, LinkBase::of(st)) {
|
||||
@@ -1203,7 +1220,7 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -
|
||||
// Unchanged and showing the file: nothing to read unless asked for.
|
||||
(Status::Ok, Some(_)) if !asked && !stale(&st.doc, &g) => {}
|
||||
// Unreadable as an image (or a document) counts as missing.
|
||||
(_, Some(mut f)) => match read_for(&mut f, &g, "links.update") {
|
||||
(_, Some(mut f)) => match read_for(&mut f, &g, "links.update", &mut image_reads) {
|
||||
Ok(read) => reads.push((g, read)),
|
||||
Err(_) => missing.extend(ids_json(&g.ids)),
|
||||
},
|
||||
@@ -1706,13 +1723,14 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| matches!(kind(id), Some(NodeKind::Image(_)))).collect();
|
||||
// Images showing their preview take their file's pixels first.
|
||||
let (mut done, mut reads) = (vec![], vec![]);
|
||||
let mut image_reads = ImageReads::new();
|
||||
for g in groups(&st.doc, Some(&ids)) {
|
||||
if !previewing(&st.doc, &g.key) {
|
||||
done.extend(g.ids);
|
||||
continue;
|
||||
}
|
||||
match probe(&g, LinkBase::of(st)) {
|
||||
(Status::Ok | Status::Modified, Some(mut f)) => match read_image(&mut f, &g.link) {
|
||||
(Status::Ok | Status::Modified, Some(mut f)) => match read_image(&mut f, &g.link, &mut image_reads) {
|
||||
Ok(read) => {
|
||||
done.extend(&g.ids);
|
||||
reads.push((g.ids, read));
|
||||
@@ -1921,3 +1939,26 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set(&mut shown);
|
||||
Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(shown) }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
use crate::tests::links::{Folder, RED, png, write};
|
||||
|
||||
#[test]
|
||||
fn groups_of_one_file_share_one_decoded_image() {
|
||||
let dir = Folder::new("shared-read");
|
||||
let path = dir.file("pic.png");
|
||||
write(&path, &png(40, 20, RED));
|
||||
let (mut reads, base) = (ImageReads::new(), LinkInfo::new(path.clone()));
|
||||
let mut read = || read_image(&mut found_at(path.clone()).unwrap(), &base, &mut reads).unwrap().1;
|
||||
let (a, b) = (read(), read());
|
||||
assert!(Arc::ptr_eq(&a.blob.bytes, &b.blob.bytes), "one retained copy of the bytes");
|
||||
// A changed file is decoded again.
|
||||
write(&path, &png(40, 20, [1, 2, 3]));
|
||||
let c = read();
|
||||
assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes));
|
||||
}
|
||||
}
|
||||
@@ -670,9 +670,11 @@ fn render_pixels(
|
||||
opts: &vectorcraft_render::RenderOptions,
|
||||
color: RasterColorModel,
|
||||
) -> Result<(vectorcraft_render::Rendered, Option<&'static str>)> {
|
||||
// No side longer than the renderer draws: it would cut the image off there.
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
if region.width() * region.height() * scale * scale > MAX_PIXELS || region.width() * scale > side || region.height() * scale > side {
|
||||
// No side longer than the renderer draws: it would cut the image off there. The sides are
|
||||
// measured in the renderer's whole pixels.
|
||||
let side = vectorcraft_render::MAX_RASTER_SIDE;
|
||||
let (w, h) = vectorcraft_render::region_pixels(region, scale);
|
||||
if region.width() * region.height() * scale * scale > MAX_PIXELS || w > side || h > side {
|
||||
return Err(EngineError::Other("image would be too large; lower the resolution".into()));
|
||||
}
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
|
||||
@@ -719,7 +719,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
/// Pathfinder panel › Trap ([`vectorcraft_render::effects::trap`]): the traps between the selected
|
||||
/// objects' leaf shapes, as one group of overprinting paths above the topmost selected object.
|
||||
fn trap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_render::effects::trap::{TRAP_LABEL, TrapOptions, TrapSource, trap_appearance, traps};
|
||||
use vectorcraft_render::effects::trap::{TRAP_LABEL, TrapOptions, TrapSource, trap_appearance, try_traps};
|
||||
const ID: &str = "object.pathfinder.trap";
|
||||
let mut q = p.clone();
|
||||
if let Some(t) = length_given(p, "thickness", ID)? {
|
||||
@@ -758,7 +758,12 @@ fn trap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if sources.iter().filter(|s| s.fill.color().is_some()).count() < 2 {
|
||||
return Err(EngineError::Other("Trap: select two or more objects filled with solid colours".into()));
|
||||
}
|
||||
let made = traps(&sources, &options);
|
||||
let Some(made) = try_traps(&sources, &options) else {
|
||||
return Err(EngineError::Other(format!(
|
||||
"Trap: more than {} pairs of objects lie close enough to trap, or too many objects share a horizontal range; trap fewer objects at a time",
|
||||
vectorcraft_render::effects::trap::MAX_NEAR_PAIRS
|
||||
)));
|
||||
};
|
||||
if made.is_empty() {
|
||||
return Err(EngineError::Other("Trap: no edges of different colours meet among the selected objects".into()));
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use vectorcraft_doc::pattern::pattern_paint;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, PatternDef, TileType};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::Result;
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::swatchlib::LibraryInfo;
|
||||
@@ -84,11 +85,11 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
|
||||
/// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art
|
||||
/// painted with it does: the same pattern there already is used, and a name another pattern or
|
||||
/// swatch has gets a number → the pattern's name in `d`.
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> String {
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<String> {
|
||||
let user = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(pattern_paint(name), Paint::None, 0.0));
|
||||
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false);
|
||||
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false)?;
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str());
|
||||
renamed.unwrap_or(name).to_string()
|
||||
Ok(renamed.unwrap_or(name).to_string())
|
||||
}
|
||||
|
||||
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
|
||||
|
||||
@@ -846,6 +846,15 @@ pub(crate) fn sync_prefs(s: &Session) {
|
||||
*last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder)));
|
||||
}
|
||||
|
||||
/// The Additional Plug-ins Folder preference was cleared from `old`: when `old` is the folder last
|
||||
/// loaded, it is forgotten, so setting the preference to it again loads it again.
|
||||
pub(crate) fn forget_prefs_folder(old: &str) {
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if last.as_ref().is_some_and(|(f, _, _)| f == old.trim()) {
|
||||
*last = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns Safe Mode on for `--safe-mode`, before the plug-in folder is attached: no plug-in loads or
|
||||
/// runs in this process from then on.
|
||||
pub fn start_in_safe_mode() {
|
||||
|
||||
@@ -697,6 +697,9 @@ impl Session {
|
||||
let history_changed = p.history_states != self.prefs.history_states;
|
||||
let tile_edge_changed = p.pattern_tile_edge_color != self.prefs.pattern_tile_edge_color;
|
||||
let fonts_folder_changed = p.fonts_folder != self.prefs.fonts_folder;
|
||||
if p.plugins_folder.trim().is_empty() && !self.prefs.plugins_folder.trim().is_empty() {
|
||||
super::plugin::forget_prefs_folder(&self.prefs.plugins_folder);
|
||||
}
|
||||
let hyphen_exceptions_changed = p.hyphenation_exceptions != self.prefs.hyphenation_exceptions;
|
||||
let corner_radius_changed = p.corner_radius != self.prefs.corner_radius;
|
||||
let lock_guides_changed = p.lock_guides_by_default != self.prefs.lock_guides_by_default;
|
||||
|
||||
@@ -161,7 +161,9 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(param("give exactly one of `path` and `source`")),
|
||||
};
|
||||
let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string());
|
||||
let request = script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), source: text, args, fuel, answers };
|
||||
let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language));
|
||||
let request =
|
||||
script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), source: text, args, fuel, locale, answers };
|
||||
let name = s.script_start(request)?;
|
||||
if s.script_frames {
|
||||
return Ok(json!({"running": true, "name": name}));
|
||||
|
||||
@@ -753,7 +753,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
|
||||
// The pattern comes with its swatch; a pattern the document has without one
|
||||
// gets one.
|
||||
let target = patternlib::import(d, src, pattern);
|
||||
let target = patternlib::import(d, src, pattern)?;
|
||||
let name = match patternlib::pattern_swatch(d, &target) {
|
||||
Some(name) => name,
|
||||
None => {
|
||||
|
||||
@@ -405,7 +405,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// Where the symbols land, worked out on a copy: nothing to add and nothing to place is no edit.
|
||||
let mut probe = (*st.doc).clone();
|
||||
let imported = clip.import_into(&mut probe, &choices, false);
|
||||
let imported = clip.import_into(&mut probe, &choices, false)?;
|
||||
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
|
||||
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None };
|
||||
@@ -413,7 +413,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = json!({ "library": info.id });
|
||||
if imported.added > 0 || place {
|
||||
let placed = s.edit("Add to Symbols", |d, sel| {
|
||||
let imported = clip.import_into(d, &choices, false);
|
||||
let imported = clip.import_into(d, &choices, false)?;
|
||||
// Every symbol brought in (nested ones too) takes its Symbol Options along.
|
||||
for sym in &clip.symbols {
|
||||
let to = target(&imported.renamed, &sym.name);
|
||||
|
||||
@@ -976,12 +976,12 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result<Value> {
|
||||
}
|
||||
let (chars, paras) = (kinds.contains(&Kind::Char), kinds.contains(&Kind::Para));
|
||||
let mut trial = (*s.doc()?.doc).clone();
|
||||
let mut placed = import_text_styles(&src, &mut trial, chars, paras);
|
||||
let mut placed = import_text_styles(&src, &mut trial, chars, paras)?;
|
||||
// An undo step only when the document changes. The step takes the document the import made,
|
||||
// unless the edit first ends a typing session, which can change the document it starts from.
|
||||
if trial != *s.doc()?.doc {
|
||||
if super::typing_in_progress(s) {
|
||||
placed = s.edit(label, |d, _| Ok(import_text_styles(&src, d, chars, paras)))?;
|
||||
placed = s.edit(label, |d, _| import_text_styles(&src, d, chars, paras))?;
|
||||
} else {
|
||||
s.edit(label, |d, _| {
|
||||
*d = trial;
|
||||
|
||||
@@ -1105,7 +1105,7 @@ fn self_referencing_pattern_is_not_added_again() {
|
||||
let different = dst.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 30, "height": 30})).unwrap()["id"].clone();
|
||||
dst.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [different]})).unwrap();
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert!(dst.doc().unwrap().doc.pattern("Dots 2").is_some());
|
||||
assert!(
|
||||
dst.doc().unwrap().doc.pattern("Dots 2").unwrap().art[0]
|
||||
@@ -1116,7 +1116,7 @@ fn self_referencing_pattern_is_not_added_again() {
|
||||
);
|
||||
let before = dst.doc().unwrap().doc.clone();
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert!(again.iter().all(|s| !s.added));
|
||||
assert_eq!(dst.doc().unwrap().doc, before);
|
||||
}
|
||||
@@ -1148,13 +1148,13 @@ fn separate_self_referencing_patterns_are_not_added_again() {
|
||||
dst.execute("object.pattern.make", &json!({"name": format!("Dots{k}"), "edit": false, "ids": [different]})).unwrap();
|
||||
}
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
for k in 0..9 {
|
||||
assert!(dst.doc().unwrap().doc.pattern(&format!("Dots{k} 2")).is_some(), "{k}");
|
||||
}
|
||||
let before = dst.doc().unwrap().doc.clone();
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert!(again.iter().all(|s| !s.added));
|
||||
assert_eq!(dst.doc().unwrap().doc.patterns.len(), before.patterns.len());
|
||||
assert_eq!(dst.doc().unwrap().doc, before);
|
||||
@@ -1162,7 +1162,7 @@ fn separate_self_referencing_patterns_are_not_added_again() {
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
target.patterns.retain(|p| !p.name.starts_with("Dots8"));
|
||||
let left = target.patterns.len();
|
||||
let third = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
let third = super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert_eq!(dst.doc().unwrap().doc.patterns.len(), left + 1);
|
||||
assert!(third.iter().filter(|s| s.name != "Patterned8" && !s.name.starts_with("Patterned8 ")).all(|s| !s.added));
|
||||
}
|
||||
@@ -1195,13 +1195,13 @@ fn a_long_loop_of_patterns_is_not_added_again() {
|
||||
dst.execute("object.pattern.make", &json!({"name": format!("Dots{k}"), "edit": false, "ids": [different]})).unwrap();
|
||||
}
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
for k in 0..9 {
|
||||
assert!(dst.doc().unwrap().doc.pattern(&format!("Dots{k} 2")).is_some(), "{k}");
|
||||
}
|
||||
let before = dst.doc().unwrap().doc.clone();
|
||||
let target = std::sync::Arc::make_mut(&mut dst.doc_mut().unwrap().doc);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true);
|
||||
let again = super::super::clipboard::resources::import_text_styles(&source, target, true, true).unwrap();
|
||||
assert!(again.iter().all(|s| !s.added));
|
||||
assert_eq!(dst.doc().unwrap().doc.patterns.len(), before.patterns.len());
|
||||
assert_eq!(dst.doc().unwrap().doc, before);
|
||||
|
||||
@@ -8,7 +8,7 @@ use vectorcraft_doc::{AreaFit, Document, Justify, Node, NodeId, NodeKind, RubyAl
|
||||
use vectorcraft_geom::{Affine, PathData, Vec2};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::{len_param, length_given, number_given, shape_node};
|
||||
use super::pathops::{length_given, number_given, shape_node};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, id_param, index, number_or, ok,
|
||||
str_param, switch_or, targets, text_param,
|
||||
@@ -824,7 +824,9 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let leading = match p.get("leading") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(None),
|
||||
Some(_) => Some(Some(len_param(p, "leading").ok_or_else(|| bad(C, "leading must be a number or \"auto\""))?.clamp(0.1, 5000.0))),
|
||||
Some(_) => {
|
||||
Some(Some(length_given(p, "leading", C).ok().flatten().ok_or_else(|| bad(C, "leading must be a number or \"auto\""))?.clamp(0.1, 5000.0)))
|
||||
}
|
||||
};
|
||||
let tracking = number_given(p, "tracking", C)?;
|
||||
let justify = match text_param(p, "justify", C)? {
|
||||
|
||||
@@ -106,7 +106,8 @@ impl Entry {
|
||||
Entry::End(e) => format!("ended: {}", e.id()),
|
||||
Entry::Report { ms, host_calls, slowest } => {
|
||||
let time = ms.map_or_else(|| "time unavailable".to_string(), |ms| format!("{ms} ms"));
|
||||
let mut s = format!("{time}, {host_calls} host calls");
|
||||
let calls = if *host_calls == 1 { "host call" } else { "host calls" };
|
||||
let mut s = format!("{time}, {host_calls} {calls}");
|
||||
if !slowest.is_empty() {
|
||||
let list: Vec<String> = slowest.iter().map(|c| format!("{} ×{} {} ms", c.id, c.calls, c.total_ms)).collect();
|
||||
s.push_str("; slowest: ");
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
//! The members of a script's `$` object besides `$.write`, `$.writeln`, `$.evalFile`, `$.fileName`
|
||||
//! and `$.includePath`, from the Dollar object
|
||||
//! page (<https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/>), and
|
||||
//! the locale the global `localize` reads
|
||||
//! (<https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/>).
|
||||
//!
|
||||
//! Every value here belongs to one run: a run starts with the locale of the interface, the
|
||||
//! environment values of [`ENV_NAMES`] read from the process, localization off and a timer at zero,
|
||||
//! and what a script changes ends with its run. `$.setenv` never changes the process's environment.
|
||||
//!
|
||||
//! These are VectorCraft's own values and rules: `$.appEncoding` is always UTF-8; `$.build` and
|
||||
//! `$.version` give VectorCraft's version, `$.engineName` is `VectorCraft` and `$.buildDate` is
|
||||
//! `null`; `$.flags` takes only 512, which turns localization on; `$.level` and `$.memCache` are 0
|
||||
//! and `$.screens` is empty; `$.os` names the system without its version; `$.strict` is whether the
|
||||
//! realm reads scripts as strict mode code; `$.bp` and `$.colorPicker` throw, since scripts have no
|
||||
//! debugger and cannot show a dialog; `$.gc` does nothing, since the interpreter collects its own
|
||||
//! garbage; `$.getenv` and `$.setenv` know only [`ENV_NAMES`], with values of at most
|
||||
//! [`MAX_ENV_BYTES`] bytes of letters, digits and `_ . - @`; and `$.sleep` waits at most
|
||||
//! [`MAX_SLEEP_MS`] milliseconds, between two frames of the app, and does not wait on the web,
|
||||
//! which has no clock.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use vectorcraft_js::{Data, HostError, HostItem, Localization, ScriptItem};
|
||||
|
||||
use super::{Host, function};
|
||||
|
||||
/// The longest `$.sleep`, in milliseconds.
|
||||
pub const MAX_SLEEP_MS: f64 = 1_000.0;
|
||||
/// The environment variables `$.getenv` reads and `$.setenv` sets.
|
||||
pub const ENV_NAMES: &[&str] = &["LANG", "LC_MESSAGES", "LC_ALL", "OS"];
|
||||
/// The most bytes of an environment value.
|
||||
pub const MAX_ENV_BYTES: usize = 64;
|
||||
/// The value of `$.flags` that turns localization on, the only one a script may set.
|
||||
pub const LOCALIZE_FLAG: f64 = 512.0;
|
||||
|
||||
/// What `$` knows of a run.
|
||||
pub(crate) struct RunInfo {
|
||||
/// The locale the run starts with, such as `de_DE`.
|
||||
pub locale: String,
|
||||
/// The realm reads scripts as strict mode code.
|
||||
pub strict: bool,
|
||||
}
|
||||
|
||||
/// The locale for an interface language code such as `de`, `pt-br` or `zh-hant`: the language,
|
||||
/// with its region after `_` where the code gives one (`pt_BR`; `zh_CN` for `zh-hans` and `zh_TW`
|
||||
/// for `zh-hant`); `en` for a code that is not a language.
|
||||
pub(crate) fn ui_locale(code: &str) -> String {
|
||||
let mut parts = code.split(['-', '_']);
|
||||
let language = parts.next().unwrap_or_default().to_ascii_lowercase();
|
||||
if !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_lowercase()) {
|
||||
return "en".into();
|
||||
}
|
||||
let region = match parts.next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("hans") => Some("CN".to_string()),
|
||||
Some("hant") => Some("TW".to_string()),
|
||||
Some(r) if r.len() == 2 && r.bytes().all(|b| b.is_ascii_lowercase()) => Some(r.to_ascii_uppercase()),
|
||||
_ => None,
|
||||
};
|
||||
region.map_or(language.clone(), |r| format!("{language}_{r}"))
|
||||
}
|
||||
|
||||
/// A locale a script gives `$.locale`, as `ll` or `ll_RR`: a language of two or three letters and
|
||||
/// an optional region of two letters or three digits, joined by `_` or `-`, in any case.
|
||||
fn script_locale(text: &str) -> Option<String> {
|
||||
let mut parts = text.split(['-', '_']);
|
||||
let language = parts.next()?;
|
||||
let region = parts.next();
|
||||
if parts.next().is_some() || !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||
return None;
|
||||
}
|
||||
let language = language.to_ascii_lowercase();
|
||||
match region {
|
||||
None => Some(language),
|
||||
Some(r) if r.len() == 2 && r.bytes().all(|b| b.is_ascii_alphabetic()) => Some(format!("{language}_{}", r.to_ascii_uppercase())),
|
||||
Some(r) if r.len() == 3 && r.bytes().all(|b| b.is_ascii_digit()) => Some(format!("{language}_{r}")),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The languages whose numbers are written with a decimal comma (VectorCraft's own list).
|
||||
const DECIMAL_COMMA: &[&str] = &[
|
||||
"bg", "ca", "cs", "da", "de", "el", "es", "et", "fi", "fr", "hr", "hu", "id", "it", "lt", "lv", "nb", "nl", "no", "pl", "pt", "ro", "ru", "sk",
|
||||
"sl", "sr", "sv", "tr", "uk", "vi",
|
||||
];
|
||||
|
||||
/// The character `locale` writes before a number's fraction.
|
||||
pub(crate) fn decimal_point(locale: &str) -> &'static str {
|
||||
let language = locale.split('_').next().unwrap_or_default();
|
||||
if DECIMAL_COMMA.contains(&language) { "," } else { "." }
|
||||
}
|
||||
|
||||
/// The platform suffix of a localization object's names on this system.
|
||||
pub(crate) fn platform() -> Option<&'static str> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
None
|
||||
} else if cfg!(windows) {
|
||||
Some("Win")
|
||||
} else if cfg!(target_os = "macos") {
|
||||
Some("Mac")
|
||||
} else {
|
||||
Some("Unix")
|
||||
}
|
||||
}
|
||||
|
||||
/// `$.os`: the system, without its version.
|
||||
fn os() -> &'static str {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
"Web"
|
||||
} else if cfg!(windows) {
|
||||
"Windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"macOS"
|
||||
} else if cfg!(target_os = "linux") {
|
||||
"Linux"
|
||||
} else if cfg!(target_os = "freebsd") {
|
||||
"FreeBSD"
|
||||
} else {
|
||||
"Unix"
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `value` one an environment value may be?
|
||||
fn env_value_ok(value: &str) -> bool {
|
||||
value.len() <= MAX_ENV_BYTES && value.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-' | b'@'))
|
||||
}
|
||||
|
||||
/// The values of [`ENV_NAMES`] in the process's environment, each left out when it is not one an
|
||||
/// environment value may be.
|
||||
fn process_env() -> Vec<(&'static str, Option<String>)> {
|
||||
ENV_NAMES.iter().map(|&n| (n, std::env::var(n).ok().filter(|v| env_value_ok(v)))).collect()
|
||||
}
|
||||
|
||||
fn one_string(args: &[Data], name: &str) -> Result<String, HostError> {
|
||||
match args.first() {
|
||||
Some(Data::String(s)) => Ok(s.clone()),
|
||||
_ => Err(HostError::Type(format!("$.{name}: give a name, as a string"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn value(v: Data) -> HostItem {
|
||||
HostItem::Value(v)
|
||||
}
|
||||
|
||||
fn text(s: impl Into<String>) -> Data {
|
||||
Data::String(s.into())
|
||||
}
|
||||
|
||||
/// The members `$` has besides `write`, `writeln`, `evalFile`, `fileName` and `includePath`.
|
||||
pub(super) fn members(host: &Rc<Host>, info: RunInfo, localization: &Rc<Localization>) -> Vec<(String, HostItem)> {
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let host_locale = info.locale.clone();
|
||||
localization.set_locale(&info.locale);
|
||||
localization.set_platform(platform());
|
||||
let env = Rc::new(RefCell::new(process_env()));
|
||||
let timer = Rc::new(Cell::new(Duration::ZERO));
|
||||
let getter = |f: Rc<dyn Fn() -> Data>| HostItem::Getter(function(move |_| Ok(f())));
|
||||
let property = |get: Rc<dyn Fn() -> Data>, set: Rc<dyn Fn(Data) -> Result<(), HostError>>| HostItem::Property {
|
||||
get: function(move |_| Ok(get())),
|
||||
set: function(move |mut a| {
|
||||
set(if a.is_empty() { Data::Undefined } else { a.swap_remove(0) })?;
|
||||
Ok(Data::Undefined)
|
||||
}),
|
||||
};
|
||||
let fail = |message: &'static str| HostItem::Function(function(move |_| Err(HostError::Error(message.to_string()))));
|
||||
|
||||
let locale = {
|
||||
let (l, s) = (localization.clone(), localization.clone());
|
||||
property(
|
||||
Rc::new(move || text(l.locale())),
|
||||
Rc::new(move |v| {
|
||||
let locale = match v {
|
||||
Data::Null | Data::Undefined => host_locale.clone(),
|
||||
Data::String(t) if t.is_empty() => host_locale.clone(),
|
||||
Data::String(t) => script_locale(&t).ok_or_else(|| HostError::Range(BAD_LOCALE.to_string()))?,
|
||||
_ => return Err(HostError::Type(BAD_LOCALE.to_string())),
|
||||
};
|
||||
s.set_locale(&locale);
|
||||
Ok(())
|
||||
}),
|
||||
)
|
||||
};
|
||||
let localize = {
|
||||
let (l, s) = (localization.clone(), localization.clone());
|
||||
property(
|
||||
Rc::new(move || Data::Bool(l.enabled())),
|
||||
Rc::new(move |v| match v {
|
||||
Data::Bool(on) => {
|
||||
s.set_enabled(on);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(HostError::Type("$.localize: give true or false".into())),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let flags = {
|
||||
let (l, s) = (localization.clone(), localization.clone());
|
||||
property(
|
||||
Rc::new(move || Data::Number(if l.enabled() { LOCALIZE_FLAG } else { 0.0 })),
|
||||
Rc::new(move |v| match v {
|
||||
Data::Number(n) if n == 0.0 || n == LOCALIZE_FLAG => {
|
||||
s.set_enabled(n == LOCALIZE_FLAG);
|
||||
Ok(())
|
||||
}
|
||||
Data::Number(_) => Err(HostError::Range("$.flags: only 512, which turns localization on, or 0 can be set".into())),
|
||||
_ => Err(HostError::Type("$.flags: give a number".into())),
|
||||
}),
|
||||
)
|
||||
};
|
||||
let decimal = {
|
||||
let l = localization.clone();
|
||||
getter(Rc::new(move || text(decimal_point(&l.locale()))))
|
||||
};
|
||||
let app_encoding = property(
|
||||
Rc::new(|| text("UTF-8")),
|
||||
Rc::new(|v| match v {
|
||||
Data::String(t) if t.eq_ignore_ascii_case("utf-8") || t.eq_ignore_ascii_case("utf8") => Ok(()),
|
||||
Data::String(_) => Err(HostError::Range("$.appEncoding: scripts here read and write UTF-8 only".into())),
|
||||
_ => Err(HostError::Type("$.appEncoding: give an encoding's name, as a string".into())),
|
||||
}),
|
||||
);
|
||||
let mem_cache =
|
||||
property(Rc::new(|| Data::Number(0.0)), Rc::new(|_| Err(HostError::Error("$.memCache: the memory cache size cannot be set".into()))));
|
||||
let hires_timer = {
|
||||
let (h, last) = (host.clone(), timer.clone());
|
||||
getter(Rc::new(move || {
|
||||
let Some(now) = h.elapsed() else { return Data::Number(0.0) };
|
||||
let since = now.saturating_sub(last.replace(now));
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
Data::Number(since.as_micros() as f64)
|
||||
}))
|
||||
};
|
||||
let getenv = {
|
||||
let (h, env) = (host.clone(), env.clone());
|
||||
function(move |a| {
|
||||
let name = one_string(&a, "getenv")?;
|
||||
h.charge_call(name.len() as u64 + 2)?;
|
||||
let env = env.borrow();
|
||||
let found = env.iter().find(|(n, _)| *n == name).and_then(|(_, v)| v.clone());
|
||||
Ok(found.map_or(Data::Null, Data::String))
|
||||
})
|
||||
};
|
||||
let setenv = {
|
||||
let (h, env) = (host.clone(), env.clone());
|
||||
function(move |a| {
|
||||
let name = one_string(&a, "setenv")?;
|
||||
let Some(Data::String(v)) = a.get(1) else { return Err(HostError::Type("$.setenv: give a value, as a string".into())) };
|
||||
h.charge_call((name.len() + v.len()) as u64 + 4)?;
|
||||
let mut env = env.borrow_mut();
|
||||
let Some(slot) = env.iter_mut().find(|(n, _)| *n == name) else {
|
||||
return Err(HostError::Error(format!("$.setenv: only {} can be set", ENV_NAMES.join(", "))));
|
||||
};
|
||||
if !env_value_ok(v) {
|
||||
return Err(HostError::Range(format!("$.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @")));
|
||||
}
|
||||
slot.1 = Some(v.clone());
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
};
|
||||
let sleep = {
|
||||
let h = host.clone();
|
||||
function(move |a| {
|
||||
let ms = match a.first() {
|
||||
Some(Data::Number(n)) if (0.0..=MAX_SLEEP_MS).contains(n) => *n,
|
||||
Some(Data::Number(_)) => return Err(HostError::Range(format!("$.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS}"))),
|
||||
_ => return Err(HostError::Type("$.sleep: give a number of milliseconds".into())),
|
||||
};
|
||||
h.charge_call(8)?;
|
||||
h.sleep(Duration::from_secs_f64(ms / 1000.0))?;
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
};
|
||||
let about = text(format!("VectorCraft script engine {version}"));
|
||||
|
||||
vec![
|
||||
("about".into(), HostItem::Function(function(move |_| Ok(about.clone())))),
|
||||
("appEncoding".into(), app_encoding),
|
||||
("bp".into(), fail("$.bp: scripts here have no debugger")),
|
||||
("build".into(), value(text(version))),
|
||||
("buildDate".into(), value(Data::Null)),
|
||||
("colorPicker".into(), fail("$.colorPicker: scripts cannot show a dialog yet")),
|
||||
("decimalPoint".into(), decimal),
|
||||
("engineName".into(), value(text("VectorCraft"))),
|
||||
("error".into(), HostItem::Script(ScriptItem::LastError)),
|
||||
("flags".into(), flags),
|
||||
("gc".into(), HostItem::Function(function(|_| Ok(Data::Undefined)))),
|
||||
("getenv".into(), HostItem::Function(getenv)),
|
||||
("global".into(), HostItem::Script(ScriptItem::Global)),
|
||||
("hiresTimer".into(), hires_timer),
|
||||
("level".into(), value(Data::Number(0.0))),
|
||||
("line".into(), HostItem::Script(ScriptItem::Line)),
|
||||
("locale".into(), locale),
|
||||
("localize".into(), localize),
|
||||
("memCache".into(), mem_cache),
|
||||
("os".into(), value(text(os()))),
|
||||
("screens".into(), value(Data::Array(Vec::new()))),
|
||||
("setenv".into(), HostItem::Function(setenv)),
|
||||
("sleep".into(), HostItem::Function(sleep)),
|
||||
("stack".into(), HostItem::Script(ScriptItem::Stack)),
|
||||
("strict".into(), value(Data::Bool(info.strict))),
|
||||
("version".into(), value(text(version))),
|
||||
]
|
||||
}
|
||||
|
||||
const BAD_LOCALE: &str = "$.locale: give a locale such as \"en\" or \"de_DE\", or null for the interface's";
|
||||
+157
-45
@@ -31,13 +31,15 @@
|
||||
//! A run writes to the Script Console with `$.write` and `$.writeln`, and `vc.log` adds a line
|
||||
//! there too. The session's console gets a start line, the run's output, its uncaught error, an end
|
||||
//! line and a report line; the run's report holds its own output and error, its time, its host
|
||||
//! calls by kind and its slowest commands.
|
||||
//! calls by kind and its slowest commands. The rest of `$`, and the global `localize` and
|
||||
//! `toSource`, are in [`dollar`].
|
||||
//!
|
||||
//! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the
|
||||
//! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`.
|
||||
|
||||
pub mod console;
|
||||
pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod include;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
@@ -94,7 +96,7 @@ const MAX_BRIDGE_BYTES: u64 = 4 << 30;
|
||||
/// The version `vc.api.version` gives.
|
||||
pub const API_VERSION: &str = "1.0";
|
||||
/// The features `vc.api.has` knows.
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs"];
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"];
|
||||
/// The most commands a run's report lists in `slowestCommands`.
|
||||
pub const SLOWEST_COMMANDS: usize = 5;
|
||||
|
||||
@@ -153,6 +155,8 @@ pub(crate) struct Request {
|
||||
pub source: String,
|
||||
pub args: Map<String, Value>,
|
||||
pub fuel: u64,
|
||||
/// The locale the run starts with (`$.locale`).
|
||||
pub locale: String,
|
||||
/// The answers to the dialogs of a run with nobody to ask, in order.
|
||||
pub answers: Vec<DialogAnswer>,
|
||||
}
|
||||
@@ -166,21 +170,27 @@ thread_local! {
|
||||
static NEXT_JOB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
/// A session's hold on its running job: while one exists the lease is held. Dropping it ends the job.
|
||||
/// It keeps the run's number and its name as console lines give it, so the run's console entry can
|
||||
/// end when the job is gone.
|
||||
#[derive(Debug)]
|
||||
pub struct JobKey(u64);
|
||||
pub struct JobKey {
|
||||
id: u64,
|
||||
run: u64,
|
||||
name: Arc<str>,
|
||||
}
|
||||
|
||||
impl Drop for JobKey {
|
||||
fn drop(&mut self) {
|
||||
let _ = JOBS.try_with(|jobs| {
|
||||
if let Ok(mut jobs) = jobs.try_borrow_mut() {
|
||||
jobs.remove(&self.0);
|
||||
jobs.remove(&self.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn with_job<T>(key: &JobKey, f: impl FnOnce(&mut Job) -> T) -> Option<T> {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.0).map(f))
|
||||
JOBS.with(|jobs| jobs.borrow_mut().get_mut(&key.id).map(f))
|
||||
}
|
||||
|
||||
/// The state a script changes that a rollback puts back.
|
||||
@@ -496,16 +506,19 @@ struct Host {
|
||||
script_map: RefCell<include::SourceMap>,
|
||||
/// The same for each source `$.evalFile` gave, in order.
|
||||
eval_maps: RefCell<Vec<include::SourceMap>>,
|
||||
/// The last error `$.evalFile` raised for a file it could not run, with the file, line and
|
||||
/// column that error is at.
|
||||
eval_failure: RefCell<Option<EvalFailure>>,
|
||||
/// The file, line and column of each error `$.evalFile` raised for a file it could not run, in
|
||||
/// order: the error's mark ([`HostError::Marked`]) is its index.
|
||||
eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>,
|
||||
/// When the run started, where the platform has a clock.
|
||||
started: Option<std::time::Instant>,
|
||||
/// The time since [`Host::started`] at which a `$.sleep` ends.
|
||||
wake_at: Cell<Option<std::time::Duration>>,
|
||||
/// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]).
|
||||
can_wait: Rc<Cell<bool>>,
|
||||
/// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one).
|
||||
eval_strict: Cell<Option<bool>>,
|
||||
}
|
||||
|
||||
/// An error `$.evalFile` raised, as thrown, and the file, line and column it is at.
|
||||
type EvalFailure = (String, Arc<str>, u32, u32);
|
||||
|
||||
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
|
||||
#[derive(Default)]
|
||||
struct Counts {
|
||||
@@ -578,10 +591,64 @@ impl Host {
|
||||
pending.end_line(|line, cut| self.line(console::Entry::Output(line), cut));
|
||||
}
|
||||
}
|
||||
|
||||
/// The time since the run started; none without a clock.
|
||||
fn elapsed(&self) -> Option<std::time::Duration> {
|
||||
#[cfg(test)]
|
||||
if TEST_NO_CLOCK.with(Cell::get) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(d) = TEST_ELAPSED.with(Cell::get) {
|
||||
return Some(d);
|
||||
}
|
||||
self.started.map(|s| s.elapsed())
|
||||
}
|
||||
|
||||
/// `$.sleep`: ends the slice, and the run does not go on until `d` has passed. Without a clock
|
||||
/// it does not wait. A getter, a conversion, a built-in's callback or a file `$.evalFile` runs
|
||||
/// cannot stop at the call, so a wait there is an error, with or without a clock.
|
||||
fn sleep(&self, d: std::time::Duration) -> std::result::Result<(), HostError> {
|
||||
if d.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
if !self.can_wait.get() {
|
||||
return Err(HostError::Error(
|
||||
"$.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if let Some(now) = self.elapsed() {
|
||||
self.wake_at.set(Some(now.saturating_add(d)));
|
||||
self.pause.set(true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The time left of a `$.sleep`, or none when the run is not asleep.
|
||||
fn asleep(&self) -> Option<std::time::Duration> {
|
||||
let wake = self.wake_at.get()?;
|
||||
let left = self.elapsed().map_or(std::time::Duration::ZERO, |now| wake.saturating_sub(now));
|
||||
if left.is_zero() {
|
||||
self.wake_at.set(None);
|
||||
return None;
|
||||
}
|
||||
Some(left)
|
||||
}
|
||||
|
||||
fn over(&self, limit: &str) -> HostError {
|
||||
HostError::Abort(limit.to_string())
|
||||
}
|
||||
|
||||
/// `error`, marked as an error at `file`, `line` and `column`, the place [`located`] gives when
|
||||
/// the run ends with it uncaught.
|
||||
fn placed(&self, error: HostError, file: Arc<str>, line: u32, column: u32) -> HostError {
|
||||
let mut places = self.eval_failures.borrow_mut();
|
||||
let Ok(mark) = u32::try_from(places.len()) else { return error };
|
||||
places.push((file, line, column));
|
||||
HostError::Marked { error: Box::new(error), mark }
|
||||
}
|
||||
|
||||
fn charge_call(&self, bytes: u64) -> std::result::Result<(), HostError> {
|
||||
let calls = self.calls.get() + 1;
|
||||
self.calls.set(calls);
|
||||
@@ -936,8 +1003,9 @@ fn each_line(text: &str, mut done: impl FnMut(String, bool)) {
|
||||
/// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)`
|
||||
/// gives them, one after another, and `$.writeln(...values)` does the same and ends the line.
|
||||
/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file
|
||||
/// being run and `$.includePath` the `#includepath` list.
|
||||
fn dollar_object(host: &Rc<Host>) -> Vec<(String, HostItem)> {
|
||||
/// being run and `$.includePath` the `#includepath` list. Its other members are
|
||||
/// [`dollar::members`].
|
||||
fn dollar_object(host: &Rc<Host>, info: dollar::RunInfo, localization: &Rc<vectorcraft_js::Localization>) -> Vec<(String, HostItem)> {
|
||||
let writer = |end: bool| {
|
||||
let h = host.clone();
|
||||
HostItem::TextFunction(function(move |a| {
|
||||
@@ -966,13 +1034,15 @@ fn dollar_object(host: &Rc<Host>) -> Vec<(String, HostItem)> {
|
||||
strict_writes: Rc::new(move || strict.eval_strict.get()),
|
||||
}
|
||||
};
|
||||
vec![
|
||||
let mut items = vec![
|
||||
("write".into(), writer(false)),
|
||||
("writeln".into(), writer(true)),
|
||||
("evalFile".into(), eval_file),
|
||||
("fileName".into(), getter(include::Files::file_name)),
|
||||
("includePath".into(), getter(include::Files::include_path)),
|
||||
]
|
||||
];
|
||||
items.extend(dollar::members(host, info, localization));
|
||||
items
|
||||
}
|
||||
|
||||
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
|
||||
@@ -994,14 +1064,12 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
|
||||
host.charge_call(path.len() as u64 + 2)?;
|
||||
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
|
||||
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
|
||||
if f.line > 0 {
|
||||
*host.eval_failure.borrow_mut() = Some((message.clone(), f.file.clone(), f.line, f.column));
|
||||
}
|
||||
match f.kind {
|
||||
let error = match f.kind {
|
||||
include::FailKind::Limit => HostError::Abort(message),
|
||||
include::FailKind::Syntax => HostError::Syntax(message),
|
||||
include::FailKind::Error => HostError::Error(message),
|
||||
}
|
||||
};
|
||||
if f.line > 0 { host.placed(error, f.file, f.line, f.column) } else { error }
|
||||
})?;
|
||||
// A file without preprocessor lines is parsed here first, so its syntax error names its place.
|
||||
let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() };
|
||||
@@ -1009,8 +1077,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
|
||||
host.files.borrow_mut().end_eval();
|
||||
let (_, file, line, column) = expanded.map.locate(e.line, e.column);
|
||||
let message = format!("{file}:{line}:{column}: {}", e.message);
|
||||
*host.eval_failure.borrow_mut() = Some((message.clone(), file, line, column));
|
||||
return Err(HostError::Syntax(message));
|
||||
return Err(host.placed(HostError::Syntax(message), file, line, column));
|
||||
}
|
||||
host.eval_maps.borrow_mut().push(expanded.map);
|
||||
host.eval_strict.set(expanded.strict);
|
||||
@@ -1103,18 +1170,20 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
|
||||
(RunError { kind, message, line: f.line, column: f.column }, file)
|
||||
}
|
||||
|
||||
/// `e`, which the realm raised in source `tag` ([`Realm::error_source`]), at the line and column of
|
||||
/// the file it is in, with that file's name unless it is the script's own.
|
||||
fn located(host: &Host, tag: u32, e: &RunError) -> (RunError, Option<Arc<str>>) {
|
||||
/// `e`, which the realm raised in source `tag` ([`Realm::error_source`]) with host error mark `mark`
|
||||
/// ([`Realm::error_mark`]), at the line and column of the file it is in, with that file's name
|
||||
/// unless it is the script's own.
|
||||
fn located(host: &Host, tag: u32, mark: Option<u32>, e: &RunError) -> (RunError, Option<Arc<str>>) {
|
||||
let map = |m: &include::SourceMap, own: bool| {
|
||||
let (index, file, line, column) = m.locate(e.line, e.column);
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
(RunError { kind: e.kind.clone(), message, line, column }, (!own || index > 0).then_some(file))
|
||||
};
|
||||
// An error `$.evalFile` raised for a file it could not run is at that file's place.
|
||||
if let Some((_, file, line, column)) = host.eval_failure.borrow().as_ref().filter(|(thrown, ..)| e.message.contains(thrown.as_str())) {
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, *line, *column) } else { e.message.clone() };
|
||||
return (RunError { kind: e.kind.clone(), message, line: *line, column: *column }, Some(file.clone()));
|
||||
// An error `$.evalFile` raised for a file it could not run, and no script caught, is at that
|
||||
// file's place.
|
||||
if let Some((file, line, column)) = mark.and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
return (RunError { kind: e.kind.clone(), message, line, column }, Some(file));
|
||||
}
|
||||
if e.line == 0 {
|
||||
return (e.clone(), None);
|
||||
@@ -1181,6 +1250,15 @@ impl Session {
|
||||
!self.script_stop.is_set() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.waiting.get())).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The time left of the running script's `$.sleep`, or none when it is not asleep. A run asked
|
||||
/// to stop is not asleep: the next [`Session::script_pump`] ends it.
|
||||
pub fn script_sleep_left(&self) -> Option<std::time::Duration> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.asleep())).flatten()
|
||||
}
|
||||
|
||||
/// The dialog (`alert`, `confirm` or `prompt`) the running script waits at for the person's
|
||||
/// answer. A run asked to stop no longer waits: the next [`Session::script_pump`] ends it.
|
||||
pub fn script_dialog(&self) -> Option<ScriptDialog> {
|
||||
@@ -1230,12 +1308,8 @@ impl Session {
|
||||
/// ([`Self::script_report`]). False with none running.
|
||||
pub fn script_abandon(&mut self) -> bool {
|
||||
let Some(key) = self.script_key.take() else { return false };
|
||||
let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else {
|
||||
drop(key);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
|
||||
self.script_gone(key, console::Ending::Stopped);
|
||||
return true;
|
||||
};
|
||||
drop(key);
|
||||
@@ -1245,6 +1319,19 @@ impl Session {
|
||||
true
|
||||
}
|
||||
|
||||
/// Ends the run whose job is no longer held: its console entry ends with `ending`, with no
|
||||
/// report line, since its time and host calls went with the job, and the session's state is
|
||||
/// put back as at the end of any run.
|
||||
fn script_gone(&mut self, key: JobKey, ending: console::Ending) {
|
||||
let line = console::ConsoleLine { run: key.run, name: key.name.clone(), entry: console::Entry::End(ending) };
|
||||
self.script_console.push(line, false);
|
||||
drop(key);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
}
|
||||
|
||||
/// A script can't start while a document holds a drag in progress or an undo group, which its
|
||||
/// one undo step could not take in.
|
||||
fn settle_for_script(&mut self) -> Result<()> {
|
||||
@@ -1278,6 +1365,7 @@ impl Session {
|
||||
};
|
||||
let limits = Limits { fuel: request.fuel, heap_bytes: HEAP_BYTES, ..Limits::default() };
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() };
|
||||
let strict = options.strict;
|
||||
let mut realm = Realm::with_options(options, limits);
|
||||
realm.share_interrupt(&self.script_stop);
|
||||
realm.set_data_limits(DataLimits::default());
|
||||
@@ -1309,24 +1397,30 @@ impl Session {
|
||||
files: RefCell::new(files),
|
||||
script_map: RefCell::default(),
|
||||
eval_maps: RefCell::default(),
|
||||
eval_failure: RefCell::default(),
|
||||
eval_failures: RefCell::default(),
|
||||
started: clock(),
|
||||
wake_at: Cell::new(None),
|
||||
can_wait: realm.wait_flag(),
|
||||
eval_strict: Cell::new(None),
|
||||
});
|
||||
let args = to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0))
|
||||
.map_err(|place| EngineError::BadParams { cmd: "script.run".into(), msg: format!("`args{place}` is nested more than 64 levels deep") })?;
|
||||
let line = console::ConsoleLine { run: host.run, name: host.name.clone(), entry: console::Entry::Start };
|
||||
self.script_console.push(line, false);
|
||||
let info = dollar::RunInfo { locale: request.locale, strict };
|
||||
let localization = realm.localization();
|
||||
let started = match expanded {
|
||||
Err(f) => Err(preprocessor_error(f)),
|
||||
Ok(expanded) => {
|
||||
*host.script_map.borrow_mut() = expanded.map;
|
||||
realm.set_strict_writes(expanded.strict == Some(true));
|
||||
realm
|
||||
.define_host_object("vc", vc_object(&host, args))
|
||||
.and_then(|()| realm.define_host_object("$", dollar_object(&host)))
|
||||
.add_script_extensions()
|
||||
.and_then(|()| realm.define_host_object("vc", vc_object(&host, args)))
|
||||
.and_then(|()| realm.define_host_object("$", dollar_object(&host, info, &localization)))
|
||||
.and_then(|()| dialogs::install(&mut realm, &host))
|
||||
.and_then(|()| realm.start(&expanded.source))
|
||||
.map_err(|e| located(&host, realm.error_source(), &e))
|
||||
.map_err(|e| located(&host, realm.error_source(), realm.error_mark(), &e))
|
||||
}
|
||||
};
|
||||
if let Err((e, file)) = started {
|
||||
@@ -1337,10 +1431,11 @@ impl Session {
|
||||
return Err(EngineError::Other(message));
|
||||
}
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
let (run, line_name) = (host.run, host.name.clone());
|
||||
let job = Job { realm, host, world: World::working(self), start_uids: open, name: name.clone(), scope };
|
||||
let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(id, job));
|
||||
self.script_key = Some(JobKey(id));
|
||||
self.script_key = Some(JobKey { id, run, name: line_name });
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
@@ -1348,14 +1443,15 @@ impl Session {
|
||||
/// run has ended: its report, or the error that ended it, with the documents put back.
|
||||
pub fn script_pump(&mut self) -> Option<Result<Value>> {
|
||||
let key = self.script_key.take()?;
|
||||
let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.0)) else {
|
||||
let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
|
||||
self.script_gone(key, console::Ending::Internal);
|
||||
return Some(Err(EngineError::Other(JOB_GONE.to_string())));
|
||||
};
|
||||
if let Some(e) = job.host.dialogs.take_failure() {
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
if (job.host.waiting.get() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job));
|
||||
if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
}
|
||||
@@ -1377,7 +1473,7 @@ impl Session {
|
||||
}
|
||||
Ok(Err(e)) => Some(self.script_failed(job, &e)),
|
||||
Ok(Ok(Progress::Paused)) => {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.0, job));
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
}
|
||||
@@ -1398,7 +1494,7 @@ impl Session {
|
||||
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
|
||||
job.host.dialogs.stopped();
|
||||
let fuel_left = job.realm.fuel_left();
|
||||
let (e, file) = located(&job.host, job.realm.error_source(), e);
|
||||
let (e, file) = located(&job.host, job.realm.error_source(), job.realm.error_mark(), e);
|
||||
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
|
||||
close_run(self, &job.host, &mut report, ending(&e.kind));
|
||||
drop(job);
|
||||
@@ -1496,6 +1592,11 @@ impl Session {
|
||||
if self.script_waiting() || self.script_dialog().is_some() {
|
||||
self.script_stop.set();
|
||||
}
|
||||
// A `$.sleep` waits here, where nothing is drawn, instead of turning the loop over.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(left) = self.script_sleep_left() {
|
||||
std::thread::sleep(left.min(std::time::Duration::from_millis(100)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1648,6 +1749,13 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
r
|
||||
}
|
||||
|
||||
/// Tests: removes the session's running job while the session keeps its hold on it. → whether a
|
||||
/// job was removed.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn forget_job(s: &Session) -> bool {
|
||||
s.script_key.as_ref().is_some_and(|k| JOBS.with(|jobs| jobs.borrow_mut().remove(&k.id)).is_some())
|
||||
}
|
||||
|
||||
/// The objects a run may add before it is asked to continue or stop.
|
||||
fn growth_objects() -> u64 {
|
||||
#[cfg(test)]
|
||||
@@ -1676,4 +1784,8 @@ thread_local! {
|
||||
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the `JSINCLUDE` folders in place of the environment's.
|
||||
pub(crate) static TEST_JSINCLUDE: RefCell<Option<Vec<std::path::PathBuf>>> = const { RefCell::new(None) };
|
||||
/// Tests: the time since a run started, in place of its clock's.
|
||||
pub(crate) static TEST_ELAPSED: Cell<Option<std::time::Duration>> = const { Cell::new(None) };
|
||||
/// Tests: runs have no clock, as in a wasm build.
|
||||
pub(crate) static TEST_NO_CLOCK: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
@@ -152,6 +152,7 @@ mod saveoptions;
|
||||
mod scalestrokes;
|
||||
mod script_console;
|
||||
mod script_dialogs;
|
||||
mod script_dollar;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
mod script_run;
|
||||
|
||||
@@ -903,6 +903,29 @@ fn gradients_and_patterns_on_a_picked_object_are_taken() {
|
||||
assert_eq!((undo_steps(&s), &s.paint.fill), (undo, &fill), "nothing changes");
|
||||
}
|
||||
|
||||
/// A stop selected on the whole instance's gradient is not selected once a part of its art is
|
||||
/// picked, so the Gradient tool does not take Delete for it, and is selected again when the whole
|
||||
/// instance is.
|
||||
#[test]
|
||||
fn picking_a_part_leaves_no_gradient_stop_selected() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
let g = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]});
|
||||
s.execute("select.set", &json!({"ids": [inst.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": g})).unwrap();
|
||||
s.fill_active = true;
|
||||
let view = ViewInfo::default();
|
||||
s.select_tool("gradient", view).unwrap();
|
||||
s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
|
||||
assert_eq!(s.selected_stop(), Some(1));
|
||||
assert!(s.tool_claims_key(vectorcraft_tools::ToolKey::Delete, view));
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
assert_eq!(s.selected_stop(), None);
|
||||
assert!(!s.tool_claims_key(vectorcraft_tools::ToolKey::Delete, view));
|
||||
s.execute("select.set", &json!({"ids": [inst.0]})).unwrap();
|
||||
assert_eq!(s.selected_stop(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_and_blend_on_a_picked_object_go_through_transparency_set() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1481,6 +1481,22 @@ fn rasterize_refuses_an_image_longer_than_the_renderer_draws() {
|
||||
assert!(close(b.y0, vb.y0) && b.y1 >= vb.y1, "{b:?} covers {vb:?}");
|
||||
}
|
||||
|
||||
/// Art that snaps to exactly 32,768 pixels a side is rasterized, wherever it is on the canvas.
|
||||
#[test]
|
||||
fn rasterize_takes_art_that_snaps_to_32768_pixels_a_side() {
|
||||
let scale = 400.0 / 72.0;
|
||||
for y in [100_000.0, 250_000.0, 333_333.3, 777_777.7] {
|
||||
let mut s = session();
|
||||
let probe = rect(&mut s, 10.0, y, 100.0, 5898.0);
|
||||
let vb = s.doc().unwrap().doc.bounds_of(&[probe], true).unwrap();
|
||||
let h = 5898.0 + (32_767.8 / scale - vb.height());
|
||||
let a = rect(&mut s, 200.0, y, 100.0, h);
|
||||
sel(&mut s, &[a]);
|
||||
let r = s.execute("object.rasterize", &json!({"ppi": 400, "padding": 0})).unwrap_or_else(|e| panic!("at y = {y}: {e}"));
|
||||
assert_eq!(r["height"].as_u64(), Some(u64::from(vectorcraft_render::MAX_RASTER_SIDE)), "at y = {y}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rasterize refuses a resolution given as text or as another value that is not a number, and the
|
||||
/// selected art stays as it was.
|
||||
#[test]
|
||||
|
||||
@@ -1315,6 +1315,25 @@ fn plugin_management_commands() {
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
/// Clearing the Additional Plug-ins Folder forgets the folder: setting the same folder again
|
||||
/// installs what is in it, as setting any other folder does.
|
||||
#[test]
|
||||
fn plugins_folder_set_again_after_clearing_installs_its_plugins() {
|
||||
let dir = crate::tests_links::Folder::new("plugin-folder-cleared");
|
||||
let id = "test.engine.foldercleared";
|
||||
let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#);
|
||||
std::fs::write(dir.0.join("cleared.wasm"), wat::parse_str(src).unwrap()).unwrap();
|
||||
let mut s = session();
|
||||
let folder = json!({"key": "pluginsFolder", "value": dir.0.display().to_string()});
|
||||
run(&mut s, "prefs.set", folder.clone());
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed from the folder");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
run(&mut s, "prefs.set", json!({"key": "pluginsFolder", "value": ""}));
|
||||
run(&mut s, "prefs.set", folder);
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed again when the folder is set again");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// #2541: a plug-in installed in a session with a plug-in store is installed again in the next
|
||||
/// session that attaches the store, and Remove Plug-in takes it out of the store.
|
||||
#[test]
|
||||
|
||||
@@ -170,6 +170,55 @@ fn a_stopped_run_reports_its_diagnostics_and_its_unended_line() {
|
||||
assert_eq!(texts(&mut s, "end"), ["ended: stopped"]);
|
||||
}
|
||||
|
||||
/// A report line counts one host call in the singular, and gives a run without a clock as "time
|
||||
/// unavailable".
|
||||
#[test]
|
||||
fn a_report_line_counts_one_host_call_in_the_singular_and_says_when_time_is_unavailable() {
|
||||
use crate::script::console::{Entry, Slow};
|
||||
let report = |ms: Option<u64>, host_calls: u64| Entry::Report { ms, host_calls, slowest: vec![] }.text();
|
||||
assert_eq!(report(Some(3), 0), "3 ms, 0 host calls");
|
||||
assert_eq!(report(Some(3), 1), "3 ms, 1 host call");
|
||||
assert_eq!(report(Some(0), 2), "0 ms, 2 host calls");
|
||||
assert_eq!(report(None, 0), "time unavailable, 0 host calls");
|
||||
assert_eq!(report(None, 1), "time unavailable, 1 host call");
|
||||
assert_eq!(report(None, 2), "time unavailable, 2 host calls");
|
||||
let slowest = vec![Slow { id: "a.b".into(), calls: 1, total_ms: 4, max_ms: 4 }];
|
||||
assert_eq!(Entry::Report { ms: None, host_calls: 1, slowest }.text(), "time unavailable, 1 host call; slowest: a.b ×1 4 ms");
|
||||
}
|
||||
|
||||
/// A run whose job is gone still ends its console entry, once, with its own number and name and no
|
||||
/// report line: as stopped when it is abandoned, as an internal fault when a slice finds it gone.
|
||||
/// The session can start the next run.
|
||||
#[test]
|
||||
fn a_run_whose_job_is_gone_still_ends_its_console_entry() {
|
||||
for abandon in [true, false] {
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
run(&mut s, "$.writeln('one'); while (true) {}").unwrap();
|
||||
assert!(s.script_pump().is_none());
|
||||
assert!(script::forget_job(&s));
|
||||
if abandon {
|
||||
assert!(s.script_abandon());
|
||||
} else {
|
||||
let e = s.script_pump().unwrap().unwrap_err();
|
||||
assert_eq!(e.to_string(), "the script's run is no longer available");
|
||||
}
|
||||
assert!(!s.script_running());
|
||||
let all = lines(&mut s);
|
||||
let kinds: Vec<&str> = all.iter().map(|(_, k, _)| k.as_str()).collect();
|
||||
assert_eq!(kinds, ["start", "output", "end"], "{all:?}");
|
||||
assert_eq!(all[2].2, if abandon { "ended: stopped" } else { "ended: internal" });
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
assert_eq!((c["lines"][2]["run"].as_u64(), c["lines"][2]["name"].as_str()), (Some(1), Some("t.js")));
|
||||
assert!(!s.script_abandon() && s.script_pump().is_none(), "nothing is left to end");
|
||||
assert_eq!(lines(&mut s).len(), 3, "the entry ends once");
|
||||
s.script_frames = false;
|
||||
run(&mut s, "$.writeln('two')").unwrap();
|
||||
assert_eq!(texts(&mut s, "end").last().map(String::as_str), Some("ended: finished"), "the next run starts");
|
||||
assert_eq!(lines(&mut s).last().map(|l| l.0), Some(2));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_are_numbered_a_busy_run_adds_nothing_and_clear_keeps_the_report() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize` and
|
||||
//! `toSource`, and what of them one run keeps to itself.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::script::{TEST_ELAPSED, TEST_NO_CLOCK};
|
||||
use crate::*;
|
||||
|
||||
/// The values `source` gives `vc.log`, in a run of its text.
|
||||
fn logged(s: &mut Session, source: &str) -> Value {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_or_else(|e| panic!("{source}: {e}"))["log"].clone()
|
||||
}
|
||||
|
||||
/// The one value `expr` gives, logged.
|
||||
fn value(s: &mut Session, expr: &str) -> Value {
|
||||
logged(s, &format!("vc.log({expr});"))[0].clone()
|
||||
}
|
||||
|
||||
/// The name of the error `statement` throws and its message, as `Name: message`.
|
||||
fn thrown(s: &mut Session, statement: &str) -> String {
|
||||
value(s, &format!("(function () {{ try {{ {statement}; return 'no error'; }} catch (e) {{ return e.name + ': ' + e.message; }} }})()"))
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_member_has_its_value() {
|
||||
let mut s = Session::new();
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let os = if cfg!(target_arch = "wasm32") {
|
||||
"Web"
|
||||
} else if cfg!(windows) {
|
||||
"Windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"macOS"
|
||||
} else if cfg!(target_os = "linux") {
|
||||
"Linux"
|
||||
} else if cfg!(target_os = "freebsd") {
|
||||
"FreeBSD"
|
||||
} else {
|
||||
"Unix"
|
||||
};
|
||||
for (expr, want) in [
|
||||
("$.about()", json!(format!("VectorCraft script engine {version}"))),
|
||||
("$.appEncoding", json!("UTF-8")),
|
||||
("$.build", json!(version)),
|
||||
("$.buildDate", json!(null)),
|
||||
("$.decimalPoint", json!(".")),
|
||||
("$.engineName", json!("VectorCraft")),
|
||||
("$.error", json!(null)),
|
||||
("$.flags", json!(0)),
|
||||
("$.gc() === undefined", json!(true)),
|
||||
("$.global === this", json!(true)),
|
||||
("typeof $.hiresTimer === 'number' && $.hiresTimer >= 0", json!(true)),
|
||||
("$.level", json!(0)),
|
||||
("\n$.line", json!(2)),
|
||||
("$.locale", json!("en")),
|
||||
("$.localize", json!(false)),
|
||||
("$.memCache", json!(0)),
|
||||
("$.os", json!(os)),
|
||||
("$.screens.length", json!(0)),
|
||||
("$.stack", json!("[global]:1\n")),
|
||||
("$.strict", json!(false)),
|
||||
("$.version", json!(version)),
|
||||
("typeof $.getenv + typeof $.setenv + typeof $.sleep", json!("functionfunctionfunction")),
|
||||
("vc.api.has('dollar')", json!(true)),
|
||||
] {
|
||||
assert_eq!(value(&mut s, expr), want, "{expr}");
|
||||
}
|
||||
assert_eq!(thrown(&mut s, "$.bp()"), "Error: $.bp: scripts here have no debugger");
|
||||
assert_eq!(thrown(&mut s, "$.colorPicker(0)"), "Error: $.colorPicker: scripts cannot show a dialog yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_members_keep_their_values_and_settable_ones_check_what_they_are_given() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(value(&mut s, "($.build = 'x', $.level = 3, $.os = 'y', [$.build === 'x', $.level, $.os === 'y'])"), json!([false, 0, false]));
|
||||
assert!(thrown(&mut s, "(function () { 'use strict'; $.version = '9'; })()").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "(function () { 'use strict'; $.error = null; })()").starts_with("TypeError"));
|
||||
assert_eq!(value(&mut s, "($.appEncoding = 'utf-8', $.appEncoding)"), json!("UTF-8"));
|
||||
assert!(thrown(&mut s, "$.appEncoding = 'ISO-8859-1'").starts_with("RangeError"));
|
||||
assert!(thrown(&mut s, "$.appEncoding = 8").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "$.memCache = 1024").starts_with("Error"));
|
||||
assert_eq!(value(&mut s, "($.flags = 512, [$.flags, $.localize])"), json!([512, true]));
|
||||
assert_eq!(value(&mut s, "($.flags = 512, $.flags = 0, [$.flags, $.localize])"), json!([0, false]));
|
||||
for bad in ["$.flags = 2", "$.flags = 513", "$.flags = -512"] {
|
||||
assert!(thrown(&mut s, bad).starts_with("RangeError"), "{bad}");
|
||||
}
|
||||
assert!(thrown(&mut s, "$.flags = '512'").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "$.localize = 1").starts_with("TypeError"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_locale_starts_as_the_interfaces_and_a_change_lasts_one_run() {
|
||||
let mut s = Session::new();
|
||||
for (ui, want) in [("de", "de"), ("pt-br", "pt_BR"), ("zh-hant", "zh_TW"), ("zh-hans", "zh_CN"), ("auto", "en"), ("x", "en")] {
|
||||
s.ui_language = Some(ui.into());
|
||||
assert_eq!(value(&mut s, "$.locale"), json!(want), "{ui}");
|
||||
}
|
||||
s.ui_language = None;
|
||||
s.prefs.interface_language = "fr".into();
|
||||
assert_eq!(value(&mut s, "$.locale"), json!("fr"), "without a language from the app, the preference");
|
||||
s.ui_language = Some("de".into());
|
||||
let lookup = "localize({en: 'e', de: 'd', fr: 'f', fr_CA: 'c'})";
|
||||
assert_eq!(value(&mut s, &format!("[{lookup}, $.decimalPoint]")), json!(["d", ","]));
|
||||
let changed = format!(
|
||||
"$.locale = 'FR-ca'; var a = [$.locale, {lookup}]; $.locale = 'fr'; a.push({lookup}); $.locale = null; a.push($.locale, {lookup}); a"
|
||||
);
|
||||
assert_eq!(value(&mut s, &format!("(function () {{ {changed}; return a; }})()")), json!(["fr_CA", "c", "f", "de", "d"]));
|
||||
assert_eq!(value(&mut s, "($.locale = '', $.locale)"), json!("de"), "an empty locale is the interface's");
|
||||
assert_eq!(value(&mut s, "($.locale = 'en_US', $.locale)"), json!("en_US"));
|
||||
assert_eq!(value(&mut s, "$.locale"), json!("de"), "the next run starts with the interface's again");
|
||||
for bad in ["$.locale = 'german'", "$.locale = 'de_DE_x'", "$.locale = 'd'"] {
|
||||
assert!(thrown(&mut s, bad).starts_with("RangeError"), "{bad}");
|
||||
}
|
||||
assert!(thrown(&mut s, "$.locale = 5").starts_with("TypeError"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localized_to_string_is_on_only_while_the_run_turns_it_on() {
|
||||
let mut s = Session::new();
|
||||
s.ui_language = Some("de".into());
|
||||
let text = "String({en: 'Open', de: 'Öffnen'})";
|
||||
assert_eq!(value(&mut s, text), json!("[object Object]"));
|
||||
assert_eq!(value(&mut s, &format!("($.localize = true, {text})")), json!("Öffnen"));
|
||||
assert_eq!(value(&mut s, text), json!("[object Object]"), "the next run starts with it off");
|
||||
assert_eq!(value(&mut s, "localize('%1 of %2', 3, 7)"), json!("3 of 7"), "localize works with it off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_source_writes_plain_data() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(value(&mut s, "toSource({a: [1, 'x'], b: null})"), json!(r#"({"a":[1, "x"], "b":null})"#));
|
||||
assert_eq!(value(&mut s, "[true, 2].toSource()"), json!("[true, 2]"));
|
||||
assert!(thrown(&mut s, "var o = {}; o.o = o; toSource(o)").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "toSource(vc)").starts_with("TypeError"), "a host object is not plain data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() {
|
||||
let mut s = Session::new();
|
||||
for name in ["HOME", "PATH", "USERPROFILE", "TEMP", "lang", ""] {
|
||||
assert_eq!(value(&mut s, &format!("$.getenv('{name}')")), json!(null), "{name}");
|
||||
}
|
||||
let process = std::env::var("OS").ok();
|
||||
let before = value(&mut s, "$.getenv('OS')");
|
||||
if let Some(os) = process.as_deref().filter(|v| v.len() <= 64 && v.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-@".contains(&b))) {
|
||||
assert_eq!(before, json!(os));
|
||||
}
|
||||
assert_eq!(value(&mut s, "($.setenv('OS', 'Test-1'), $.getenv('OS'))"), json!("Test-1"));
|
||||
assert_eq!(std::env::var("OS").ok(), process, "the process's environment stays as it was");
|
||||
assert_eq!(value(&mut s, "$.getenv('OS')"), before, "the next run reads the process's value again");
|
||||
assert!(thrown(&mut s, "$.setenv('HOME', 'x')").starts_with("Error"));
|
||||
assert!(thrown(&mut s, "$.setenv('LANG', 'a b')").starts_with("RangeError"));
|
||||
assert!(thrown(&mut s, &format!("$.setenv('LANG', '{}')", "a".repeat(65))).starts_with("RangeError"));
|
||||
assert!(thrown(&mut s, "$.setenv('LANG')").starts_with("TypeError"));
|
||||
assert!(thrown(&mut s, "$.getenv(1)").starts_with("TypeError"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_line_and_stack_follow_the_running_code() {
|
||||
let mut s = Session::new();
|
||||
let source = "try { null.x; } catch (e) {}\nfunction where() {\n return [$.line, $.stack, $.error instanceof TypeError];\n}\nvc.log(where());";
|
||||
assert_eq!(logged(&mut s, source)[0], json!([3, "[global]:5\nwhere:3\n", true]));
|
||||
assert_eq!(value(&mut s, "$.error"), json!(null), "each run starts without one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_waits_between_slices_until_its_time_has_passed() {
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
TEST_ELAPSED.set(Some(Duration::ZERO));
|
||||
s.execute("script.run", &json!({"source": "vc.log(1); $.sleep(250); vc.log(2);", "name": "t.js"})).unwrap();
|
||||
let logs =
|
||||
|s: &mut Session| s.execute("script.console", &json!({})).unwrap()["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "log").count();
|
||||
assert!(s.script_pump().is_none());
|
||||
assert_eq!(logs(&mut s), 1);
|
||||
TEST_ELAPSED.set(Some(Duration::from_millis(249)));
|
||||
assert!(s.script_pump().is_none());
|
||||
assert!(s.script_pump().is_none());
|
||||
assert_eq!(logs(&mut s), 1, "the run waits");
|
||||
assert_eq!(s.script_sleep_left(), Some(Duration::from_millis(1)), "the app can wait this long before the next frame");
|
||||
TEST_ELAPSED.set(Some(Duration::from_millis(250)));
|
||||
let r = s.script_pump().unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([1, 2]));
|
||||
TEST_ELAPSED.set(None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sleeping_run_stops_when_asked() {
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
TEST_ELAPSED.set(Some(Duration::ZERO));
|
||||
s.execute("script.run", &json!({"source": "$.sleep(1000); vc.log(2);", "name": "t.js"})).unwrap();
|
||||
assert!(s.script_pump().is_none());
|
||||
assert_eq!(s.script_sleep_left(), Some(Duration::from_secs(1)));
|
||||
s.execute("script.stop", &json!({})).unwrap();
|
||||
assert_eq!(s.script_sleep_left(), None, "a run asked to stop does not wait");
|
||||
assert!(s.script_pump().unwrap().is_err());
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "stopped");
|
||||
TEST_ELAPSED.set(None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_takes_milliseconds_from_0_to_1000() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(value(&mut s, "($.sleep(0), $.sleep(1), 'woke')"), json!("woke"));
|
||||
for bad in ["$.sleep(-1)", "$.sleep(1001)"] {
|
||||
assert!(thrown(&mut s, bad).starts_with("RangeError"), "{bad}");
|
||||
}
|
||||
for bad in ["$.sleep()", "$.sleep('5')", "$.sleep(NaN)", "$.sleep(Infinity)"] {
|
||||
assert!(thrown(&mut s, bad).starts_with("TypeError"), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_throws_where_the_run_cannot_wait_instead_of_running_on() {
|
||||
let mut s = Session::new();
|
||||
s.script_frames = true;
|
||||
TEST_ELAPSED.set(Some(Duration::ZERO));
|
||||
let source = "var o = {}; Object.defineProperty(o, 'x', { get: function () { $.sleep(250); vc.log('after'); return 1; } });
|
||||
try { o.x; } catch (e) { vc.log(e.name + ': ' + e.message); }
|
||||
try { [1].map(function () { $.sleep(250); vc.log('after'); }); } catch (e) { vc.log(e.name + ': ' + e.message); }
|
||||
[1].map(function () { $.sleep(0); });
|
||||
vc.log('done');";
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap();
|
||||
let r = s.script_pump().expect("the run does not wait").unwrap();
|
||||
TEST_ELAPSED.set(None);
|
||||
let message = "Error: $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code";
|
||||
assert_eq!(r["log"], json!([message, message, "done"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleep_throws_where_the_run_cannot_wait_without_a_clock_too() {
|
||||
let mut s = Session::new();
|
||||
TEST_NO_CLOCK.set(true);
|
||||
let source = "var o = {}; Object.defineProperty(o, 'x', { get: function () { $.sleep(250); return 1; } });
|
||||
try { o.x; vc.log('no error'); } catch (e) { vc.log(e.name); }
|
||||
$.sleep(250);
|
||||
vc.log('done');";
|
||||
let log = logged(&mut s, source);
|
||||
TEST_NO_CLOCK.set(false);
|
||||
assert_eq!(log, json!(["Error", "done"]), "the script's own code does not wait without a clock");
|
||||
}
|
||||
@@ -509,3 +509,57 @@ fn script_dialogs_in_included_and_evaluated_files() {
|
||||
assert_eq!(report["dialogs"][0]["answer"], true, "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The line, column and file name of a failed run's report, and its console error line (the only
|
||||
/// line of a run without output that starts with the script's name).
|
||||
fn place(report: &Value) -> (u64, u64, Option<&str>, &str) {
|
||||
let file = report.get("file").map(|f| f.as_str().unwrap().rsplit(['/', '\\']).next().unwrap());
|
||||
let lines = report["console"]["lines"].as_array().unwrap();
|
||||
let error = lines.iter().filter_map(Value::as_str).find(|l| l.starts_with("main.jsx")).unwrap();
|
||||
(report["line"].as_u64().unwrap(), report["column"].as_u64().unwrap(), file, error)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_eval_file_error_caught_and_thrown_again_is_at_the_new_throw() {
|
||||
let base = folder("rethrow");
|
||||
write(&base.join("main/sub/broken.jsx"), "var a = 1;\n\nvar = 2;");
|
||||
write(&base.join("main/sub/directive.jsx"), "\n#frobnicate 1");
|
||||
write(&base.join("main/sub/rethrow.jsx"), "var r = 1;\n throw saved;");
|
||||
write(&base.join("main/sub/outer.jsx"), "var q = 1;\n$.evalFile('broken.jsx');");
|
||||
write(&base.join("main/sub/outer2.jsx"), "try { $.evalFile('broken.jsx'); } catch (e) {\n\n throw e;\n}");
|
||||
let caught = "var saved;\ntry { $.evalFile('sub/broken.jsx'); } catch (e) { saved = e; }\n";
|
||||
let cases = [
|
||||
// Thrown again in the script, or in another file $.evalFile runs.
|
||||
(format!("{caught}var b = 2;\n throw saved;"), (4, 3, None)),
|
||||
(format!("{caught}$.evalFile('sub/rethrow.jsx');"), (2, 3, Some("rethrow.jsx"))),
|
||||
// A new error whose message holds the failure's text, or is the same text.
|
||||
(format!("{caught}throw new Error(saved.message);"), (3, 1, None)),
|
||||
(format!("{caught}throw new SyntaxError(saved.message);"), (3, 1, None)),
|
||||
// A second failure, caught, does not move the first one.
|
||||
(format!("{caught}try {{ $.evalFile('sub/directive.jsx'); }} catch (e) {{}}\n throw saved;"), (4, 2, None)),
|
||||
// A second failure, uncaught, is at its own file's place.
|
||||
(format!("{caught}$.evalFile('sub/directive.jsx');"), (2, 1, Some("directive.jsx"))),
|
||||
// An uncaught failure is at the file's place, through a finally block and from a nested file.
|
||||
("var a = 1;\ntry { $.evalFile('sub/broken.jsx'); } finally { a = 2; }".to_string(), (3, 5, Some("broken.jsx"))),
|
||||
("$.evalFile('sub/outer.jsx');".to_string(), (3, 5, Some("broken.jsx"))),
|
||||
// Caught in a nested file and thrown again there.
|
||||
("$.evalFile('sub/outer2.jsx');".to_string(), (3, 5, Some("outer2.jsx"))),
|
||||
// A failure caught in a run after one that failed with it, and a different error.
|
||||
("try { $.evalFile('sub/broken.jsx'); } catch (e) {}\nthrow new Error('other');".to_string(), (2, 1, None)),
|
||||
];
|
||||
let mut s = Session::new();
|
||||
let main = base.join("main/main.jsx");
|
||||
for (text, (line, column, file)) in cases {
|
||||
write(&main, &text);
|
||||
assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "{text}");
|
||||
let report = s.script_report().unwrap().clone();
|
||||
let (l, c, f, error) = place(&report);
|
||||
assert_eq!((report["kind"].as_str(), l, c, f), (Some("thrown"), line, column, file), "{text}\n{report}");
|
||||
let at = match file {
|
||||
Some(f) => format!("{f}:{line}:{column}: "),
|
||||
None => format!("main.jsx:{line}:{column}: "),
|
||||
};
|
||||
assert!(error.starts_with("main.jsx") && error.contains(&at), "{error}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -284,6 +284,151 @@ fn pasted_art_with_a_filter_at_the_size_limit_still_draws_when_renamed() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A pasted filter is not renamed to a name an effect in the document already gives, even one whose
|
||||
/// filter was deleted, so defining a filter of that name later changes only that effect.
|
||||
#[test]
|
||||
fn pasted_art_takes_no_name_the_documents_effects_use() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgFilter.define", json!({"xml": r#"<filter id="Shift 2"><feOffset dx="1" dy="1"/></filter>"#}));
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Shift 2", "ids": [a.0]}));
|
||||
run(&mut s, "svgFilter.delete", json!({"name": "Shift 2"}));
|
||||
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{SHIFT_MORE}</defs><rect width="30" height="30" filter="url(#Shift)"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let names: Vec<String> = filter_effects(&s).into_iter().map(|(n, _)| n).collect();
|
||||
assert_eq!(names, ["Shift 2", "Shift 3"]);
|
||||
}
|
||||
|
||||
/// A pasted filter is not renamed to a name an effect in a brush's art gives either.
|
||||
#[test]
|
||||
fn pasted_art_takes_no_name_the_documents_brushes_use() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgFilter.define", json!({"xml": r#"<filter id="Shift 2"><feOffset dx="1" dy="1"/></filter>"#}));
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Shift 2", "ids": [a.0]}));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
run(&mut s, "brush.new", json!({"type": "art", "name": "Fx"}));
|
||||
run(&mut s, "edit.clear", json!({"ids": [a.0]}));
|
||||
run(&mut s, "svgFilter.delete", json!({"name": "Shift 2"}));
|
||||
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{SHIFT_MORE}</defs><rect width="30" height="30" filter="url(#Shift)"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let names: Vec<String> = filter_effects(&s).into_iter().map(|(n, _)| n).collect();
|
||||
assert_eq!(names, ["Shift 3"]);
|
||||
}
|
||||
|
||||
/// A pasted filter at the size limit with a one-letter name takes a free capital letter when every
|
||||
/// lowercase letter and digit is in use.
|
||||
#[test]
|
||||
fn a_renamed_paste_takes_a_free_capital_letter() {
|
||||
let mut s = session();
|
||||
for n in ('a'..='z').chain('0'..='9') {
|
||||
run(&mut s, "svgFilter.define", json!({"xml": one_char_filter(n)}));
|
||||
}
|
||||
run(&mut s, "svgFilter.define", json!({"xml": r#"<filter id="S"><feOffset dx="3" dy="3"/></filter>"#}));
|
||||
let (open, close) = (r#"<filter id="S"><feOffset dx="9" dy="9" result=""#, r#""/></filter>"#);
|
||||
let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len()));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{big}</defs><rect width="30" height="30" filter="url(#S)"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let pasted = filter_effects(&s);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(pasted[0].0, "A");
|
||||
assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok("A".to_string()));
|
||||
assert!(pasted[0].1.contains("dx=\"9\""), "its own filter");
|
||||
}
|
||||
|
||||
/// A filter named `n`, with the characters a quoted attribute value cannot hold escaped.
|
||||
fn one_char_filter(n: char) -> String {
|
||||
let id = match n {
|
||||
'"' => """.to_string(),
|
||||
'&' => "&".to_string(),
|
||||
'<' => "<".to_string(),
|
||||
c => c.to_string(),
|
||||
};
|
||||
format!(r#"<filter id="{id}"><feOffset dx="1" dy="1"/></filter>"#)
|
||||
}
|
||||
|
||||
/// A pasted filter at the size limit with a one-letter name takes a free punctuation character when
|
||||
/// every letter and digit is in use.
|
||||
#[test]
|
||||
fn a_renamed_paste_takes_a_free_punctuation_character() {
|
||||
let mut s = session();
|
||||
for n in ('a'..='z').chain('0'..='9').chain('A'..='Z') {
|
||||
run(&mut s, "svgFilter.define", json!({"xml": one_char_filter(n)}));
|
||||
}
|
||||
let (open, close) = (r#"<filter id="S"><feOffset dx="9" dy="9" result=""#, r#""/></filter>"#);
|
||||
let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len()));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{big}</defs><rect width="30" height="30" filter="url(#S)"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let pasted = filter_effects(&s);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_eq!(pasted[0].0, "!");
|
||||
assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok("!".to_string()));
|
||||
assert!(pasted[0].1.contains("dx=\"9\""), "its own filter");
|
||||
}
|
||||
|
||||
/// A pasted filter at the size limit with a one-letter name, when every free name it could take is
|
||||
/// in use, is refused rather than pasted under the name of the document's filter.
|
||||
#[test]
|
||||
fn a_paste_with_no_free_name_for_its_filter_is_refused() {
|
||||
let mut s = session();
|
||||
for n in ('a'..='z').chain('0'..='9').chain('A'..='Z') {
|
||||
run(&mut s, "svgFilter.define", json!({"xml": one_char_filter(n)}));
|
||||
}
|
||||
// A document holds at most 64 filters: the other one-character names are taken by effects
|
||||
// whose filters were deleted.
|
||||
for n in ('!'..='~').filter(|c| !c.is_ascii_alphanumeric()) {
|
||||
let a = rect(&mut s, 10.0);
|
||||
let name = run(&mut s, "svgFilter.define", json!({"xml": one_char_filter(n)}))["name"].as_str().unwrap().to_string();
|
||||
assert_eq!(name, n.to_string());
|
||||
run(&mut s, "svgFilter.apply", json!({"name": name, "ids": [a.0]}));
|
||||
run(&mut s, "svgFilter.delete", json!({"name": name}));
|
||||
}
|
||||
let (open, close) = (r#"<filter id="S"><feOffset dx="9" dy="9" result=""#, r#""/></filter>"#);
|
||||
let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len()));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{big}</defs><rect width="30" height="30" filter="url(#S)"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
let (before, effects) = (steps(&s), filter_effects(&s).len());
|
||||
assert_eq!(effects, 32);
|
||||
assert!(err(&mut s, "edit.pasteInPlace", json!({})).contains("no free name"));
|
||||
assert_eq!(filter_effects(&s).len(), effects, "nothing pasted");
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
/// A pasted filter whose name holds a tab, a line feed or a carriage return keeps those characters
|
||||
/// in its id under its new name.
|
||||
#[test]
|
||||
fn a_renamed_paste_keeps_whitespace_characters_in_its_id() {
|
||||
for c in ["	", " ", " "] {
|
||||
let mut s = session();
|
||||
run(&mut s, "svgFilter.define", json!({"xml": format!(r#"<filter id="S{c}t"><feOffset dx="3" dy="3"/></filter>"#)}));
|
||||
let svg = format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs><filter id="S{c}t"><feOffset dx="9" dy="9"/></filter></defs><rect width="30" height="30" filter="url(#S{c}t)"/></svg>"#
|
||||
);
|
||||
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
|
||||
run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let pasted = filter_effects(&s);
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert_ne!(pasted[0].0, names(&mut s)[0], "renamed");
|
||||
assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok(pasted[0].0.clone()), "{c}: its id is its name");
|
||||
}
|
||||
}
|
||||
|
||||
/// Art in a symbol's definition that uses a filter follows its edits too.
|
||||
#[test]
|
||||
fn a_symbols_art_follows_a_filter_edit() {
|
||||
|
||||
@@ -522,6 +522,7 @@ fn character_ruby_and_path_handle_refuse_a_param_of_the_wrong_type() {
|
||||
("text.setStyle", json!({"size": 30, "justify": {"value": "center"}}), string("justify")),
|
||||
("text.setStyle", json!({"features": ["dlig", 5]}), tags.clone()),
|
||||
("text.setStyle", json!({"leading": true}), "leading must be a number or \"auto\"".to_string()),
|
||||
("text.setStyle", json!({"leading": "12abc"}), "leading must be a number or \"auto\"".to_string()),
|
||||
("text.setRangeStyle", json!({"id": id.0, "font": 5}), string("font")),
|
||||
("text.setRangeStyle", json!({"id": id.0, "size": 30, "style": false}), string("style")),
|
||||
("text.setRangeStyle", json!({"id": id.0, "features": [null]}), tags),
|
||||
|
||||
@@ -525,6 +525,51 @@ fn many_objects_of_one_name_are_numbered_in_turn() {
|
||||
assert!(text.contains("(Dot_00000000000000019999_)"));
|
||||
}
|
||||
|
||||
/// A document with one top-level layer for each of the 27 layer colour presets, named after its
|
||||
/// position.
|
||||
fn every_layer_preset() -> Document {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.layers.clear();
|
||||
for i in 0..vectorcraft_doc::LAYER_COLORS.len() {
|
||||
let id = doc.alloc_id();
|
||||
doc.layers.push(Arc::new(Node::layer(id, &format!("P{i}"), LayerColor::Preset(u8::try_from(i).unwrap()))));
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
/// #6502: Yellow, Magenta and Cyan (presets 4, 5 and 6) are written as the file's indexes 6, 4
|
||||
/// and 5, with their own RGB beside them; every other preset keeps its position.
|
||||
#[test]
|
||||
fn layer_presets_are_written_with_the_files_colour_index() {
|
||||
let text = program(&every_layer_preset());
|
||||
for (i, (_, [r, g, b])) in vectorcraft_doc::LAYER_COLORS.iter().enumerate() {
|
||||
let index = match i {
|
||||
4 => 6,
|
||||
5 => 4,
|
||||
6 => 5,
|
||||
i => i,
|
||||
};
|
||||
let want = format!(" {index} {r} {g} {b} 0 50 0 Lb\n(P{i}) Ln\n");
|
||||
assert!(text.contains(&want), "missing {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #6502: every preset comes back as itself after a save and an open.
|
||||
#[test]
|
||||
fn layer_presets_survive_a_round_trip() {
|
||||
let doc = read_back(&every_layer_preset());
|
||||
let colors: Vec<LayerColor> = doc
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| match l.kind {
|
||||
NodeKind::Layer { color, .. } => color,
|
||||
_ => panic!("{:?}", l.kind),
|
||||
})
|
||||
.collect();
|
||||
let want: Vec<LayerColor> = (0..27u8).map(LayerColor::Preset).collect();
|
||||
assert_eq!(colors, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_have_fourteen_operands() {
|
||||
let text = program(&sample());
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
use vectorcraft_color::cms::Cms;
|
||||
use vectorcraft_color::swatch::{REGISTRATION, Swatch};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
|
||||
use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath};
|
||||
use vectorcraft_pathops::BoolOp;
|
||||
@@ -449,14 +449,7 @@ impl<'a> Writer<'a> {
|
||||
/// (`Xy`, `0 0 Xd`, `7 () XW`) when it has any, `LB`, `%AI5_EndLayer--`.
|
||||
fn write_layer(&mut self, n: &Node, after: &[Arc<Node>]) {
|
||||
let NodeKind::Layer { color, template, printable, children, clip, preview, dim_images } = &n.kind else { return };
|
||||
let [r, g, b] = match color {
|
||||
LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(*i)).map_or([79, 128, 255], |c| c.1),
|
||||
LayerColor::Custom(rgb) => *rgb,
|
||||
};
|
||||
let index = match color {
|
||||
LayerColor::Preset(i) if usize::from(*i) < LAYER_COLORS.len() => i64::from(*i),
|
||||
_ => -1,
|
||||
};
|
||||
let (index, [r, g, b]) = ai_ops::layer_color(*color);
|
||||
if *template {
|
||||
self.warn(TEMPLATES);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use vectorcraft_color::{Color, Gradient};
|
||||
use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_doc::{LAYER_COLORS, LayerColor, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, SubPath};
|
||||
|
||||
use crate::ps;
|
||||
@@ -62,6 +62,43 @@ pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, editing: bool)
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour index an `.ai` layer's `Lb` gives preset `preset` (its position in
|
||||
/// [`LAYER_COLORS`]). The file numbers Magenta, Cyan and Yellow 4, 5 and 6, where
|
||||
/// [`LAYER_COLORS`] has Yellow, Magenta and Cyan; every other preset has its own position (#6502,
|
||||
/// from the index and RGB pairs of the `Lb` records in files users sent). A reader takes the index
|
||||
/// and ignores the RGB beside it, so the index decides the colour.
|
||||
pub(crate) fn ai_layer_index(preset: u8) -> u8 {
|
||||
match preset {
|
||||
4 => 6,
|
||||
5 => 4,
|
||||
6 => 5,
|
||||
i => i,
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset (position in [`LAYER_COLORS`]) of the colour index `index` in an `.ai` layer's
|
||||
/// `Lb`: the inverse of [`ai_layer_index`].
|
||||
pub(crate) fn preset_of_ai_layer_index(index: u8) -> u8 {
|
||||
match index {
|
||||
6 => 4,
|
||||
4 => 5,
|
||||
5 => 6,
|
||||
i => i,
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour index and RGB an `.ai` layer's `Lb` writes for `color`: a preset's index
|
||||
/// ([`ai_layer_index`]) with its RGB, or `-1` with a custom colour's RGB.
|
||||
pub(crate) fn layer_color(color: LayerColor) -> (i64, [u8; 3]) {
|
||||
match color {
|
||||
LayerColor::Preset(i) => match LAYER_COLORS.get(usize::from(i)) {
|
||||
Some((_, rgb)) => (i64::from(ai_layer_index(i)), *rgb),
|
||||
None => (-1, [79, 128, 255]),
|
||||
},
|
||||
LayerColor::Custom(rgb) => (-1, rgb),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn unit(v: f32) -> f32 {
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
@@ -19,10 +19,12 @@
|
||||
//! (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the contents (`X=` … `X+`, then
|
||||
//! `(AIDeformArtKey)`) and the kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object). Then the
|
||||
//! distorted art on plain lines, and the plugin's `XP`. While the contents are edited, the group
|
||||
//! holds the contents and the dictionary the mesh. A top object's outline is the edge of its
|
||||
//! one-patch mesh. A warp's mesh is a grid of its shape: a warp of type whose own warp doesn't come
|
||||
//! out as drawn opens as a mesh envelope on that grid where that does. An envelope whose parts don't
|
||||
//! read, or that doesn't come out as drawn, keeps its drawn art.
|
||||
//! holds the contents and the dictionary the mesh, which in some files lies away from the drawn art
|
||||
//! by a move, as if it hadn't followed the envelope: such a mesh or top object whose grid draws its
|
||||
//! contents as large as the drawn art but elsewhere is tried again moved onto that art. A top
|
||||
//! object's outline is the edge of its one-patch mesh. A warp's mesh is a grid of its shape: a warp
|
||||
//! of type whose own warp doesn't come out as drawn opens as a mesh envelope on that grid where that
|
||||
//! does. An envelope whose parts don't read, or that doesn't come out as drawn, keeps its drawn art.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::sync::Arc;
|
||||
@@ -62,6 +64,10 @@ const MAX_GRID: u32 = 50;
|
||||
/// How far, in points over width and height together, a saved size may lie from the contents'
|
||||
/// bounds with their strokes and still count as that box.
|
||||
const SAVED_SIZE_SLACK: f64 = 0.5;
|
||||
/// How far, in points over width and height together, what an envelope draws may differ in size
|
||||
/// from its drawn art and still count as that art moved, and how far it must lie from it to count
|
||||
/// as moved at all ([`moved_onto`]).
|
||||
const MOVED_SLACK: f64 = 0.5;
|
||||
/// The bits of the options word that are read: Distort Appearance, Distort Pattern Fills, Distort
|
||||
/// Linear Gradients, Anti-Alias (set: off) and Preserve Shape Using (set: Clipping Mask).
|
||||
const KNOWN_BITS: i64 = 0b111 | 1 << 16 | 1 << 17;
|
||||
@@ -183,6 +189,40 @@ fn with_strokes(kind: &NodeKind) -> Option<NodeKind> {
|
||||
Some(kind)
|
||||
}
|
||||
|
||||
/// The kind of `envelope`, a mesh or a top object in Edit Contents, with its grid moved onto
|
||||
/// `drawn`, the drawn art the file saves for it, where what it draws is as large as that art (within
|
||||
/// [`MOVED_SLACK`]) but lies elsewhere (further than that): moved by as far as the drawn art's box
|
||||
/// lies from the box of what it draws. While the contents are edited, the grid is kept in the
|
||||
/// envelope's dictionary, and in some files it lies away from the drawn art by a move, the contents
|
||||
/// with the drawn art, as if the grid hadn't followed the envelope when it moved. `None` outside
|
||||
/// Edit Contents, for a warp (it maps from its contents' box, which lies with them), and where
|
||||
/// nothing is drawn. Symbol instances and pattern fills in the contents are measured as they are,
|
||||
/// not drawn out: where that makes the sizes differ, no move is tried.
|
||||
pub(super) fn moved_onto(envelope: &Node, drawn: &Node) -> Option<NodeKind> {
|
||||
let NodeKind::Envelope { kind, editing: true, .. } = &envelope.kind else { return None };
|
||||
if matches!(**kind, EnvelopeKind::Warp { .. }) {
|
||||
return None;
|
||||
}
|
||||
// What it draws, measured as its drawn art is: the pieces in a group with its own appearance.
|
||||
let mut drew = envelope.clone();
|
||||
drew.kind = NodeKind::Group { children: vectorcraft_render::expand_live(envelope).into_iter().map(Arc::new).collect(), clip: false };
|
||||
let (from, to) = (drew.visual_bounds()?, drawn.visual_bounds()?);
|
||||
let by = to.center() - from.center();
|
||||
let resized = (from.width() - to.width()).abs() + (from.height() - to.height()).abs();
|
||||
if !(resized <= MOVED_SLACK && by.x.abs() + by.y.abs() > MOVED_SLACK && by.x.is_finite() && by.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let mut moved = envelope.kind.clone();
|
||||
if let NodeKind::Envelope { kind, .. } = &mut moved {
|
||||
match &mut **kind {
|
||||
EnvelopeKind::Mesh { points, .. } => points.iter_mut().for_each(|p| *p += by),
|
||||
EnvelopeKind::TopObject { path, .. } => path.transform(Affine::translate(by)),
|
||||
EnvelopeKind::Warp { .. } => return None,
|
||||
}
|
||||
}
|
||||
Some(moved)
|
||||
}
|
||||
|
||||
/// A warp: its style, bend, distortions and orientation.
|
||||
fn warp(o: &Obj) -> Option<EnvelopeKind> {
|
||||
let style = whole(o, "DeformStyle")??;
|
||||
@@ -552,7 +592,8 @@ impl WarpedType {
|
||||
/// for it ([`live_on_saved_grid`]), which opens in its place where it does: its type stays
|
||||
/// editable in that shape, and the warp's style and bend are lost. With Distort Appearance, each
|
||||
/// is also checked mapping from its type's glyphs grown by half their strokes' weight
|
||||
/// ([`with_strokes`]). Each
|
||||
/// ([`with_strokes`]). In Edit Contents, a mesh or top object whose grid draws the type
|
||||
/// elsewhere than its drawn art is checked last moved onto that art ([`moved_onto`]). Each
|
||||
/// check uses one of the import's checks and, for an envelope that shows, adds to what the page
|
||||
/// check allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't
|
||||
/// available, the drawn art and the hidden type stay.
|
||||
@@ -634,7 +675,17 @@ impl WarpedType {
|
||||
(plain.visible, plain.opacity) = (true, 1.0);
|
||||
let page = self.page.filter(|_| shown.contains(&drawn));
|
||||
let mut alike = None;
|
||||
for (i, kind) in kinds.into_iter().enumerate() {
|
||||
// In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again
|
||||
// moved onto that art ([`moved_onto`]), after every other way.
|
||||
let (mut tries, mut moved, mut again, mut i) = (kinds.into_iter(), vec![], false, 0);
|
||||
loop {
|
||||
let Some(kind) = tries.next() else {
|
||||
if again || moved.is_empty() {
|
||||
break;
|
||||
}
|
||||
(tries, again) = (std::mem::take(&mut moved).into_iter(), true);
|
||||
continue;
|
||||
};
|
||||
// A second try is only made while more checks are left than there are envelopes of
|
||||
// type and warped text objects still to come (some of which may need none): one
|
||||
// envelope's tries don't use up the checks of the others.
|
||||
@@ -642,6 +693,7 @@ impl WarpedType {
|
||||
return Err(TypeKept::Budget);
|
||||
}
|
||||
self.checks -= 1;
|
||||
i += 1;
|
||||
let mut envelope = art.clone();
|
||||
(envelope.id, envelope.kind) = (id, kind);
|
||||
let shared = Shared { patterns: &doc.patterns, images: &doc.images };
|
||||
@@ -651,6 +703,9 @@ impl WarpedType {
|
||||
alike = Some(envelope);
|
||||
break;
|
||||
}
|
||||
if !again && let Some(kind) = moved_onto(&live_one, &plain) {
|
||||
moved.push(kind);
|
||||
}
|
||||
}
|
||||
let envelope = alike.ok_or(TypeKept::Differs)?;
|
||||
if doc.node(drawn).is_none() {
|
||||
|
||||
@@ -913,7 +913,18 @@ impl<'a> Reader<'a> {
|
||||
let mut plain = drawn.clone();
|
||||
(plain.visible, plain.opacity) = (true, 1.0);
|
||||
let page = self.page_in_doc();
|
||||
if !crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent) {
|
||||
let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent);
|
||||
// In Edit Contents, a grid that draws the contents elsewhere than the drawn art is checked
|
||||
// again moved onto that art.
|
||||
if !alike
|
||||
&& self.envelope_checks > 0
|
||||
&& let Some(kind) = crate::import::ai::envelope::moved_onto(&shown, &plain)
|
||||
{
|
||||
self.envelope_checks -= 1;
|
||||
(envelope.kind, shown.kind) = (kind.clone(), kind);
|
||||
alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent);
|
||||
}
|
||||
if !alike {
|
||||
self.warn(crate::import::ai::envelope::DRAWN);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -471,8 +471,9 @@ impl<'a> Reader<'a> {
|
||||
a.dim = flag(4, false).then_some(dim_pct.round() as u8);
|
||||
let index = n.get(at).copied().unwrap_or(0.0);
|
||||
let rgb = |i: usize| n.get(at + i).map_or(0, |v| v.clamp(0.0, 255.0) as u8);
|
||||
// The file numbers some presets differently from `LAYER_COLORS` (#6502).
|
||||
a.color = Some(if (0.0..vectorcraft_doc::LAYER_COLORS.len() as f64).contains(&index) && index.fract() == 0.0 {
|
||||
LayerColor::Preset(index as u8)
|
||||
LayerColor::Preset(crate::ai_ops::preset_of_ai_layer_index(index as u8))
|
||||
} else {
|
||||
LayerColor::Custom([rgb(1), rgb(2), rgb(3)])
|
||||
});
|
||||
|
||||
@@ -7880,6 +7880,63 @@ fn an_envelope_whose_contents_are_edited_opens_live_in_edit_contents() {
|
||||
assert_eq!(fill(&content[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
}
|
||||
|
||||
/// While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files it
|
||||
/// lies away from the drawn art by a move, the contents with the drawn art. Where the mesh draws the
|
||||
/// contents as large as the drawn art but elsewhere, the envelope opens live with its mesh moved
|
||||
/// onto that art; where it draws them at another size, it keeps its drawn art.
|
||||
#[test]
|
||||
fn an_envelope_in_edit_contents_whose_mesh_stayed_behind_opens_live_on_its_drawn_art() {
|
||||
use kurbo::Shape as _;
|
||||
use vectorcraft_doc::live::EnvelopeKind;
|
||||
// The top object of `an_envelope_whose_contents_are_edited_opens_live_in_edit_contents`.
|
||||
let at = |(i, j): (usize, usize)| (40.0 + i as f64 * 120.0, 20.0 + j as f64 * 60.0);
|
||||
let handle = |p: (usize, usize), q: (usize, usize)| match (p, q) {
|
||||
((0, 1), (1, 1)) => (70.0, 95.0),
|
||||
((1, 1), (0, 1)) => (130.0, 95.0),
|
||||
_ => {
|
||||
let ((x, y), (u, v)) = (at(p), at(q));
|
||||
(x + (u - x) / 3.0, y + (v - y) / 3.0)
|
||||
}
|
||||
};
|
||||
let mesh = mesh_text(1, 1, &at, &handle, None);
|
||||
let mut bp = kurbo::BezPath::new();
|
||||
bp.move_to((40.0, 20.0));
|
||||
bp.curve_to((70.0, 5.0), (130.0, 5.0), (160.0, 20.0));
|
||||
bp.curve_to((160.0, 40.0), (160.0, 60.0), (160.0, 80.0));
|
||||
bp.curve_to((120.0, 80.0), (80.0, 80.0), (40.0, 80.0));
|
||||
bp.curve_to((40.0, 60.0), (40.0, 40.0), (40.0, 20.0));
|
||||
bp.close_path();
|
||||
let shaped = |a: Affine| EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&(a * bp.clone())), corners: None };
|
||||
let keys = ENVELOPE_KEYS.replace("0 /Bool (AIDeformEditModeKey)", "1 /Bool (AIDeformEditModeKey)");
|
||||
// The contents and the drawn art lie 30 points right and 15 down of where the mesh in the
|
||||
// dictionary draws them.
|
||||
let moved = Affine::translate((30.0, 15.0));
|
||||
let contents = Rect::new(70.0, 35.0, 190.0, 95.0);
|
||||
let read_with = |drawn: &EnvelopeKind| {
|
||||
let block = format!("0 g\n{mesh}");
|
||||
let red = format!("{RED}{}f\n", rect_path(contents.x0, 100.0 - contents.y1, contents.x1, 100.0 - contents.y0));
|
||||
read_ok(&layer(&envelope_parts(&red, &keys, &block, 3, &drawn_box(drawn, contents, contents))))
|
||||
};
|
||||
let r = read_with(&shaped(moved));
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
let (content, kind, _, editing, _) = live_envelope(&a[0]);
|
||||
assert!(editing);
|
||||
let EnvelopeKind::TopObject { path, .. } = kind else { panic!("{kind:?}") };
|
||||
// Moved as far as the drawn art's box lies from the box of what the mesh draws.
|
||||
let (got, want) = (path.to_bezpath().bounding_box(), (moved * bp.clone()).bounding_box());
|
||||
assert!((got.origin() - want.origin()).hypot() < 0.01 && (got.size() - want.size()).to_vec2().hypot() < 1e-6, "{got:?} {want:?}");
|
||||
assert_eq!(content.len(), 1, "{content:#?}");
|
||||
assert_eq!(content[0].geometric_bounds(), Some(contents));
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
// Drawn art moved and a tenth larger isn't the mesh's art moved: it stays.
|
||||
let r = read_with(&shaped(moved * Affine::scale_about(1.1, (100.0, 50.0))));
|
||||
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]);
|
||||
}
|
||||
|
||||
/// An envelope that doesn't read (a warp style number past the list, a mesh envelope whose shape
|
||||
/// isn't a mesh, one whose plugin never closes it) keeps its drawn art, with one note; the art
|
||||
/// round it is read as ever.
|
||||
@@ -8465,20 +8522,44 @@ fn layer_with(ops: &str) -> Node {
|
||||
/// the colour index and the last one change nothing.
|
||||
#[test]
|
||||
fn the_template_flag_of_a_layer() {
|
||||
// Index 4 is the file's Magenta (#6502).
|
||||
let l = layer_with("1 1 0 0 1 0 0 4 255 79 255 1 50 0");
|
||||
let NodeKind::Layer { template, printable, dim_images, color, .. } = l.kind else { panic!() };
|
||||
assert!(template && !printable && l.locked);
|
||||
assert_eq!((dim_images, color), (Some(50), LayerColor::Preset(4)));
|
||||
assert_eq!((dim_images, color), (Some(50), LayerColor::Preset(5)));
|
||||
// Index 5 is the file's Cyan (#6502).
|
||||
for ops in ["1 1 1 1 1 0 1 5 1 2 3 1 30 0", "1 1 1 1 1 0 0 5 1 2 3 1 30 1", "1 1 1 1 1 0 1 5 1 2 3 1 30"] {
|
||||
let l = layer_with(ops);
|
||||
let NodeKind::Layer { template, printable, dim_images, color, .. } = l.kind else { panic!() };
|
||||
assert!(template && printable && !l.locked, "{ops}");
|
||||
assert_eq!((dim_images, color), (Some(30), LayerColor::Preset(5)), "{ops}");
|
||||
assert_eq!((dim_images, color), (Some(30), LayerColor::Preset(6)), "{ops}");
|
||||
}
|
||||
let l = layer_with("1 1 1 1 0 0 1 0 79 128 255 0 50 0");
|
||||
assert!(matches!(l.kind, NodeKind::Layer { template: false, .. }));
|
||||
}
|
||||
|
||||
/// #6502: an `.ai` file numbers Magenta, Cyan and Yellow 4, 5 and 6 (the index and RGB pairs of
|
||||
/// the `Lb` records in files users sent), so they open as those presets; the index decides, not
|
||||
/// the RGB beside it, and the other presets keep their position.
|
||||
#[test]
|
||||
fn layer_colour_indexes_follow_the_file_format() {
|
||||
let color = |ops: &str| match layer_with(ops).kind {
|
||||
NodeKind::Layer { color, .. } => color,
|
||||
_ => panic!(),
|
||||
};
|
||||
let preset = |name: &str| {
|
||||
let i = vectorcraft_doc::LAYER_COLORS.iter().position(|(n, _)| *n == name).unwrap();
|
||||
LayerColor::Preset(u8::try_from(i).unwrap())
|
||||
};
|
||||
for (index, rgb, name) in
|
||||
[(3, "79 79 255", "Blue"), (4, "255 79 255", "Magenta"), (5, "79 255 255", "Cyan"), (6, "255 255 79", "Yellow"), (7, "128 128 128", "Gray")]
|
||||
{
|
||||
assert_eq!(color(&format!("1 1 1 1 0 0 0 {index} {rgb} 0 50 0")), preset(name), "index {index}");
|
||||
}
|
||||
// The RGB beside an index doesn't change the preset.
|
||||
assert_eq!(color("1 1 1 1 0 0 0 4 255 255 79 0 50 0"), preset("Magenta"));
|
||||
}
|
||||
|
||||
/// The colour index is one place earlier in eleven and twelve operands, as in ten, and the twelfth
|
||||
/// is the dimming percentage; with nine it is one place earlier still.
|
||||
#[test]
|
||||
|
||||
@@ -5846,6 +5846,67 @@ fn a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art() {
|
||||
assert_eq!(super::tests::program_warnings(&r.warnings), [crate::import::ai::ENVELOPE_TYPE_DRAWN], "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// [`type_envelope_on`] while its contents are edited: the text object in the group before its
|
||||
/// dictionary, and `shape` in its contents' block, where the editing data then saves the mesh.
|
||||
fn type_envelope_editing(keys: &str, shape: &str, drawn: &str) -> String {
|
||||
let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() };
|
||||
format!(
|
||||
"{}{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_1 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n",
|
||||
hidden(&format!("u\n{}U\n", text_object(0))),
|
||||
hidden(&format!("/ArtDictionary :\n{}", keys.replace("0 /Bool (AIDeformEditModeKey)", "1 /Bool (AIDeformEditModeKey)"))),
|
||||
hidden(&format!("0 g\n{shape}")),
|
||||
)
|
||||
}
|
||||
|
||||
/// While the contents of an envelope of type are edited, its grid is kept in its dictionary, and in
|
||||
/// some files it lies away from the drawn art by a move, the type with the drawn art. A warp of type
|
||||
/// whose saved grid draws the type as large as its drawn art but elsewhere opens live as a mesh
|
||||
/// envelope on that grid moved onto the drawn art (#3179).
|
||||
#[test]
|
||||
fn a_warp_of_type_in_edit_contents_whose_grid_stayed_behind_opens_on_its_drawn_art() {
|
||||
use vectorcraft_doc::live::EnvelopeKind;
|
||||
let Some(family) = installed_family() else { return };
|
||||
let doc = type_envelope_text(&family, None);
|
||||
let mut text = made_envelope_type(&doc);
|
||||
text.visible = true;
|
||||
// The drawn art is the grid's moved 10 points left and 25 down.
|
||||
let by = kurbo::Vec2::new(-10.0, 25.0);
|
||||
let EnvelopeKind::Mesh { rows, cols, points, handles } = rising_kind() else { panic!("a mesh") };
|
||||
let want: Vec<kurbo::Point> = points.iter().map(|p| *p + by).collect();
|
||||
let kind = EnvelopeKind::Mesh { rows, cols, points: want.clone(), handles };
|
||||
let options = vectorcraft_doc::live::EnvelopeOptions::NEW;
|
||||
let shaped = Node::new(
|
||||
vectorcraft_doc::NodeId(1_000_000),
|
||||
NodeKind::Envelope {
|
||||
content: vec![std::sync::Arc::new(text)],
|
||||
kind: Box::new(kind),
|
||||
fidelity: 50.0,
|
||||
editing: false,
|
||||
options,
|
||||
frame: Box::default(),
|
||||
},
|
||||
);
|
||||
let (drawn, page) = drawn_envelope(&shaped);
|
||||
let art = native_with_text(
|
||||
&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_editing(&arc_keys(0.3), &rising_grid(), &drawn))),
|
||||
&doc,
|
||||
);
|
||||
let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap();
|
||||
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
|
||||
let (envelopes, loose) = envelopes_and_type(&r.document);
|
||||
assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings);
|
||||
assert!(loose.is_empty(), "{loose:?}");
|
||||
assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings);
|
||||
let mut live = None;
|
||||
r.document.walk(|n| {
|
||||
if let NodeKind::Envelope { kind, editing, .. } = &n.kind {
|
||||
live = Some(((**kind).clone(), *editing));
|
||||
}
|
||||
});
|
||||
let Some((EnvelopeKind::Mesh { points, .. }, true)) = live else { panic!("not a mesh envelope in Edit Contents: {live:?}") };
|
||||
assert!(points.iter().zip(&want).all(|(p, q)| (*p - *q).hypot() < 0.05), "{points:?}");
|
||||
}
|
||||
|
||||
/// A warp of type tried again on its saved grid leaves a check for each envelope of type still to
|
||||
/// come: with one check too few for both, the next envelope, whose first try opens it, gets it.
|
||||
#[test]
|
||||
|
||||
@@ -65,8 +65,8 @@ use std::sync::Arc;
|
||||
use vectorcraft_color::cms::Cms;
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{
|
||||
AppearanceItem, AreaOptions, CharPosition, CharStyle, CompositeFont, Document, FillLayer, ImageBlob, Justify, LAYER_COLORS, LayerColor, Node,
|
||||
NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, StrokeLayer, TextKind, TextObject,
|
||||
AppearanceItem, AreaOptions, CharPosition, CharStyle, CompositeFont, Document, FillLayer, ImageBlob, Justify, Node, NodeKind, ParaDirection,
|
||||
ParaStyle, PathAlign, PathEffect, StrokeLayer, TextKind, TextObject,
|
||||
};
|
||||
use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Rect, Shape, SubPath, Vec2};
|
||||
|
||||
@@ -940,6 +940,35 @@ fn names_outside_windows_1252_are_replaced_and_kept_apart() {
|
||||
assert_eq!(inks(&read), want);
|
||||
}
|
||||
|
||||
/// #6502: the legacy writer gives Yellow, Magenta and Cyan (presets 4, 5 and 6) the file's
|
||||
/// indexes 6, 4 and 5, and they open as the same presets.
|
||||
#[test]
|
||||
fn layer_presets_are_written_with_the_files_colour_index() {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.layers.clear();
|
||||
for i in 3..8u8 {
|
||||
let id = doc.alloc_id();
|
||||
doc.layers.push(Arc::new(Node::layer(id, &format!("P{i}"), vectorcraft_doc::LayerColor::Preset(i))));
|
||||
}
|
||||
let out = write(&doc);
|
||||
let text = String::from_utf8_lossy(&out.bytes).replace("\r\n", "\n");
|
||||
for (i, index) in [(3, 3), (4, 6), (5, 4), (6, 5), (7, 7)] {
|
||||
let [r, g, b] = vectorcraft_doc::LAYER_COLORS[i].1;
|
||||
let want = format!(" 0 {index} {r} {g} {b} Lb\n(P{i}) Ln\n");
|
||||
assert!(text.contains(&want), "missing {want:?} in\n{text}");
|
||||
}
|
||||
let read = crate::import(&out.bytes).unwrap().document;
|
||||
let colors: Vec<_> = read
|
||||
.layers
|
||||
.iter()
|
||||
.filter_map(|l| match l.kind {
|
||||
NodeKind::Layer { color, .. } => Some(color),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(colors, (3..8u8).map(vectorcraft_doc::LayerColor::Preset).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn losses_are_warned() {
|
||||
let mut doc = sample();
|
||||
|
||||
@@ -5,9 +5,9 @@ use super::encoding::{
|
||||
use super::{
|
||||
Affine, AppearanceItem, Arc, BezPath, BlendMode, CharStyle, Cms, Color, Document, ELLIPTICAL, FREEFORM, FillLayer, FillRule, Gradient,
|
||||
GradientKind, GradientPaint, HEX_LINE, HIDDEN, HIDDEN_LAYER, HIDDEN_SHOWN, HiddenObjects, IMAGE_ALPHA, ImageBlob, Justify, LARGE_IMAGE,
|
||||
LAYER_COLORS, LAYER_NAME, LIVE, LayerColor, LegacyAiOptions, MAX_IMAGE_PIXELS, MAX_NEST, NAMES, Node, NodeKind, PATTERNS, Paint, ParaDirection,
|
||||
ParaStyle, PathData, ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE,
|
||||
TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke,
|
||||
LAYER_NAME, LIVE, LegacyAiOptions, MAX_IMAGE_PIXELS, MAX_NEST, NAMES, Node, NodeKind, PATTERNS, Paint, ParaDirection, ParaStyle, PathData,
|
||||
ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind,
|
||||
TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke,
|
||||
};
|
||||
|
||||
pub(super) struct Writer<'a> {
|
||||
@@ -135,14 +135,7 @@ impl<'a> Writer<'a> {
|
||||
/// A top-level layer. False when it isn't a layer.
|
||||
pub(super) fn layer(&mut self, n: &Node) -> bool {
|
||||
let NodeKind::Layer { color, template, printable, children, clip, preview, dim_images } = &n.kind else { return false };
|
||||
let [r, g, b] = match color {
|
||||
LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(*i)).map_or([79, 128, 255], |c| c.1),
|
||||
LayerColor::Custom(rgb) => *rgb,
|
||||
};
|
||||
let index = match color {
|
||||
LayerColor::Preset(i) if usize::from(*i) < LAYER_COLORS.len() => i64::from(*i),
|
||||
_ => -1,
|
||||
};
|
||||
let (index, [r, g, b]) = ai_ops::layer_color(*color);
|
||||
let flag = |b: bool| u8::from(b);
|
||||
let name = self.layer_name(n.name.as_deref().unwrap_or("Layer"));
|
||||
// A template layer doesn't print and shows dimmed.
|
||||
@@ -173,14 +166,7 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
let art = std::mem::take(&mut self.hidden_art);
|
||||
let NodeKind::Layer { color, template, printable, .. } = &n.kind else { return false };
|
||||
let [r, g, b] = match color {
|
||||
LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(*i)).map_or([79, 128, 255], |c| c.1),
|
||||
LayerColor::Custom(rgb) => *rgb,
|
||||
};
|
||||
let index = match color {
|
||||
LayerColor::Preset(i) if usize::from(*i) < LAYER_COLORS.len() => i64::from(*i),
|
||||
_ => -1,
|
||||
};
|
||||
let (index, [r, g, b]) = ai_ops::layer_color(*color);
|
||||
let name = format!("{} (hidden)", n.name.as_deref().unwrap_or("Layer"));
|
||||
let name = self.layer_name(&name);
|
||||
let _ = writeln!(
|
||||
|
||||
+102
-9
@@ -175,6 +175,63 @@ pub enum Expr {
|
||||
/// A parenthesized expression, kept so a rule about the bare form (a label, a directive) can
|
||||
/// tell them apart.
|
||||
Paren(ExprId),
|
||||
/// An XML literal (`<a b="c">d</a>`), or with `list` an XMLList literal (`<>…</>`).
|
||||
XmlLiteral {
|
||||
parts: Vec<XmlPart>,
|
||||
list: bool,
|
||||
},
|
||||
/// An E4X name (`@a`, `*`, `ns::a`), the key of an [`Expr::Index`] or the operand of
|
||||
/// [`Expr::XmlScopeName`] and [`Expr::XmlDescendants`].
|
||||
XmlName {
|
||||
attribute: bool,
|
||||
qualifier: Option<XmlQualifier>,
|
||||
name: XmlNamePart,
|
||||
},
|
||||
/// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope.
|
||||
XmlScopeName(ExprId),
|
||||
/// `object..name`.
|
||||
XmlDescendants {
|
||||
object: ExprId,
|
||||
name: ExprId,
|
||||
},
|
||||
/// `object.(predicate)`.
|
||||
XmlFilter {
|
||||
object: ExprId,
|
||||
predicate: ExprId,
|
||||
},
|
||||
}
|
||||
|
||||
/// A piece of an XML literal, in source order.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum XmlPart {
|
||||
/// Markup kept as written.
|
||||
Text(Vec<u16>),
|
||||
/// `{expression}` in element content: XML values keep their markup, other values are escaped.
|
||||
Content(ExprId),
|
||||
/// `{expression}` as an attribute's value.
|
||||
Attribute(ExprId),
|
||||
/// `{expression}` as an element or attribute name, its string checked as an XML name.
|
||||
Name(ExprId),
|
||||
/// `{expression}` as a run of attributes, its string checked as `name="value"` attributes.
|
||||
Attributes(ExprId),
|
||||
}
|
||||
|
||||
/// What stands before `::` in a qualified name.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum XmlQualifier {
|
||||
/// `*::name`: any namespace.
|
||||
Any,
|
||||
Expr(ExprId),
|
||||
}
|
||||
|
||||
/// The name in an E4X name.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum XmlNamePart {
|
||||
Ident(String),
|
||||
/// `*`.
|
||||
Star,
|
||||
/// `[expression]`.
|
||||
Computed(ExprId),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -218,19 +275,55 @@ pub enum Stmt {
|
||||
Expr(ExprId),
|
||||
Block(Vec<StmtId>),
|
||||
Empty,
|
||||
If { test: ExprId, consequent: StmtId, alternate: Option<StmtId> },
|
||||
DoWhile { body: StmtId, test: ExprId },
|
||||
While { test: ExprId, body: StmtId },
|
||||
For { init: Option<ForInit>, test: Option<ExprId>, update: Option<ExprId>, body: StmtId },
|
||||
ForIn { target: ForInTarget, object: ExprId, body: StmtId },
|
||||
If {
|
||||
test: ExprId,
|
||||
consequent: StmtId,
|
||||
alternate: Option<StmtId>,
|
||||
},
|
||||
DoWhile {
|
||||
body: StmtId,
|
||||
test: ExprId,
|
||||
},
|
||||
While {
|
||||
test: ExprId,
|
||||
body: StmtId,
|
||||
},
|
||||
For {
|
||||
init: Option<ForInit>,
|
||||
test: Option<ExprId>,
|
||||
update: Option<ExprId>,
|
||||
body: StmtId,
|
||||
},
|
||||
/// `for (… in …)`, or with `each` the E4X `for each (… in …)`, which assigns the values.
|
||||
ForIn {
|
||||
target: ForInTarget,
|
||||
object: ExprId,
|
||||
body: StmtId,
|
||||
each: bool,
|
||||
},
|
||||
/// `default xml namespace = expression;`.
|
||||
DefaultXmlNamespace(ExprId),
|
||||
Continue(Option<Name>),
|
||||
Break(Option<Name>),
|
||||
Return(Option<ExprId>),
|
||||
With { object: ExprId, body: StmtId },
|
||||
Switch { discriminant: ExprId, cases: Vec<SwitchCase> },
|
||||
Labeled { label: Name, body: StmtId },
|
||||
With {
|
||||
object: ExprId,
|
||||
body: StmtId,
|
||||
},
|
||||
Switch {
|
||||
discriminant: ExprId,
|
||||
cases: Vec<SwitchCase>,
|
||||
},
|
||||
Labeled {
|
||||
label: Name,
|
||||
body: StmtId,
|
||||
},
|
||||
Throw(ExprId),
|
||||
Try { block: Vec<StmtId>, handler: Option<CatchClause>, finalizer: Option<Vec<StmtId>> },
|
||||
Try {
|
||||
block: Vec<StmtId>,
|
||||
handler: Option<CatchClause>,
|
||||
finalizer: Option<Vec<StmtId>>,
|
||||
},
|
||||
Debugger,
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
//! run past [`crate::Limits`].
|
||||
|
||||
mod array;
|
||||
pub(crate) mod extensions;
|
||||
mod global;
|
||||
mod json;
|
||||
mod math;
|
||||
@@ -131,7 +132,11 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
|
||||
crate::string_builtins::install(interp)?;
|
||||
crate::number_builtins::install(interp)?;
|
||||
crate::regexp_builtins::install(interp)?;
|
||||
crate::date_builtins::install(interp)
|
||||
crate::date_builtins::install(interp)?;
|
||||
if interp.options.e4x {
|
||||
crate::xml_builtins::install(interp)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- helpers for the built-ins ----
|
||||
@@ -218,7 +223,7 @@ const UNITS_PER_FUEL: usize = 16;
|
||||
/// against the longest string the heap limit allows, and has its bytes reserved before it is
|
||||
/// added. The buffer's bytes count toward the heap until `finish` or until the native call that
|
||||
/// made the builder returns. Everything the caller still needs must be reachable from the roots.
|
||||
struct Builder {
|
||||
pub(crate) struct Builder {
|
||||
units: Vec<u16>,
|
||||
/// Code units already reserved and charged to the heap.
|
||||
charged: usize,
|
||||
@@ -227,7 +232,7 @@ struct Builder {
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
fn new() -> Self {
|
||||
pub(crate) fn new() -> Self {
|
||||
Builder { units: Vec::new(), charged: 0, unpaid: 0 }
|
||||
}
|
||||
|
||||
@@ -259,7 +264,7 @@ impl Builder {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn push_units(&mut self, interp: &mut Interp, units: &[u16]) -> JsResult<()> {
|
||||
pub(crate) fn push_units(&mut self, interp: &mut Interp, units: &[u16]) -> JsResult<()> {
|
||||
self.make_room(interp, units.len())?;
|
||||
self.units.extend_from_slice(units);
|
||||
Ok(())
|
||||
@@ -267,7 +272,7 @@ impl Builder {
|
||||
|
||||
/// Appends `units` `count` times. Nothing is written for an empty `units`, however large
|
||||
/// `count` is.
|
||||
fn push_repeated(&mut self, interp: &mut Interp, units: &[u16], count: u64) -> JsResult<()> {
|
||||
pub(crate) fn push_repeated(&mut self, interp: &mut Interp, units: &[u16], count: u64) -> JsResult<()> {
|
||||
if units.is_empty() || count == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -279,14 +284,14 @@ impl Builder {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn push_str(&mut self, interp: &mut Interp, s: &str) -> JsResult<()> {
|
||||
pub(crate) fn push_str(&mut self, interp: &mut Interp, s: &str) -> JsResult<()> {
|
||||
let units: Vec<u16> = s.encode_utf16().collect();
|
||||
self.push_units(interp, &units)
|
||||
}
|
||||
|
||||
/// The string built, whose bytes were charged as it grew. From here on the heap counts them
|
||||
/// as the string's.
|
||||
fn finish(self, interp: &mut Interp) -> Value {
|
||||
pub(crate) fn finish(self, interp: &mut Interp) -> Value {
|
||||
interp.held_bytes = interp.held_bytes.saturating_sub(2 * self.charged);
|
||||
Value::String(Str::from_units(self.units))
|
||||
}
|
||||
@@ -358,6 +363,13 @@ fn object_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResu
|
||||
|
||||
/// `Object.prototype.toString` (section 15.2.4.2).
|
||||
fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
// With `$.localize` on, a localization object gives its text for the current locale.
|
||||
if interp.localization.enabled()
|
||||
&& let Value::Object(id) = this
|
||||
&& let Some(text) = extensions::localized_text(interp, id)?
|
||||
{
|
||||
return Ok(text);
|
||||
}
|
||||
let class = match &this {
|
||||
Value::Undefined => "Undefined",
|
||||
Value::Null => "Null",
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
//! The script extensions a host adds with [`crate::Realm::add_script_extensions`]: the global
|
||||
//! `localize`, the global `toSource` and `Object.prototype.toSource`, and the getters behind
|
||||
//! [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of
|
||||
//! [`Localization`].
|
||||
//!
|
||||
//! `toSource` writes primitives, arrays and plain objects as the text of a JavaScript expression
|
||||
//! that makes the same value: strings in double quotes, property names quoted, properties in the
|
||||
//! order the object lists them, a hole in an array as an empty element. It never runs a getter or
|
||||
//! a script's own method: a getter, a function, a date, a regular expression, an error, a boxed
|
||||
//! primitive, an array with properties besides its elements, an object whose prototype is not
|
||||
//! `Object.prototype`, a property that is not enumerable or any other object that is not plain
|
||||
//! data throws a `TypeError`, and so does an object that contains itself. A value nested deeper, with more entries or longer text than the
|
||||
//! realm's [`crate::DataLimits`] allow throws a `RangeError`. Every value written takes fuel.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::{Builder, arg, method};
|
||||
use crate::heap::{Class, NativeFn, ObjId, Prop, key};
|
||||
use crate::interp::{ErrorType, Interp, JsResult};
|
||||
use crate::value::{Value, array_index, index_key, number_to_str};
|
||||
use crate::{ScriptItem, bytecode::Code};
|
||||
|
||||
/// The locale `localize` looks a localization object up in, and whether `toString` gives an
|
||||
/// object's localized text (`$.localize`). A host changes it through [`crate::Realm::localization`].
|
||||
#[derive(Debug)]
|
||||
pub struct Localization {
|
||||
locale: RefCell<String>,
|
||||
platform: Cell<Option<&'static str>>,
|
||||
enabled: Cell<bool>,
|
||||
}
|
||||
|
||||
impl Default for Localization {
|
||||
fn default() -> Self {
|
||||
Self { locale: RefCell::new("en".into()), platform: Cell::new(None), enabled: Cell::new(false) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Localization {
|
||||
/// The locale, a language and an optional region joined by `_`, such as `de_DE`.
|
||||
pub fn locale(&self) -> String {
|
||||
self.locale.borrow().clone()
|
||||
}
|
||||
|
||||
pub fn set_locale(&self, locale: &str) {
|
||||
*self.locale.borrow_mut() = locale.to_string();
|
||||
}
|
||||
|
||||
/// The platform suffix the lookup tries first (`Win`, `Mac` or `Unix`), or none.
|
||||
pub fn platform(&self) -> Option<&'static str> {
|
||||
self.platform.get()
|
||||
}
|
||||
|
||||
pub fn set_platform(&self, platform: Option<&'static str>) {
|
||||
self.platform.set(platform);
|
||||
}
|
||||
|
||||
/// Does `Object.prototype.toString` give an object's localized text?
|
||||
pub fn enabled(&self) -> bool {
|
||||
self.enabled.get()
|
||||
}
|
||||
|
||||
pub fn set_enabled(&self, on: bool) {
|
||||
self.enabled.set(on);
|
||||
}
|
||||
|
||||
/// The property names a localization object is looked up by, in order: the locale with the
|
||||
/// platform suffix, the locale, its language with the suffix, its language, and `en`.
|
||||
pub fn keys(&self) -> Vec<String> {
|
||||
let locale = self.locale();
|
||||
let language = locale.split('_').next().unwrap_or_default().to_string();
|
||||
let mut keys = Vec::with_capacity(5);
|
||||
for name in [&locale, &language] {
|
||||
if let Some(p) = self.platform() {
|
||||
keys.push(format!("{name}_{p}"));
|
||||
}
|
||||
keys.push(name.clone());
|
||||
}
|
||||
keys.push("en".into());
|
||||
let mut unique = Vec::with_capacity(keys.len());
|
||||
for k in keys {
|
||||
if !k.is_empty() && !unique.contains(&k) {
|
||||
unique.push(k);
|
||||
}
|
||||
}
|
||||
unique
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
|
||||
let global = interp.global;
|
||||
method(interp, global, "localize", localize, 1)?;
|
||||
method(interp, global, "toSource", to_source, 1)?;
|
||||
let object_proto = interp.intrinsics.object_proto;
|
||||
method(interp, object_proto, "toSource", to_source_method, 0)
|
||||
}
|
||||
|
||||
/// The text of the localization object `id` for the current locale: the string value of the first
|
||||
/// of [`Localization::keys`] that the object has as its own data property. No getter runs.
|
||||
pub(crate) fn localized_text(interp: &mut Interp, id: ObjId) -> JsResult<Option<Value>> {
|
||||
if !matches!(interp.object(id)?.class, Class::Ordinary) {
|
||||
return Ok(None);
|
||||
}
|
||||
for k in interp.localization.keys() {
|
||||
interp.use_fuel()?;
|
||||
if let Some(Prop::Data { value: v @ Value::String(_), .. }) = interp.get_own_property(id, &key(&k))? {
|
||||
return Ok(Some(v));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// `localize(object, ...values)`: the text of a localization object for the current locale, or of
|
||||
/// a string, with `%1` replaced by the first value, `%2` by the second and so on. A number with no
|
||||
/// value stays as it is. An object with none of the locale's names is returned as it is.
|
||||
fn localize(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let mark = interp.temp_roots.len();
|
||||
interp.temp_roots.extend(args.iter().cloned());
|
||||
let r = localize_rooted(interp, args);
|
||||
interp.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
fn localize_rooted(interp: &mut Interp, args: &[Value]) -> JsResult<Value> {
|
||||
let text = match args.first() {
|
||||
Some(Value::String(s)) => s.flat(),
|
||||
Some(first @ Value::Object(id)) => match localized_text(interp, *id)? {
|
||||
Some(Value::String(s)) => s.flat(),
|
||||
_ => return Ok(first.clone()),
|
||||
},
|
||||
_ => return Err(interp.type_error("localize: the first argument must be a localization object or a string")),
|
||||
};
|
||||
let values = args.get(1..).unwrap_or_default();
|
||||
let mut converted: Vec<Option<Rc<[u16]>>> = vec![None; values.len()];
|
||||
let mut out = Builder::new();
|
||||
let (mut start, mut i) = (0, 0);
|
||||
while let Some(&u) = text.get(i) {
|
||||
if u != u16::from(b'%') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let digits = text.get(i + 1..).unwrap_or_default().iter().take(4).take_while(|d| (0x30..=0x39).contains(*d)).count();
|
||||
let n = text.get(i + 1..i + 1 + digits).unwrap_or_default().iter().fold(0usize, |n, d| n * 10 + usize::from(*d - 0x30));
|
||||
let Some(slot) = n.checked_sub(1).filter(|&k| digits > 0 && k < values.len()) else {
|
||||
i += 1 + digits;
|
||||
continue;
|
||||
};
|
||||
out.push_units(interp, text.get(start..i).unwrap_or_default())?;
|
||||
let units = match converted.get(slot).cloned().flatten() {
|
||||
Some(u) => u,
|
||||
None => {
|
||||
let s = interp.to_str(&arg(values, slot))?.flat();
|
||||
if let Some(c) = converted.get_mut(slot) {
|
||||
*c = Some(s.clone());
|
||||
}
|
||||
s
|
||||
}
|
||||
};
|
||||
out.push_units(interp, &units)?;
|
||||
i += 1 + digits;
|
||||
start = i;
|
||||
}
|
||||
out.push_units(interp, text.get(start..).unwrap_or_default())?;
|
||||
Ok(out.finish(interp))
|
||||
}
|
||||
|
||||
/// The global `toSource(value)`.
|
||||
fn to_source(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
write_source(interp, arg(args, 0))
|
||||
}
|
||||
|
||||
/// `Object.prototype.toSource()`: the source of the value it is called on.
|
||||
fn to_source_method(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
write_source(interp, this)
|
||||
}
|
||||
|
||||
fn write_source(interp: &mut Interp, v: Value) -> JsResult<Value> {
|
||||
let mark = interp.temp_roots.len();
|
||||
interp.temp_roots.push(v.clone());
|
||||
let mut w = Source { out: Builder::new(), ancestors: Vec::new(), entries: 0 };
|
||||
let r = w.value(interp, &v);
|
||||
interp.temp_roots.truncate(mark);
|
||||
r?;
|
||||
Ok(w.out.finish(interp))
|
||||
}
|
||||
|
||||
/// A value being written as source: the text so far, the objects it is inside and the entries it
|
||||
/// has written.
|
||||
struct Source {
|
||||
out: Builder,
|
||||
ancestors: Vec<ObjId>,
|
||||
entries: usize,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
fn push(&mut self, interp: &mut Interp, s: &str) -> JsResult<()> {
|
||||
self.out.push_str(interp, s)?;
|
||||
self.check_length(interp)
|
||||
}
|
||||
|
||||
fn check_length(&mut self, interp: &mut Interp) -> JsResult<()> {
|
||||
self.fit(interp, 0)
|
||||
}
|
||||
|
||||
/// Checks that `more` code units can be added without passing the length limit.
|
||||
fn fit(&mut self, interp: &mut Interp, more: usize) -> JsResult<()> {
|
||||
if self.out.units.len().saturating_add(more) > interp.data_limits.bytes {
|
||||
return Err(interp.throw(ErrorType::Range, "toSource: the source is too long"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn count(&mut self, interp: &mut Interp, n: usize) -> JsResult<()> {
|
||||
self.entries = self.entries.saturating_add(n);
|
||||
if self.entries > interp.data_limits.entries {
|
||||
return Err(interp.throw(ErrorType::Range, "toSource: the value has too many entries"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn value(&mut self, interp: &mut Interp, v: &Value) -> JsResult<()> {
|
||||
interp.use_fuel()?;
|
||||
match v {
|
||||
Value::Undefined => self.push(interp, "(void 0)"),
|
||||
Value::Null => self.push(interp, "null"),
|
||||
Value::Bool(b) => self.push(interp, if *b { "true" } else { "false" }),
|
||||
Value::Number(n) if *n == 0.0 && n.is_sign_negative() => self.push(interp, "-0"),
|
||||
Value::Number(n) => {
|
||||
self.out.push_units(interp, &number_to_str(*n).flat())?;
|
||||
self.check_length(interp)
|
||||
}
|
||||
Value::String(s) => self.quoted(interp, &s.flat()),
|
||||
Value::Object(id) => self.object(interp, *id),
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` in double quotes, with the characters a string literal cannot hold escaped. The length
|
||||
/// limit is checked before each addition, so a string that grows as it is escaped throws a
|
||||
/// `RangeError` before the text takes more heap than the limit allows.
|
||||
fn quoted(&mut self, interp: &mut Interp, s: &[u16]) -> JsResult<()> {
|
||||
self.fit(interp, 1)?;
|
||||
self.out.push_str(interp, "\"")?;
|
||||
let mut start = 0;
|
||||
for (i, &c) in s.iter().enumerate() {
|
||||
let escape = match c {
|
||||
0x22 => "\\\"".to_string(),
|
||||
0x5C => "\\\\".to_string(),
|
||||
0x0A => "\\n".to_string(),
|
||||
0x0D => "\\r".to_string(),
|
||||
0x09 => "\\t".to_string(),
|
||||
0x08 => "\\b".to_string(),
|
||||
0x0C => "\\f".to_string(),
|
||||
0..=0x1F | 0x7F | 0x2028 | 0x2029 | 0xD800..=0xDFFF => format!("\\u{c:04X}"),
|
||||
_ => continue,
|
||||
};
|
||||
self.fit(interp, (i - start).saturating_add(escape.len()))?;
|
||||
self.out.push_units(interp, s.get(start..i).unwrap_or_default())?;
|
||||
self.out.push_str(interp, &escape)?;
|
||||
start = i + 1;
|
||||
}
|
||||
self.fit(interp, s.len().saturating_sub(start).saturating_add(1))?;
|
||||
self.out.push_units(interp, s.get(start..).unwrap_or_default())?;
|
||||
self.push(interp, "\"")
|
||||
}
|
||||
|
||||
fn object(&mut self, interp: &mut Interp, id: ObjId) -> JsResult<()> {
|
||||
if self.ancestors.contains(&id) {
|
||||
return Err(interp.type_error("toSource: the value contains itself"));
|
||||
}
|
||||
if self.ancestors.len() >= interp.data_limits.depth {
|
||||
return Err(interp.throw(ErrorType::Range, "toSource: the value is nested too deep"));
|
||||
}
|
||||
let (object_proto, array_proto) = (interp.intrinsics.object_proto, interp.intrinsics.array_proto);
|
||||
let o = interp.object(id)?;
|
||||
// The text makes an array or an object from `Object.prototype` with enumerable properties
|
||||
// only, so an array with other properties, an object with another prototype and a property
|
||||
// that is not enumerable are refused.
|
||||
let enumerable = o.props.iter().all(|(_, p)| p.enumerable());
|
||||
let shape = match &o.class {
|
||||
Class::Array { length, .. }
|
||||
if o.proto == Some(array_proto) && enumerable && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) =>
|
||||
{
|
||||
Some(Err(*length))
|
||||
}
|
||||
Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)),
|
||||
Class::Ordinary if o.proto == Some(object_proto) && enumerable => {
|
||||
Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::<Vec<_>>()))
|
||||
}
|
||||
Class::Ordinary => return Err(interp.type_error(NOT_PLAIN_OBJECT)),
|
||||
_ => None,
|
||||
};
|
||||
let Some(shape) = shape else {
|
||||
let what = format!("toSource: a {} cannot be written as source", interp.object(id)?.class.name());
|
||||
return Err(interp.type_error(&what));
|
||||
};
|
||||
self.ancestors.push(id);
|
||||
let r = match shape {
|
||||
Err(length) => self.array(interp, id, length),
|
||||
Ok(props) => self.plain(interp, props),
|
||||
};
|
||||
self.ancestors.pop();
|
||||
r
|
||||
}
|
||||
|
||||
fn array(&mut self, interp: &mut Interp, id: ObjId, length: u32) -> JsResult<()> {
|
||||
self.count(interp, length as usize)?;
|
||||
self.push(interp, "[")?;
|
||||
let mut hole = false;
|
||||
for i in 0..length {
|
||||
interp.use_fuel()?;
|
||||
if i > 0 {
|
||||
self.push(interp, ", ")?;
|
||||
}
|
||||
let prop = interp.object(id)?.props.get(&index_key(i)).cloned();
|
||||
hole = prop.is_none();
|
||||
match prop {
|
||||
None => {}
|
||||
Some(Prop::Data { value, .. }) => self.value(interp, &value)?,
|
||||
Some(Prop::Accessor { .. }) => return Err(interp.type_error("toSource: a getter cannot be written as source")),
|
||||
}
|
||||
}
|
||||
// A hole at the end needs a comma of its own, or the array would be one shorter.
|
||||
if hole {
|
||||
self.push(interp, ",")?;
|
||||
}
|
||||
self.push(interp, "]")
|
||||
}
|
||||
|
||||
fn plain(&mut self, interp: &mut Interp, props: Vec<(crate::heap::Key, Prop)>) -> JsResult<()> {
|
||||
self.count(interp, props.len())?;
|
||||
self.push(interp, "({")?;
|
||||
for (n, (k, prop)) in props.into_iter().enumerate() {
|
||||
interp.use_fuel()?;
|
||||
if n > 0 {
|
||||
self.push(interp, ", ")?;
|
||||
}
|
||||
let Prop::Data { value, .. } = prop else { return Err(interp.type_error("toSource: a getter cannot be written as source")) };
|
||||
self.quoted(interp, &k)?;
|
||||
self.push(interp, ":")?;
|
||||
self.value(interp, &value)?;
|
||||
}
|
||||
self.push(interp, "})")
|
||||
}
|
||||
}
|
||||
|
||||
const NOT_PLAIN_ARRAY: &str =
|
||||
"toSource: an array with properties besides its elements, a property that is not enumerable or another prototype cannot be written as source";
|
||||
const NOT_PLAIN_OBJECT: &str =
|
||||
"toSource: an object with a property that is not enumerable, or whose prototype is not Object.prototype, cannot be written as source";
|
||||
|
||||
/// The getter behind `item`; [`ScriptItem::Global`] is a value and has none.
|
||||
pub(crate) fn getter(item: ScriptItem) -> Option<(&'static str, NativeFn)> {
|
||||
match item {
|
||||
ScriptItem::Global => None,
|
||||
ScriptItem::LastError => Some(("error", last_error)),
|
||||
ScriptItem::Line => Some(("line", line)),
|
||||
ScriptItem::Stack => Some(("stack", stack)),
|
||||
}
|
||||
}
|
||||
|
||||
fn last_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
Ok(interp.last_error.clone())
|
||||
}
|
||||
|
||||
fn line(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let line = interp.script_frames().last().map_or(0, |(code, pc, _)| code.line_column(pc.saturating_sub(1)).0);
|
||||
Ok(Value::Number(f64::from(line)))
|
||||
}
|
||||
|
||||
/// The most frames `$.stack` lists, and the most characters of a function's name it shows.
|
||||
const STACK_FRAMES: usize = 64;
|
||||
const STACK_NAME_UNITS: usize = 64;
|
||||
|
||||
/// The script's frames, outermost first, one a line: the function's name and the line it is at.
|
||||
fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let frames: Vec<(Rc<Code>, usize, bool)> = interp.script_frames().map(|(c, pc, f)| (c.clone(), pc, f)).collect();
|
||||
let skip = frames.len().saturating_sub(STACK_FRAMES);
|
||||
let mut text = String::new();
|
||||
if skip > 0 {
|
||||
text.push_str("…\n");
|
||||
}
|
||||
for (code, pc, function) in frames.iter().skip(skip) {
|
||||
interp.use_fuel()?;
|
||||
let name = if *function { function_name(code) } else { "[global]".to_string() };
|
||||
let line = code.line_column(pc.saturating_sub(1)).0;
|
||||
text.push_str(&format!("{name}:{line}\n"));
|
||||
}
|
||||
let mut out = Builder::new();
|
||||
out.push_str(interp, &text)?;
|
||||
Ok(out.finish(interp))
|
||||
}
|
||||
|
||||
/// The name `code` has: its own as a function expression's, or its declaration's, cut to
|
||||
/// [`STACK_NAME_UNITS`]; `[anonymous]` without one.
|
||||
fn function_name(code: &Code) -> String {
|
||||
match code.self_name.as_ref().or(code.decl_name.as_ref()) {
|
||||
Some(name) => String::from_utf16_lossy(name.get(..STACK_NAME_UNITS).unwrap_or(&**name)),
|
||||
None => "[anonymous]".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -145,6 +145,35 @@ pub(crate) enum Op {
|
||||
/// Pushes the completion value, which a `finally` block in script and eval code keeps and
|
||||
/// sets back with `SetCompletion` when it ends normally.
|
||||
GetCompletion,
|
||||
/// `[qualifier] name` → an E4X name object.
|
||||
XmlMakeName {
|
||||
attribute: bool,
|
||||
qualified: bool,
|
||||
},
|
||||
/// `object name` → the descendants that match.
|
||||
XmlDescendants,
|
||||
/// `value` → the string an embedded expression puts in a literal (0 content, 1 attribute
|
||||
/// value, 2 name, 3 run of attributes).
|
||||
XmlEscape(u8),
|
||||
/// The `parts` strings → the XML or XMLList they spell.
|
||||
XmlLiteral {
|
||||
parts: u32,
|
||||
list: bool,
|
||||
},
|
||||
/// `name` → the value of the name on the nearest XML value in scope.
|
||||
XmlScopeGet,
|
||||
/// `object` → the filter's state.
|
||||
XmlFilterStart,
|
||||
/// `state` → `state item`, or jumps with `state` when the items are used up.
|
||||
XmlFilterNext(u32),
|
||||
/// `state value` → `state`, the current item kept when the value is truthy.
|
||||
XmlFilterTest,
|
||||
/// `state` → the XMLList of the items kept.
|
||||
XmlFilterEnd,
|
||||
/// `iterator name` → `iterator value`: the value under the name a `for each` got.
|
||||
ForEachValue,
|
||||
/// `value` → nothing: sets the default XML namespace of the running code.
|
||||
SetDefaultNamespace,
|
||||
}
|
||||
|
||||
/// What code is: a function body, a script, or eval code.
|
||||
@@ -195,6 +224,8 @@ pub(crate) struct Code {
|
||||
pub(crate) strict: bool,
|
||||
/// A function expression's own name, bound inside it.
|
||||
pub(crate) self_name: Option<Key>,
|
||||
/// A function declaration's name, which `$.stack` shows.
|
||||
pub(crate) decl_name: Option<Key>,
|
||||
pub(crate) params: Vec<Key>,
|
||||
pub(crate) vars: Vec<Key>,
|
||||
/// Function declarations to instantiate on entry: their names and indices in `functions`.
|
||||
@@ -272,7 +303,13 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
|
||||
let table = finally_tables.get(t as usize).ok_or_else(|| format!("finally table {t} out of range"))?;
|
||||
Effect { pops: 2, next: Some(0), jumps: table.iter().map(|&target| (target, 1)).collect() }
|
||||
}
|
||||
Op::ForInNext(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] },
|
||||
Op::ForInNext(t) | Op::XmlFilterNext(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] },
|
||||
Op::XmlMakeName { qualified, .. } => e(1 + u32::from(qualified), 1),
|
||||
Op::XmlDescendants | Op::XmlFilterTest => e(2, 1),
|
||||
Op::XmlEscape(_) | Op::XmlScopeGet | Op::XmlFilterStart | Op::XmlFilterEnd => e(1, 1),
|
||||
Op::XmlLiteral { parts, .. } => e(parts, 1),
|
||||
Op::ForEachValue => e(2, 2),
|
||||
Op::SetDefaultNamespace => e(1, 0),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+116
-8
@@ -18,7 +18,7 @@ use std::rc::Rc;
|
||||
|
||||
use crate::ast::{
|
||||
AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LogicalOp, PropertyValue, Stmt, StmtId, UnaryOp, UpdateOp,
|
||||
VarDecl,
|
||||
VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
};
|
||||
use crate::bytecode::{Code, CodeKind, Handler, Op, Source, fallthrough_effect, verify};
|
||||
use crate::error::{SyntaxError, TOO_DEEP};
|
||||
@@ -276,7 +276,14 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
work.extend(block.iter().rev());
|
||||
}
|
||||
Stmt::Expr(_) | Stmt::Empty | Stmt::Continue(_) | Stmt::Break(_) | Stmt::Return(_) | Stmt::Throw(_) | Stmt::Debugger => {}
|
||||
Stmt::Expr(_)
|
||||
| Stmt::Empty
|
||||
| Stmt::Continue(_)
|
||||
| Stmt::Break(_)
|
||||
| Stmt::Return(_)
|
||||
| Stmt::Throw(_)
|
||||
| Stmt::Debugger
|
||||
| Stmt::DefaultXmlNamespace(_) => {}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
@@ -348,6 +355,11 @@ impl<'a> FnCompiler<'a> {
|
||||
Ok(())
|
||||
}
|
||||
Stmt::Try { block, handler, finalizer } => self.try_stmt(block, handler.as_ref(), finalizer.as_deref()),
|
||||
Stmt::DefaultXmlNamespace(e) => {
|
||||
self.expr(*e)?;
|
||||
self.emit(Op::SetDefaultNamespace);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -467,14 +479,14 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
self.jump(Op::Jump, head);
|
||||
}
|
||||
Some(Stmt::ForIn { target, object, body }) => return self.for_in(target, *object, *body, labels),
|
||||
Some(Stmt::ForIn { target, object, body, each }) => return self.for_in(target, *object, *body, labels, *each),
|
||||
_ => return internal("not a loop"),
|
||||
}
|
||||
self.bind(brk);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn for_in(&mut self, target: &ForInTarget, object: ExprId, body: StmtId, labels: Vec<String>) -> CResult<()> {
|
||||
fn for_in(&mut self, target: &ForInTarget, object: ExprId, body: StmtId, labels: Vec<String>, each: bool) -> CResult<()> {
|
||||
if let ForInTarget::Var(d) = target {
|
||||
self.var_decls(std::slice::from_ref(d))?;
|
||||
}
|
||||
@@ -485,6 +497,9 @@ impl<'a> FnCompiler<'a> {
|
||||
let brk = self.new_label();
|
||||
self.bind(head);
|
||||
self.jump(Op::ForInNext, brk);
|
||||
if each {
|
||||
self.emit(Op::ForEachValue);
|
||||
}
|
||||
match target {
|
||||
ForInTarget::Var(d) => {
|
||||
let n = self.var_name(&d.name.name);
|
||||
@@ -827,10 +842,83 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
}
|
||||
Expr::Paren(inner) => self.expr(*inner)?,
|
||||
Expr::XmlLiteral { parts, list } => self.xml_literal(parts, *list)?,
|
||||
Expr::XmlName { attribute, qualifier, name } => self.xml_name(*attribute, *qualifier, name)?,
|
||||
Expr::XmlScopeName(name) => {
|
||||
self.expr(*name)?;
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
self.emit(Op::XmlScopeGet);
|
||||
}
|
||||
Expr::XmlDescendants { .. } | Expr::XmlFilter { .. } => self.chain(id)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn xml_literal(&mut self, parts: &[XmlPart], list: bool) -> CResult<()> {
|
||||
for part in parts {
|
||||
match part {
|
||||
XmlPart::Text(units) => {
|
||||
let i = self.string(units);
|
||||
self.emit(Op::String(i));
|
||||
}
|
||||
XmlPart::Content(e) | XmlPart::Attribute(e) | XmlPart::Name(e) | XmlPart::Attributes(e) => {
|
||||
self.expr(*e)?;
|
||||
self.emit(Op::XmlEscape(match part {
|
||||
XmlPart::Content(_) => 0,
|
||||
XmlPart::Attribute(_) => 1,
|
||||
XmlPart::Name(_) => 2,
|
||||
_ => 3,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.emit(Op::XmlLiteral { parts: len_u32(parts.len()), list });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn xml_name(&mut self, attribute: bool, qualifier: Option<XmlQualifier>, name: &XmlNamePart) -> CResult<()> {
|
||||
match qualifier {
|
||||
Some(XmlQualifier::Any) => self.emit(Op::Null),
|
||||
Some(XmlQualifier::Expr(e)) => self.expr(e)?,
|
||||
None => {}
|
||||
}
|
||||
match name {
|
||||
XmlNamePart::Ident(n) => {
|
||||
let i = self.string(&n.encode_utf16().collect::<Vec<u16>>());
|
||||
self.emit(Op::String(i));
|
||||
}
|
||||
XmlNamePart::Star => {
|
||||
let i = self.string(&[u16::from(b'*')]);
|
||||
self.emit(Op::String(i));
|
||||
}
|
||||
XmlNamePart::Computed(e) => self.expr(*e)?,
|
||||
}
|
||||
self.emit(Op::XmlMakeName { attribute, qualified: qualifier.is_some() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `object.(predicate)` with the object already on the stack: each item is tested with itself
|
||||
/// as the innermost scope, in list order.
|
||||
fn xml_filter(&mut self, predicate: ExprId) -> CResult<()> {
|
||||
self.emit(Op::XmlFilterStart);
|
||||
let head = self.new_label();
|
||||
let done = self.new_label();
|
||||
self.bind(head);
|
||||
let depth = self.depth;
|
||||
self.jump(Op::XmlFilterNext, done);
|
||||
self.emit(Op::PushWith);
|
||||
self.env_depth += 1;
|
||||
self.expr(predicate)?;
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
self.emit(Op::XmlFilterTest);
|
||||
self.jump(Op::Jump, head);
|
||||
self.bind(done);
|
||||
self.depth = depth;
|
||||
self.emit(Op::XmlFilterEnd);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn args(&mut self, args: &[ExprId]) -> CResult<()> {
|
||||
for a in args {
|
||||
self.expr(*a)?;
|
||||
@@ -869,7 +957,9 @@ impl<'a> FnCompiler<'a> {
|
||||
let mut cur = id;
|
||||
loop {
|
||||
match self.ast.expr(cur) {
|
||||
Some(Expr::Member { object, .. } | Expr::Index { object, .. }) => {
|
||||
Some(
|
||||
Expr::Member { object, .. } | Expr::Index { object, .. } | Expr::XmlDescendants { object, .. } | Expr::XmlFilter { object, .. },
|
||||
) => {
|
||||
suffixes.push(cur);
|
||||
cur = self.ast.unparenthesized(*object);
|
||||
}
|
||||
@@ -910,6 +1000,15 @@ impl<'a> FnCompiler<'a> {
|
||||
self.at(span.start);
|
||||
self.emit(if next_is_call { Op::GetIndexThis } else { Op::GetIndex });
|
||||
}
|
||||
Some(Expr::XmlDescendants { name, .. }) => {
|
||||
self.expr(*name)?;
|
||||
self.at(span.start);
|
||||
self.emit(Op::XmlDescendants);
|
||||
}
|
||||
Some(Expr::XmlFilter { predicate, .. }) => {
|
||||
self.at(span.start);
|
||||
self.xml_filter(*predicate)?;
|
||||
}
|
||||
Some(Expr::Call { args, .. }) => {
|
||||
let innermost = j + 1 == count;
|
||||
let has_this = if innermost {
|
||||
@@ -1163,9 +1262,15 @@ impl<'a> FnCompiler<'a> {
|
||||
for &(i, label) in &self.patches {
|
||||
let Some(target) = resolve(&self.labels, label) else { return internal("jump to an unplaced label") };
|
||||
match self.ops.get_mut(i) {
|
||||
Some(Op::Jump(t) | Op::JumpIfFalse(t) | Op::JumpIfTrue(t) | Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) | Op::ForInNext(t)) => {
|
||||
*t = target
|
||||
}
|
||||
Some(
|
||||
Op::Jump(t)
|
||||
| Op::JumpIfFalse(t)
|
||||
| Op::JumpIfTrue(t)
|
||||
| Op::JumpIfFalseKeep(t)
|
||||
| Op::JumpIfTrueKeep(t)
|
||||
| Op::ForInNext(t)
|
||||
| Op::XmlFilterNext(t),
|
||||
) => *t = target,
|
||||
_ => return internal("patching an instruction that is not a jump"),
|
||||
}
|
||||
}
|
||||
@@ -1193,6 +1298,7 @@ impl<'a> FnCompiler<'a> {
|
||||
max_stack: 0,
|
||||
strict: self.strict,
|
||||
self_name: meta.self_name,
|
||||
decl_name: meta.decl_name,
|
||||
params: meta.params,
|
||||
vars: hoisted.vars,
|
||||
fun_decls: hoisted.fun_decls,
|
||||
@@ -1209,6 +1315,7 @@ impl<'a> FnCompiler<'a> {
|
||||
#[derive(Default)]
|
||||
struct Meta {
|
||||
self_name: Option<Key>,
|
||||
decl_name: Option<Key>,
|
||||
params: Vec<Key>,
|
||||
span: (u32, u32),
|
||||
}
|
||||
@@ -1231,6 +1338,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
c.emit(Op::Return);
|
||||
let name = f.name.as_ref().map(|n| key_of(&n.name));
|
||||
let meta = Meta {
|
||||
decl_name: if f.kind == FunctionKind::Declaration { name.clone() } else { None },
|
||||
self_name: if bind_name && f.kind == FunctionKind::Expression { name } else { None },
|
||||
params: f.params.iter().map(|p| key_of(&p.name)).collect(),
|
||||
span: (f.span.start, f.span.end),
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! The script extensions: `localize`, `toSource`, host properties with setters and the items that
|
||||
//! read the interpreter's own state.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn realm() -> Realm {
|
||||
let mut r = Realm::new();
|
||||
r.add_script_extensions().unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
fn text(r: &mut Realm, source: &str) -> String {
|
||||
match r.run(source) {
|
||||
Ok(JsValue::String(s)) => s,
|
||||
other => panic!("{source}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn thrown(r: &mut Realm, source: &str) -> String {
|
||||
match r.run(source) {
|
||||
Err(e) if e.kind == RunErrorKind::Thrown => e.message,
|
||||
other => panic!("{source}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localize_looks_up_the_locale_with_its_platform_then_its_language_then_english() {
|
||||
let mut r = realm();
|
||||
let l = r.localization();
|
||||
l.set_locale("de_DE");
|
||||
l.set_platform(Some("Win"));
|
||||
assert_eq!(l.keys(), ["de_DE_Win", "de_DE", "de_Win", "de", "en"]);
|
||||
let all = "({en: 'e', de: 'd', de_Win: 'dw', de_DE: 'dd', de_DE_Win: 'ddw'})";
|
||||
assert_eq!(text(&mut r, &format!("localize({all})")), "ddw");
|
||||
assert_eq!(text(&mut r, "localize({en: 'e', de: 'd', de_Win: 'dw', de_DE: 'dd'})"), "dd");
|
||||
assert_eq!(text(&mut r, "localize({en: 'e', de: 'd', de_Win: 'dw'})"), "dw");
|
||||
assert_eq!(text(&mut r, "localize({en: 'e', de: 'd', DE: 'x'})"), "d", "names are case sensitive");
|
||||
assert_eq!(text(&mut r, "localize({en: 'e', fr: 'f'})"), "e");
|
||||
l.set_platform(None);
|
||||
assert_eq!(text(&mut r, &format!("localize({all})")), "dd");
|
||||
l.set_locale("en");
|
||||
assert_eq!(l.keys(), ["en"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localize_replaces_numbered_values_once_and_leaves_the_rest() {
|
||||
let mut r = realm();
|
||||
assert_eq!(text(&mut r, "localize({en: '%2 before %1, %1 again'}, 'a', 'b')"), "b before a, a again");
|
||||
assert_eq!(text(&mut r, "localize('%1%% %3 %0 %', 'x', '%1')"), "x%% %3 %0 %");
|
||||
assert_eq!(text(&mut r, "localize('%2', 'x', '%1')"), "%1", "a value is not replaced again");
|
||||
assert_eq!(text(&mut r, "localize('%1', {toString: function () { return 'o'; }})"), "o");
|
||||
assert_eq!(text(&mut r, "var n = 0; var v = {toString: function () { n++; return 'v'; }}; localize('%1%1', v) + n"), "vv1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localize_gives_back_an_object_without_the_locale_and_runs_no_getter() {
|
||||
let mut r = realm();
|
||||
r.localization().set_locale("fr_FR");
|
||||
assert_eq!(r.run("var o = {de: 'd'}; localize(o) === o").unwrap(), JsValue::Bool(true));
|
||||
let source = "var hit = false; var o = {get fr() { hit = true; return 'g'; }, en: 'e'}; localize(o) + ',' + hit";
|
||||
assert_eq!(text(&mut r, source), "e,false");
|
||||
assert_eq!(text(&mut r, "localize({fr: 1, en: 'e'})"), "e", "a value that is not a string is passed over");
|
||||
for bad in ["localize()", "localize(1)", "localize(null)"] {
|
||||
assert!(thrown(&mut r, bad).starts_with("TypeError"), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_string_localizes_an_object_only_while_localization_is_on() {
|
||||
let mut r = realm();
|
||||
r.localization().set_locale("ja");
|
||||
let source = "String({en: 'Hello', ja: 'こんにちは'}) + '|' + String({x: 1})";
|
||||
assert_eq!(text(&mut r, source), "[object Object]|[object Object]");
|
||||
r.localization().set_enabled(true);
|
||||
assert_eq!(text(&mut r, source), "こんにちは|[object Object]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_source_writes_plain_data_as_an_expression_that_makes_it_again() {
|
||||
let mut r = realm();
|
||||
let source = r#"toSource({a: [1, "x\n\"", null, true, -0, 1.5e300], "b c": {d: undefined}, e: {}, f: []})"#;
|
||||
let want = r#"({"a":[1, "x\n\"", null, true, -0, 1.5e+300], "b c":({"d":(void 0)}), "e":({}), "f":[]})"#;
|
||||
assert_eq!(text(&mut r, source), want);
|
||||
assert_eq!(text(&mut r, "[1, , 3].toSource() + '|' + [1, ,].toSource() + '|' + [,].toSource()"), "[1, , 3]|[1, ,]|[,]");
|
||||
assert_eq!(
|
||||
text(&mut r, "toSource(NaN) + toSource(-Infinity) + toSource() + toSource('\\u2028\\ud800\\x7f')"),
|
||||
"NaN-Infinity(void 0)\"\\u2028\\uD800\\u007F\""
|
||||
);
|
||||
assert_eq!(text(&mut r, "(5).toSource() + 'a'.toSource() + true.toSource()"), "5\"a\"true");
|
||||
// Parsed back, the text makes the same value: holes, -0 and undefined included.
|
||||
let round = r#"var v = {a: [1, , "q\u0001'\\"], b: {"0": -0, "": undefined, "x y": [[]]}};
|
||||
var w = eval(toSource(v));
|
||||
[JSON.stringify(w) === JSON.stringify(v), w.a.length, 1 in w.a, 1 / w.b[0], "" in w.b].join()"#;
|
||||
assert_eq!(text(&mut r, round), "true,3,false,-Infinity,true");
|
||||
let shared = "var s = {k: 1}; toSource([s, s])";
|
||||
assert_eq!(text(&mut r, shared), r#"[({"k":1}), ({"k":1})]"#, "a value seen twice that is not its own ancestor is written twice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_source_refuses_what_is_not_plain_data() {
|
||||
let mut r = realm();
|
||||
for (source, kind) in [
|
||||
("var o = {}; o.o = o; toSource(o)", "TypeError"),
|
||||
("var a = [1]; a.push([a]); toSource(a)", "TypeError"),
|
||||
("toSource({f: function () {}})", "TypeError"),
|
||||
("toSource({get g() { return 1; }})", "TypeError"),
|
||||
("toSource(new Date(0))", "TypeError"),
|
||||
("toSource([/x/])", "TypeError"),
|
||||
("toSource(new Error('e'))", "TypeError"),
|
||||
("toSource(new String('s'))", "TypeError"),
|
||||
("var a = [1]; a.extra = 2; toSource(a)", "TypeError"),
|
||||
("toSource(Object.create(Array.prototype))", "TypeError"),
|
||||
("var o = {}; Object.defineProperty(o, 'hidden', {value: 1}); toSource(o)", "TypeError"),
|
||||
("var a = [0]; Object.defineProperty(a, '0', {value: 1, enumerable: false}); toSource(a)", "TypeError"),
|
||||
("toSource(Object.create({a: 1}))", "TypeError"),
|
||||
("toSource(Object.create(null))", "TypeError"),
|
||||
("function F() { this.a = 1; } toSource(new F())", "TypeError"),
|
||||
("var d = []; for (var i = 0; i < 70; i++) d = [d]; toSource(d)", "RangeError"),
|
||||
("var a = []; a.length = 2000000; toSource(a)", "RangeError"),
|
||||
] {
|
||||
assert!(thrown(&mut r, source).starts_with(kind), "{source}");
|
||||
}
|
||||
assert!(thrown(&mut r, "toSource({get g() { throw 'ran'; }})").starts_with("TypeError"), "the getter does not run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_source_of_a_string_with_many_escapes_throws_a_range_error_before_the_heap_limit() {
|
||||
let mut r = realm();
|
||||
// A run's heap in the web build. 2^23 control characters, each written as six, pass a quarter
|
||||
// of it, which is all one string may take.
|
||||
r.set_limits(Limits { heap_bytes: 128 << 20, ..Limits::default() });
|
||||
let source = "var s = '\\x01'; for (var i = 0; i < 23; i++) s = s + s;
|
||||
try { toSource(s); 'no error'; } catch (e) { e.name + ': ' + e.message; }";
|
||||
assert_eq!(text(&mut r, source), "RangeError: toSource: the source is too long");
|
||||
assert_eq!(text(&mut r, "toSource('a\\x01a\\x01a\\x01a\\x01').length + ''"), "30", "short strings are written whole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_source_stops_at_the_fuel_limit() {
|
||||
let mut r = realm();
|
||||
r.set_limits(Limits { fuel: 200_000, ..Limits::default() });
|
||||
let e = r.run("var a = []; for (var i = 0; i < 1000; i++) a.push(i); while (true) toSource(a);").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_items_read_the_global_object_the_last_error_the_line_and_the_stack() {
|
||||
let mut r = realm();
|
||||
let items = ["global", "error", "line", "stack"]
|
||||
.into_iter()
|
||||
.zip([ScriptItem::Global, ScriptItem::LastError, ScriptItem::Line, ScriptItem::Stack])
|
||||
.map(|(n, i)| (n.to_string(), HostItem::Script(i)))
|
||||
.collect();
|
||||
r.define_host_object("h", items).unwrap();
|
||||
assert_eq!(r.run("var later = 2; h.global === this && h.global.later === 2").unwrap(), JsValue::Bool(true));
|
||||
let source = "var before = h.error; try { null.x; } catch (e) {} var caught = h.error; try { throw 'text'; } catch (e) {}
|
||||
[before === null, caught instanceof TypeError, h.error === caught].join()";
|
||||
assert_eq!(text(&mut r, source), "true,true,true");
|
||||
let source = "try { try { throw new RangeError('first'); } finally { try { throw new TypeError('second'); } catch (e) {} } } catch (e) {}
|
||||
h.error.message";
|
||||
assert_eq!(text(&mut r, source), "second", "an exception a finally block passes on is not thrown again");
|
||||
let source = "try { [1].map(function () { try { throw new RangeError('first'); } finally { try { throw new TypeError('second'); } catch (e) {} } }); } catch (e) {}
|
||||
h.error.message";
|
||||
assert_eq!(text(&mut r, source), "second", "nor is one that leaves a built-in's callback");
|
||||
let source = "var kept; try { throw new RangeError('first'); } catch (e) { kept = e; } try { throw new TypeError('second'); } catch (e) {}
|
||||
try { throw kept; } catch (e) {} h.error.message";
|
||||
assert_eq!(text(&mut r, source), "first", "throwing a caught error again makes it the last one");
|
||||
assert_eq!(r.run("h.error").unwrap(), JsValue::Null, "each run starts without one");
|
||||
assert_eq!(r.run("\n\n h.line").unwrap(), JsValue::Number(3.0));
|
||||
let source = "function outer() {\n return inner();\n}\nfunction inner() {\n return h.stack;\n}\nvar f = function () { return outer(); };\nf()";
|
||||
assert_eq!(text(&mut r, source), "[global]:8\n[anonymous]:7\nouter:2\ninner:5\n");
|
||||
let source = "function maker() {\n function named() {\n return h.stack;\n }\n return named;\n}\nvar later = maker();\nlater()";
|
||||
assert_eq!(text(&mut r, source), "[global]:8\nnamed:3\n", "a declared function keeps its name after its declaring function returns");
|
||||
let deep = "function d(n) { return n ? d(n - 1) : h.stack; } var s = d(100).split('\\n'); s.length + ',' + s[0]";
|
||||
let lines = text(&mut r, deep);
|
||||
assert_eq!(lines, "66,…", "64 frames, the line that some are left out, and the last line's end");
|
||||
assert!(thrown(&mut r, "'use strict'; h.line = 1").starts_with("TypeError"), "the items cannot be assigned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_property_reads_its_getter_and_gives_assignments_to_its_setter() {
|
||||
let mut r = Realm::new();
|
||||
let seen: Rc<RefCell<Vec<Data>>> = Rc::default();
|
||||
let log = seen.clone();
|
||||
let get: HostFunction = Rc::new(move |_| Ok(Data::String("got".into())));
|
||||
let set: HostFunction = Rc::new(move |args| match args.first() {
|
||||
Some(Data::Number(n)) if *n < 0.0 => Err(HostError::Range("no negatives".into())),
|
||||
Some(d) => {
|
||||
log.borrow_mut().push(d.clone());
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
None => Ok(Data::Undefined),
|
||||
});
|
||||
r.define_host_object("h", vec![("p".into(), HostItem::Property { get, set })]).unwrap();
|
||||
assert_eq!(r.run("h.p = 5; h.p = {a: [1]}; h.p").unwrap(), JsValue::String("got".into()));
|
||||
assert_eq!(*seen.borrow(), [Data::Number(5.0), Data::Object(vec![("a".into(), Data::Array(vec![Data::Number(1.0)]))])]);
|
||||
let e = r.run("try { h.p = -1; } catch (e) { e instanceof RangeError && e.message }").unwrap();
|
||||
assert_eq!(e, JsValue::String("no negatives".into()));
|
||||
}
|
||||
+115
-1
@@ -228,12 +228,84 @@ pub(crate) enum Class {
|
||||
Math,
|
||||
/// The `JSON` object (section 15.12).
|
||||
Json,
|
||||
/// An XML value (ECMA-357 section 9.1).
|
||||
Xml(Box<XmlNode>),
|
||||
/// An XMLList value (ECMA-357 section 9.2).
|
||||
XmlList(Box<XmlListData>),
|
||||
Namespace(Box<XmlNs>),
|
||||
/// A QName; `attribute` marks an attribute name (ECMA-357 sections 13.3 and 9.3), and
|
||||
/// `reference` a name made by E4X syntax, which only an XML value can be accessed with.
|
||||
QName {
|
||||
name: Box<XmlName>,
|
||||
attribute: bool,
|
||||
reference: bool,
|
||||
},
|
||||
/// A `.( )` filter in progress.
|
||||
XmlFilter(Box<XmlFilterState>),
|
||||
}
|
||||
|
||||
/// What an XML value is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum XmlKind {
|
||||
Element,
|
||||
Attribute,
|
||||
Text,
|
||||
Comment,
|
||||
Pi,
|
||||
}
|
||||
|
||||
/// A qualified name. `uri` is `None` for a name that matches any namespace.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct XmlName {
|
||||
pub(crate) uri: Option<Key>,
|
||||
pub(crate) local: Key,
|
||||
pub(crate) prefix: Option<Key>,
|
||||
}
|
||||
|
||||
/// A namespace. `prefix` is `None` when it is undefined.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct XmlNs {
|
||||
pub(crate) prefix: Option<Key>,
|
||||
pub(crate) uri: Key,
|
||||
}
|
||||
|
||||
/// An XML value: a node of a tree, linked by object index.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct XmlNode {
|
||||
pub(crate) kind: XmlKind,
|
||||
pub(crate) name: Option<XmlName>,
|
||||
pub(crate) parent: Option<ObjId>,
|
||||
pub(crate) value: Str,
|
||||
pub(crate) attrs: Vec<ObjId>,
|
||||
pub(crate) children: Vec<ObjId>,
|
||||
pub(crate) ns: Vec<XmlNs>,
|
||||
}
|
||||
|
||||
/// An XMLList value: its items, and the object and name a write to an empty list targets.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct XmlListData {
|
||||
pub(crate) items: Vec<ObjId>,
|
||||
pub(crate) target: Option<ObjId>,
|
||||
pub(crate) target_name: Option<(XmlName, bool)>,
|
||||
}
|
||||
|
||||
/// The state of a `.( )` filter: the items to test, the next one's position and those kept.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct XmlFilterState {
|
||||
pub(crate) input: Vec<ObjId>,
|
||||
pub(crate) pos: usize,
|
||||
pub(crate) kept: Vec<ObjId>,
|
||||
}
|
||||
|
||||
impl Class {
|
||||
/// The `[[Class]]` name `Object.prototype.toString` reports.
|
||||
pub(crate) fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Class::Xml(_) => "XML",
|
||||
Class::XmlList(_) => "XMLList",
|
||||
Class::Namespace(_) => "Namespace",
|
||||
Class::QName { .. } => "QName",
|
||||
Class::XmlFilter(_) => "Object",
|
||||
Class::Math => "Math",
|
||||
Class::Json => "JSON",
|
||||
Class::Ordinary | Class::ForIn(_) => "Object",
|
||||
@@ -311,6 +383,14 @@ pub(crate) const ENV_BYTES: usize = 64;
|
||||
pub(crate) const ROPE_BYTES: usize = 48;
|
||||
/// The estimated bytes of each argument a bound function holds.
|
||||
pub(crate) const BOUND_ARG_BYTES: usize = 24;
|
||||
/// The estimated bytes of an XML node without its names and text.
|
||||
pub(crate) const XML_NODE_BYTES: usize = 160;
|
||||
/// The estimated bytes of an XML list without its items.
|
||||
pub(crate) const XML_LIST_BYTES: usize = 96;
|
||||
/// The estimated bytes of a reference from an XML node or list to another.
|
||||
pub(crate) const XML_REF_BYTES: usize = 8;
|
||||
/// The estimated bytes of a namespace an XML node holds.
|
||||
pub(crate) const XML_NS_BYTES: usize = 48;
|
||||
/// The estimated bytes of a piece of code without its instructions, tables and strings.
|
||||
const CODE_BYTES: usize = 384;
|
||||
|
||||
@@ -529,7 +609,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
|
||||
strings.add(flags);
|
||||
}
|
||||
let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
|
||||
for k in keys.chain(&code.self_name) {
|
||||
for k in keys.chain(&code.self_name).chain(&code.decl_name) {
|
||||
strings.add_key(k);
|
||||
}
|
||||
stack.extend(code.functions.iter().map(|f| &**f));
|
||||
@@ -572,11 +652,45 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
work.extend(state.object.iter().map(|o| o.0));
|
||||
strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
|
||||
}
|
||||
Class::Xml(node) => {
|
||||
work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0));
|
||||
strings.add(&node.value);
|
||||
if let Some(name) = &node.name {
|
||||
add_name(name, strings);
|
||||
}
|
||||
for ns in &node.ns {
|
||||
add_ns(ns, strings);
|
||||
}
|
||||
extra = XML_NODE_BYTES + XML_REF_BYTES * (node.attrs.len() + node.children.len()) + XML_NS_BYTES * node.ns.len();
|
||||
}
|
||||
Class::XmlList(list) => {
|
||||
work.extend(list.target.iter().chain(&list.items).map(|o| o.0));
|
||||
if let Some((name, _)) = &list.target_name {
|
||||
add_name(name, strings);
|
||||
}
|
||||
extra = XML_LIST_BYTES + XML_REF_BYTES * list.items.len();
|
||||
}
|
||||
Class::Namespace(ns) => add_ns(ns, strings),
|
||||
Class::QName { name, .. } => add_name(name, strings),
|
||||
Class::XmlFilter(state) => {
|
||||
work.extend(state.input.iter().chain(&state.kept).map(|o| o.0));
|
||||
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
OBJECT_BYTES + PROP_BYTES * o.props.len() + extra
|
||||
}
|
||||
|
||||
fn add_name(name: &XmlName, strings: &mut StringSizes) {
|
||||
strings.add_key(&name.local);
|
||||
name.uri.iter().chain(&name.prefix).for_each(|k| strings.add_key(k));
|
||||
}
|
||||
|
||||
fn add_ns(ns: &XmlNs, strings: &mut StringSizes) {
|
||||
strings.add_key(&ns.uri);
|
||||
ns.prefix.iter().for_each(|k| strings.add_key(k));
|
||||
}
|
||||
|
||||
fn trace_env(e: &Env, work: &mut Vec<u32>, strings: &mut StringSizes) -> usize {
|
||||
match e {
|
||||
Env::Decl { bindings, outer } => {
|
||||
|
||||
@@ -64,6 +64,11 @@ pub enum HostError {
|
||||
/// it only while [`crate::Realm::wait_flag`] is set; otherwise the run ends with an internal
|
||||
/// error.
|
||||
Wait,
|
||||
/// `error`, with a mark the host chose. When the run ends with the exception `error` throws,
|
||||
/// or with the limit it ends the run with, [`crate::Realm::error_mark`] gives `mark`. A `catch`
|
||||
/// clause that takes the exception drops the mark, so a `throw` of the caught value later
|
||||
/// raises it without one; a `finally` block that ends normally keeps it.
|
||||
Marked { error: Box<HostError>, mark: u32 },
|
||||
}
|
||||
|
||||
/// A function the host gives a script, with its arguments converted.
|
||||
@@ -104,6 +109,12 @@ pub enum HostItem {
|
||||
Converted(Vec<Arg>, HostFunction),
|
||||
/// A property whose value the function gives each time it is read.
|
||||
Getter(HostFunction),
|
||||
/// A property whose value `get` gives each time it is read, and that `set` is given each value
|
||||
/// assigned to it, as its one argument; an error from `set` is thrown to the script.
|
||||
Property {
|
||||
get: HostFunction,
|
||||
set: HostFunction,
|
||||
},
|
||||
/// A frozen object with these members.
|
||||
Object(Vec<(String, HostItem)>),
|
||||
/// A function whose host function gives JavaScript source as a string, which then runs as
|
||||
@@ -118,6 +129,23 @@ pub enum HostItem {
|
||||
end: Rc<dyn Fn()>,
|
||||
strict_writes: Rc<dyn Fn() -> Option<bool>>,
|
||||
},
|
||||
/// A read-only property that reads the interpreter's own state.
|
||||
Script(ScriptItem),
|
||||
}
|
||||
|
||||
/// The interpreter's own state a host object can show.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ScriptItem {
|
||||
/// The global object itself, with every global the script has made.
|
||||
Global,
|
||||
/// The last `Error` object thrown in the current run, caught or not, or `null` before one.
|
||||
LastError,
|
||||
/// The line of the script's code that reads it, counted from 1.
|
||||
Line,
|
||||
/// The running frames of the script's code, outermost first, one a line as `name:line`: the
|
||||
/// global code is `[global]` and a function without a name `[anonymous]`. At most 64 frames
|
||||
/// are listed, the innermost ones, after a line `…` when some are left out.
|
||||
Stack,
|
||||
}
|
||||
|
||||
enum Step {
|
||||
@@ -427,6 +455,11 @@ impl Interp {
|
||||
HostError::Type(message) => self.throw_host(ErrorType::Type, &message),
|
||||
HostError::Range(message) => self.throw_host(ErrorType::Range, &message),
|
||||
HostError::Syntax(message) => self.throw_host(ErrorType::Syntax, &message),
|
||||
HostError::Marked { error, mark } => {
|
||||
let abrupt = self.host_error(*error)?;
|
||||
self.thrown_mark = Some(mark);
|
||||
Ok(abrupt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -474,6 +507,11 @@ impl Interp {
|
||||
let prop = match item {
|
||||
HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE },
|
||||
HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Data)), set: None, flags: ENUMERABLE },
|
||||
HostItem::Property { get, set } => Prop::Accessor {
|
||||
get: Some(self.host_function(get, &full, ArgRead::Data)),
|
||||
set: Some(self.host_function(set, &full, ArgRead::Data)),
|
||||
flags: ENUMERABLE,
|
||||
},
|
||||
HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE },
|
||||
HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Data)), flags: ENUMERABLE },
|
||||
HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Text)), flags: ENUMERABLE },
|
||||
@@ -486,6 +524,13 @@ impl Interp {
|
||||
let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto)));
|
||||
Prop::Data { value: Value::Object(f), flags: ENUMERABLE }
|
||||
}
|
||||
HostItem::Script(item) => match crate::builtins::extensions::getter(item) {
|
||||
None => Prop::Data { value: Value::Object(self.global), flags: ENUMERABLE },
|
||||
Some((name, f)) => {
|
||||
let get = crate::builtins::native(self, name, f, 0, crate::heap::NativeKind::Plain, false)?;
|
||||
Prop::Accessor { get: Some(get), set: None, flags: ENUMERABLE }
|
||||
}
|
||||
},
|
||||
};
|
||||
self.define(o, key(&name), prop)
|
||||
}
|
||||
|
||||
@@ -260,6 +260,59 @@ fn errors_from_the_host_can_be_caught_and_an_abort_cannot() {
|
||||
assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Limit(LimitKind::Host), "stopped by the host"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marked_host_error_keeps_its_mark_only_while_no_catch_takes_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
let f: HostFunction = Rc::new(|a| {
|
||||
let error = match a.first() {
|
||||
Some(Data::String(k)) if k == "abort" => HostError::Abort("stopped".into()),
|
||||
_ => HostError::Syntax("bad file".into()),
|
||||
};
|
||||
Err(HostError::Marked { error: Box::new(error), mark: 7 })
|
||||
});
|
||||
r.define_host_object("host", vec![("f".into(), HostItem::Function(f))]).unwrap();
|
||||
let cases = [
|
||||
("host.f();", Some(7)),
|
||||
("try { host.f(); } finally { var x = 1; }", Some(7)),
|
||||
("try { try { host.f(); } finally { 1; } } finally { 2; }", Some(7)),
|
||||
("function g() { host.f(); }\ng();", Some(7)),
|
||||
("try { host.f(); } finally { try { try { host.f(); } finally { 1; } } catch (e) {} }", Some(7)),
|
||||
("var saved; try { host.f(); } catch (e) { saved = e; }\nthrow saved;", None),
|
||||
("try { host.f(); } catch (e) { throw e; }", None),
|
||||
("try { try { host.f(); } finally { 1; } } catch (e) { throw e; }", None),
|
||||
("var m; try { host.f(); } catch (e) { m = e.message; }\nthrow new SyntaxError(m);", None),
|
||||
("do { try { host.f(); } finally { break; } } while (false);\nthrow new Error('other');", None),
|
||||
("try { host.f('abort'); } catch (e) { 'caught' }", Some(7)),
|
||||
];
|
||||
for (source, mark) in cases {
|
||||
assert!(r.run(source).is_err(), "{source}");
|
||||
assert_eq!(r.error_mark(), mark, "{source}");
|
||||
}
|
||||
assert_eq!(r.run("1").unwrap(), JsValue::Number(1.0));
|
||||
assert_eq!(r.error_mark(), None, "a later run that ends normally has no mark");
|
||||
}
|
||||
|
||||
/// Marked errors that `finally` blocks discard with `return`, `break` or `continue` are collected
|
||||
/// with the rest of the garbage, so a run that discards many of them stays within its heap.
|
||||
#[test]
|
||||
fn marked_errors_a_finally_block_discards_are_collected() {
|
||||
let mut r = Realm::new();
|
||||
r.set_limits(Limits { fuel: 200_000_000, heap_bytes: 1 << 20, ..Limits::default() });
|
||||
let f: HostFunction = Rc::new(|_| Err(HostError::Marked { error: Box::new(HostError::Syntax("bad file".into())), mark: 7 }));
|
||||
r.define_host_object("host", vec![("f".into(), HostItem::Function(f))]).unwrap();
|
||||
let cases = [
|
||||
"function d() { try { host.f(); } finally { return; } }\nfor (var i = 0; i < 20000; i++) d();",
|
||||
"for (var i = 0; i < 20000; i++) { try { host.f(); } finally { continue; } }",
|
||||
"for (var i = 0; i < 20000; i++) { do { try { host.f(); } finally { break; } } while (false); }",
|
||||
];
|
||||
for source in cases {
|
||||
r.run(source).unwrap_or_else(|e| panic!("{source}: {e:?}"));
|
||||
assert_eq!(r.error_mark(), None, "{source}");
|
||||
}
|
||||
assert!(r.run("try { host.f(); } finally { 1; }").is_err());
|
||||
assert_eq!(r.error_mark(), Some(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_says_where_in_the_source_it_was_raised() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
+181
-18
@@ -72,6 +72,12 @@ pub(crate) struct Intrinsics {
|
||||
pub(crate) error_protos: [ObjId; 7],
|
||||
pub(crate) eval: ObjId,
|
||||
pub(crate) throw_type_error: ObjId,
|
||||
/// The `XML` constructor, which holds the XML settings.
|
||||
pub(crate) xml_ctor: ObjId,
|
||||
pub(crate) xml_proto: ObjId,
|
||||
pub(crate) xml_list_proto: ObjId,
|
||||
pub(crate) namespace_proto: ObjId,
|
||||
pub(crate) qname_proto: ObjId,
|
||||
}
|
||||
|
||||
impl Intrinsics {
|
||||
@@ -89,6 +95,11 @@ impl Intrinsics {
|
||||
error_protos: [o; 7],
|
||||
eval: o,
|
||||
throw_type_error: o,
|
||||
xml_ctor: o,
|
||||
xml_proto: o,
|
||||
xml_list_proto: o,
|
||||
namespace_proto: o,
|
||||
qname_proto: o,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +128,11 @@ impl Intrinsics {
|
||||
self.date_proto,
|
||||
self.eval,
|
||||
self.throw_type_error,
|
||||
self.xml_ctor,
|
||||
self.xml_proto,
|
||||
self.xml_list_proto,
|
||||
self.namespace_proto,
|
||||
self.qname_proto,
|
||||
];
|
||||
v.extend(self.error_protos);
|
||||
v
|
||||
@@ -128,8 +144,8 @@ pub(crate) struct Frame {
|
||||
pub(crate) pc: usize,
|
||||
/// Where this frame's operands start on the operand stack.
|
||||
base: usize,
|
||||
env: EnvId,
|
||||
var_env: EnvId,
|
||||
pub(crate) env: EnvId,
|
||||
pub(crate) var_env: EnvId,
|
||||
/// `with` and catch environments entered and not yet left.
|
||||
env_depth: u32,
|
||||
this: Value,
|
||||
@@ -164,6 +180,13 @@ pub(crate) struct Interp {
|
||||
pub(crate) throw_site: Option<ThrowSite>,
|
||||
/// The last exception a run did not catch.
|
||||
pub(crate) last_thrown: Value,
|
||||
/// The last `Error` object thrown in this run, caught or not, or `null` (`$.error`).
|
||||
pub(crate) last_error: Value,
|
||||
/// An exception passed on rather than thrown again: one a `finally` block restores, or one
|
||||
/// leaving a nested run. [`Interp::unwind`] does not make it [`Interp::last_error`] again.
|
||||
pub(crate) passing: Value,
|
||||
/// The locale `localize` and `Object.prototype.toString` read.
|
||||
pub(crate) localization: Rc<crate::builtins::extensions::Localization>,
|
||||
/// The state of `Math.random`'s generator.
|
||||
pub(crate) random: u64,
|
||||
/// The objects `Array.prototype.join` and `toLocaleString` are joining, innermost last: a
|
||||
@@ -179,6 +202,8 @@ 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>,
|
||||
/// The global code's default XML namespace URI (ECMA-357 section 12.1).
|
||||
pub(crate) xml_default_uri: Key,
|
||||
/// 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 outermost loop of a resumable run is running ([`crate::Realm::advance`]).
|
||||
@@ -197,6 +222,16 @@ pub(crate) struct Interp {
|
||||
pub(crate) evaluated: u32,
|
||||
/// The tag of the source the last run's error was raised in.
|
||||
pub(crate) error_tag: u32,
|
||||
/// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is
|
||||
/// propagating.
|
||||
pub(crate) thrown_mark: Option<u32>,
|
||||
/// The marked exceptions `finally` blocks are running for, innermost last, each with its mark,
|
||||
/// which the block's end throws it on with, and the stack slot that holds it while the block
|
||||
/// runs. An entry whose slot no longer holds its exception belongs to a block that `break`,
|
||||
/// `continue` or `return` left, and [`Self::drop_left_finally_marks`] removes it.
|
||||
pub(crate) finally_marks: Vec<(ObjId, u32, usize)>,
|
||||
/// The mark of the host error the last run ended with.
|
||||
pub(crate) error_mark: Option<u32>,
|
||||
/// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs.
|
||||
pub(crate) strict_writes: bool,
|
||||
}
|
||||
@@ -381,12 +416,16 @@ impl Interp {
|
||||
source_units: 0,
|
||||
throw_site: None,
|
||||
last_thrown: Value::Undefined,
|
||||
last_error: Value::Null,
|
||||
passing: Value::Undefined,
|
||||
localization: Rc::default(),
|
||||
random: random_seed(),
|
||||
join_stack: Vec::new(),
|
||||
held_bytes: 0,
|
||||
install_error: None,
|
||||
date_host: crate::date_builtins::DateHost::default(),
|
||||
held: Rc::default(),
|
||||
xml_default_uri: Rc::from(Vec::new()),
|
||||
pause: Rc::default(),
|
||||
in_slice: false,
|
||||
can_wait: Rc::default(),
|
||||
@@ -396,6 +435,9 @@ impl Interp {
|
||||
source_tag: crate::realm::UNKNOWN_SOURCE,
|
||||
evaluated: 0,
|
||||
error_tag: crate::realm::UNKNOWN_SOURCE,
|
||||
thrown_mark: None,
|
||||
finally_marks: Vec::new(),
|
||||
error_mark: None,
|
||||
strict_writes: false,
|
||||
};
|
||||
crate::builtins::install(&mut interp);
|
||||
@@ -440,11 +482,11 @@ impl Interp {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn frame(&self) -> JsResult<&Frame> {
|
||||
pub(crate) fn frame(&self) -> JsResult<&Frame> {
|
||||
self.frames.last().ok_or_else(|| Abrupt::Internal("no frame".into()))
|
||||
}
|
||||
|
||||
fn frame_mut(&mut self) -> JsResult<&mut Frame> {
|
||||
pub(crate) fn frame_mut(&mut self) -> JsResult<&mut Frame> {
|
||||
self.frames.last_mut().ok_or_else(|| Abrupt::Internal("no frame".into()))
|
||||
}
|
||||
|
||||
@@ -452,7 +494,7 @@ impl Interp {
|
||||
self.frames.last().map_or(0, |f| f.base)
|
||||
}
|
||||
|
||||
fn pop(&mut self) -> JsResult<Value> {
|
||||
pub(crate) fn pop(&mut self) -> JsResult<Value> {
|
||||
if self.stack.len() <= self.base() {
|
||||
return internal("operand stack underflow");
|
||||
}
|
||||
@@ -460,7 +502,7 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The value `n` places below the top (0 is the top).
|
||||
fn peek(&self, n: usize) -> JsResult<Value> {
|
||||
pub(crate) fn peek(&self, n: usize) -> JsResult<Value> {
|
||||
let len = self.stack.len();
|
||||
match len.checked_sub(n + 1).filter(|&i| i >= self.base()) {
|
||||
Some(i) => self.stack.get(i).cloned().ok_or_else(|| Abrupt::Internal("operand stack underflow".into())),
|
||||
@@ -480,7 +522,7 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// Replaces the top `n` values with `v`.
|
||||
fn replace(&mut self, n: usize, v: Value) -> JsResult<()> {
|
||||
pub(crate) fn replace(&mut self, n: usize, v: Value) -> JsResult<()> {
|
||||
self.drop_n(n)?;
|
||||
self.push(v)
|
||||
}
|
||||
@@ -550,11 +592,22 @@ impl Interp {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes the [`Self::finally_marks`] entries of `finally` blocks that `break`, `continue` or
|
||||
/// `return` left: those whose stack slot no longer holds their exception.
|
||||
fn drop_left_finally_marks(&mut self) {
|
||||
let stack = &self.stack;
|
||||
self.finally_marks.retain(|&(id, _, slot)| matches!(stack.get(slot), Some(Value::Object(o)) if *o == id));
|
||||
}
|
||||
|
||||
pub(crate) fn collect_garbage(&mut self) {
|
||||
self.drop_left_finally_marks();
|
||||
let mut roots = Roots::default();
|
||||
roots.values.extend(self.stack.iter());
|
||||
roots.values.extend(self.temp_roots.iter());
|
||||
roots.values.push(&self.last_thrown);
|
||||
roots.values.push(&self.last_error);
|
||||
roots.values.push(&self.passing);
|
||||
roots.objects.extend(self.finally_marks.iter().map(|&(id, _, _)| id));
|
||||
for f in &self.frames {
|
||||
roots.values.push(&f.this);
|
||||
roots.values.push(&f.completion);
|
||||
@@ -640,9 +693,18 @@ impl Interp {
|
||||
/// boundary frame. Returns the exception when no handler takes it before the boundary frame.
|
||||
fn unwind(&mut self, v: Value) -> JsResult<()> {
|
||||
self.note_site();
|
||||
let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b);
|
||||
if !passed
|
||||
&& let Value::Object(o) = v
|
||||
&& self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error))
|
||||
{
|
||||
self.last_error = v.clone();
|
||||
}
|
||||
loop {
|
||||
let Some(frame) = self.frames.last_mut() else { return Err(Abrupt::Throw(v)) };
|
||||
if let Some(h) = frame.code.handler(frame.pc.saturating_sub(1)) {
|
||||
// A catch clause starts with `PushCatch`; every other handler is a `finally` block's.
|
||||
let caught = matches!(frame.code.ops.get(h.target as usize), Some(Op::PushCatch(_)));
|
||||
let target_len = frame.base + h.depth as usize;
|
||||
while frame.env_depth > h.env_depth {
|
||||
let outer = self.heap.env(frame.env).and_then(Env::outer);
|
||||
@@ -655,6 +717,10 @@ impl Interp {
|
||||
return internal("handler stack deeper than the stack");
|
||||
}
|
||||
self.stack.truncate(target_len);
|
||||
self.drop_left_finally_marks();
|
||||
if let (Some(mark), false, Value::Object(id)) = (self.thrown_mark.take(), caught, &v) {
|
||||
self.finally_marks.push((*id, mark, target_len));
|
||||
}
|
||||
self.stack.push(v);
|
||||
self.throw_site = None;
|
||||
return Ok(());
|
||||
@@ -662,11 +728,18 @@ impl Interp {
|
||||
let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) };
|
||||
self.stack.truncate(frame.base);
|
||||
if frame.boundary {
|
||||
self.passing = v.clone();
|
||||
return Err(Abrupt::Throw(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each running frame of script code, outermost first: its code, the index of its next
|
||||
/// instruction, and whether it runs a function (not global or eval code).
|
||||
pub(crate) fn script_frames(&self) -> impl Iterator<Item = (&Rc<Code>, usize, bool)> {
|
||||
self.frames.iter().map(|f| (&f.code, f.pc, f.callee.is_some()))
|
||||
}
|
||||
|
||||
fn abort_to_boundary(&mut self) {
|
||||
while let Some(frame) = self.frames.pop() {
|
||||
self.stack.truncate(frame.base);
|
||||
@@ -690,7 +763,7 @@ impl Interp {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn jump_to(&mut self, target: u32) -> JsResult<()> {
|
||||
pub(crate) fn jump_to(&mut self, target: u32) -> JsResult<()> {
|
||||
self.frame_mut()?.pc = target as usize;
|
||||
Ok(())
|
||||
}
|
||||
@@ -768,7 +841,10 @@ impl Interp {
|
||||
Op::Jump(t) => self.jump_to(t),
|
||||
Op::JumpIfFalse(t) | Op::JumpIfTrue(t) => self.op_branch(t, matches!(op, Op::JumpIfTrue(_)), false),
|
||||
Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) => self.op_branch(t, matches!(op, Op::JumpIfTrueKeep(_)), true),
|
||||
Op::Throw => Err(Abrupt::Throw(self.pop()?)),
|
||||
Op::Throw => {
|
||||
self.thrown_mark = None;
|
||||
Err(Abrupt::Throw(self.pop()?))
|
||||
}
|
||||
Op::ThrowReferenceError(i) => self.op_throw_reference_error(i),
|
||||
Op::EndFinally(t) => self.op_end_finally(t),
|
||||
Op::NewObject => self.op_new_object(),
|
||||
@@ -794,6 +870,17 @@ impl Interp {
|
||||
let v = self.frame()?.completion.clone();
|
||||
self.push(v)
|
||||
}
|
||||
Op::XmlMakeName { attribute, qualified } => self.op_xml_make_name(attribute, qualified),
|
||||
Op::XmlDescendants => self.op_xml_descendants(),
|
||||
Op::XmlEscape(kind) => self.op_xml_escape(kind),
|
||||
Op::XmlLiteral { parts, list } => self.op_xml_literal(parts, list),
|
||||
Op::XmlScopeGet => self.op_xml_scope_get(),
|
||||
Op::XmlFilterStart => self.op_xml_filter_start(),
|
||||
Op::XmlFilterNext(t) => self.op_xml_filter_next(t),
|
||||
Op::XmlFilterTest => self.op_xml_filter_test(),
|
||||
Op::XmlFilterEnd => self.op_xml_filter_end(),
|
||||
Op::ForEachValue => self.op_for_each_value(),
|
||||
Op::SetDefaultNamespace => self.op_set_default_namespace(),
|
||||
Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"),
|
||||
}
|
||||
}
|
||||
@@ -850,7 +937,15 @@ impl Interp {
|
||||
return self.pop().map(drop);
|
||||
}
|
||||
if kind == 1.0 {
|
||||
return Err(Abrupt::Throw(self.pop()?));
|
||||
let v = self.pop()?;
|
||||
self.passing = v.clone();
|
||||
if let Value::Object(o) = v
|
||||
&& let Some(i) = self.finally_marks.iter().rposition(|&(id, _, _)| id == o)
|
||||
{
|
||||
self.thrown_mark = self.finally_marks.get(i).map(|&(_, mark, _)| mark);
|
||||
self.finally_marks.truncate(i);
|
||||
}
|
||||
return Err(Abrupt::Throw(v));
|
||||
}
|
||||
let k = (kind - 2.0) as usize;
|
||||
let target = self.frame()?.code.finally_tables.get(table as usize).and_then(|t| t.get(k)).copied();
|
||||
@@ -862,7 +957,7 @@ impl Interp {
|
||||
|
||||
// ---- variables ----
|
||||
|
||||
fn resolve(&self, name: &[u16]) -> JsResult<Resolved> {
|
||||
fn resolve(&mut self, name: &[u16]) -> JsResult<Resolved> {
|
||||
let mut cur = Some(self.frame()?.env);
|
||||
while let Some(e) = cur {
|
||||
match self.heap.env(e) {
|
||||
@@ -872,11 +967,11 @@ impl Interp {
|
||||
}
|
||||
cur = *outer;
|
||||
}
|
||||
Some(Env::Obj { object, with_this, outer }) => {
|
||||
if self.has_property(*object, name)? {
|
||||
return Ok(Resolved::Obj { object: *object, with_this: *with_this });
|
||||
Some(&Env::Obj { object, with_this, outer }) => {
|
||||
if self.scope_has(object, name)? {
|
||||
return Ok(Resolved::Obj { object, with_this });
|
||||
}
|
||||
cur = *outer;
|
||||
cur = outer;
|
||||
}
|
||||
None => return internal("environment out of range"),
|
||||
}
|
||||
@@ -906,7 +1001,7 @@ impl Interp {
|
||||
match r {
|
||||
Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)),
|
||||
Resolved::Obj { object, with_this } => {
|
||||
let v = self.get_from(object, name, &Value::Object(object))?;
|
||||
let v = self.get_value(&Value::Object(object), name)?;
|
||||
Ok((v, if with_this { Value::Object(object) } else { Value::Undefined }))
|
||||
}
|
||||
Resolved::Unresolved => Err(self.not_defined(name)),
|
||||
@@ -933,6 +1028,9 @@ impl Interp {
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
Resolved::Obj { object, .. } if self.options.e4x && self.is_xml(&Value::Object(object)) => {
|
||||
self.put_value(&Value::Object(object), name.clone(), v)
|
||||
}
|
||||
Resolved::Obj { object, .. } => {
|
||||
let throw = self.strict_writes();
|
||||
self.put(object, name.clone(), v, throw)
|
||||
@@ -947,6 +1045,13 @@ impl Interp {
|
||||
|
||||
fn op_get_var(&mut self, n: u32, with_this: bool) -> JsResult<()> {
|
||||
let name = self.name(n)?;
|
||||
if with_this
|
||||
&& self.options.e4x
|
||||
&& let Some((f, this)) = self.xml_scope_method(&name)?
|
||||
{
|
||||
self.push(f)?;
|
||||
return self.push(this);
|
||||
}
|
||||
let (v, this) = self.get_var(&name)?;
|
||||
self.push(v)?;
|
||||
if with_this { self.push(this) } else { Ok(()) }
|
||||
@@ -1123,6 +1228,9 @@ impl Interp {
|
||||
|
||||
/// `base[k]` for any value (GetValue, section 8.7.1).
|
||||
pub(crate) fn get_value(&mut self, base: &Value, k: &[u16]) -> JsResult<Value> {
|
||||
if self.options.e4x && self.is_xml(base) {
|
||||
return self.xml_get(base, &Value::String(Str::from_units(k.to_vec())));
|
||||
}
|
||||
if let Value::String(s) = base {
|
||||
if is(k, "length") {
|
||||
return Ok(Value::Number(s.len() as f64));
|
||||
@@ -1469,6 +1577,9 @@ impl Interp {
|
||||
|
||||
/// PutValue on a property reference (section 8.7.2), whose base may be a primitive.
|
||||
fn put_value(&mut self, base: &Value, k: Key, v: Value) -> JsResult<()> {
|
||||
if self.options.e4x && self.is_xml(base) {
|
||||
return self.xml_put(base, &Value::String(Str::from_rc(k)), &v);
|
||||
}
|
||||
let strict = self.strict();
|
||||
match base {
|
||||
Value::Object(o) => {
|
||||
@@ -1497,6 +1608,11 @@ impl Interp {
|
||||
fn op_get_member(&mut self, n: u32, with_this: bool) -> JsResult<()> {
|
||||
let name = self.name(n)?;
|
||||
let base = self.peek(0)?;
|
||||
if with_this && self.options.e4x && self.is_xml(&base) {
|
||||
let (f, this) = self.xml_method(&base, &name)?;
|
||||
self.replace(1, f)?;
|
||||
return self.push(this);
|
||||
}
|
||||
let v = self.get_value(&base, &name)?;
|
||||
self.replace(1, v)?;
|
||||
if with_this { self.push(base) } else { Ok(()) }
|
||||
@@ -1525,6 +1641,9 @@ impl Interp {
|
||||
fn op_to_key(&mut self) -> JsResult<()> {
|
||||
let k = self.peek(0)?;
|
||||
let base = self.peek(1)?;
|
||||
if self.is_xml_access(&base, &k) {
|
||||
return Ok(());
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
let name = self.to_key(&k)?;
|
||||
self.replace(1, Value::String(Str::from_rc(name)))
|
||||
@@ -1533,6 +1652,16 @@ impl Interp {
|
||||
fn op_get_index(&mut self, with_this: bool) -> JsResult<()> {
|
||||
let k = self.peek(0)?;
|
||||
let base = self.peek(1)?;
|
||||
if self.is_xml_access(&base, &k) {
|
||||
if with_this {
|
||||
let name = self.xml_method_key(&k)?;
|
||||
let (f, this) = self.xml_method(&base, &name)?;
|
||||
self.replace(2, f)?;
|
||||
return self.push(this);
|
||||
}
|
||||
let v = self.xml_get(&base, &k)?;
|
||||
return self.replace(2, v);
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
let name = self.to_key(&k)?;
|
||||
let v = self.get_value(&base, &name)?;
|
||||
@@ -1544,6 +1673,10 @@ impl Interp {
|
||||
let v = self.peek(0)?;
|
||||
let k = self.peek(1)?;
|
||||
let base = self.peek(2)?;
|
||||
if self.is_xml_access(&base, &k) {
|
||||
self.xml_put(&base, &k, &v)?;
|
||||
return self.replace(3, v);
|
||||
}
|
||||
let name = self.to_key(&k)?;
|
||||
self.put_value(&base, name, v.clone())?;
|
||||
self.replace(3, v)
|
||||
@@ -1552,6 +1685,10 @@ impl Interp {
|
||||
fn op_delete_member(&mut self, n: u32) -> JsResult<()> {
|
||||
let name = self.name(n)?;
|
||||
let base = self.peek(0)?;
|
||||
if self.options.e4x && self.is_xml(&base) {
|
||||
let r = self.xml_delete(&base, &Value::String(Str::from_rc(name)))?;
|
||||
return self.replace(1, Value::Bool(r));
|
||||
}
|
||||
let o = self.to_object(&base)?;
|
||||
let strict = self.strict();
|
||||
let r = self.delete(o, &name, strict)?;
|
||||
@@ -1561,6 +1698,10 @@ impl Interp {
|
||||
fn op_delete_index(&mut self) -> JsResult<()> {
|
||||
let k = self.peek(0)?;
|
||||
let base = self.peek(1)?;
|
||||
if self.is_xml_access(&base, &k) {
|
||||
let r = self.xml_delete(&base, &k)?;
|
||||
return self.replace(2, Value::Bool(r));
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
let name = self.to_key(&k)?;
|
||||
let o = self.to_object(&base)?;
|
||||
@@ -1587,6 +1728,13 @@ impl Interp {
|
||||
fn op_inc_index(&mut self, prefix: bool, dec: bool) -> JsResult<()> {
|
||||
let k = self.peek(0)?;
|
||||
let base = self.peek(1)?;
|
||||
if self.is_xml_access(&base, &k) {
|
||||
let v = self.xml_get(&base, &k)?;
|
||||
let old = self.to_number(&v)?;
|
||||
let new = if dec { old - 1.0 } else { old + 1.0 };
|
||||
self.xml_put(&base, &k, &Value::Number(new))?;
|
||||
return self.replace(2, Value::Number(if prefix { new } else { old }));
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
let name = self.to_key(&k)?;
|
||||
let r = self.inc_property(&base, name, prefix, dec)?;
|
||||
@@ -1752,6 +1900,9 @@ impl Interp {
|
||||
/// For a String object, the heap budget for all its index names is checked before any is
|
||||
/// built. Each index name and each property visited takes a unit of fuel.
|
||||
fn enumerable_keys(&mut self, id: ObjId) -> JsResult<Vec<Key>> {
|
||||
if self.options.e4x && self.is_xml(&Value::Object(id)) {
|
||||
return self.xml_enumerate(id);
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
let mut cur = Some(id);
|
||||
@@ -1818,7 +1969,7 @@ impl Interp {
|
||||
state.pos += 1;
|
||||
let object = state.object;
|
||||
if let Some(o) = object
|
||||
&& self.has_property(o, &k)?
|
||||
&& self.scope_has(o, &k)?
|
||||
{
|
||||
return self.push(Value::String(Str::from_rc(k)));
|
||||
}
|
||||
@@ -2327,6 +2478,7 @@ impl Interp {
|
||||
Value::Bool(_) => "boolean",
|
||||
Value::Number(_) => "number",
|
||||
Value::String(_) => "string",
|
||||
Value::Object(_) if self.options.e4x && self.is_xml(v) => "xml",
|
||||
Value::Object(_) if self.is_callable(v) => "function",
|
||||
Value::Object(_) => "object",
|
||||
}
|
||||
@@ -2488,6 +2640,9 @@ impl Interp {
|
||||
BinaryOp::StrictNotEq => Ok(Value::Bool(!strict_eq(a, b))),
|
||||
BinaryOp::Instanceof => self.instance_of(a, b).map(Value::Bool),
|
||||
BinaryOp::In => {
|
||||
if self.options.e4x && self.is_xml(b) {
|
||||
return self.xml_has(b, a).map(Value::Bool);
|
||||
}
|
||||
let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) };
|
||||
let k = self.to_key(a)?;
|
||||
self.has_property(*o, &k).map(Value::Bool)
|
||||
@@ -2500,6 +2655,9 @@ impl Interp {
|
||||
if let (Value::Number(x), Value::Number(y)) = (a, b) {
|
||||
return Ok(Value::Number(x + y));
|
||||
}
|
||||
if self.options.e4x && self.is_xml(a) && self.is_xml(b) {
|
||||
return self.xml_concat(a, b);
|
||||
}
|
||||
let pa = self.to_primitive(a, Hint::Default)?;
|
||||
let pb = self.to_primitive(b, Hint::Default)?;
|
||||
if matches!(pa, Value::String(_)) || matches!(pb, Value::String(_)) {
|
||||
@@ -2532,7 +2690,12 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The abstract equality comparison (section 11.9.3).
|
||||
fn loose_eq(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
|
||||
pub(crate) fn loose_eq(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
|
||||
if self.options.e4x
|
||||
&& let Some(r) = self.xml_loose_eq(a, b)?
|
||||
{
|
||||
return Ok(r);
|
||||
}
|
||||
let (mut x, mut y) = (a.clone(), b.clone());
|
||||
loop {
|
||||
match (&x, &y) {
|
||||
|
||||
@@ -843,6 +843,7 @@ fn code(ops: Vec<Op>) -> Code {
|
||||
max_stack: 0,
|
||||
strict: false,
|
||||
self_name: None,
|
||||
decl_name: None,
|
||||
params: Vec::new(),
|
||||
vars: Vec::new(),
|
||||
fun_decls: Vec::new(),
|
||||
|
||||
+21
-1
@@ -47,13 +47,30 @@ pub struct Lexer<'s> {
|
||||
preprocessor_lines: bool,
|
||||
/// The deepest nesting of groups a regular expression literal may have.
|
||||
max_depth: usize,
|
||||
/// Read the E4X punctuators `..`, `::` and `@`.
|
||||
e4x: bool,
|
||||
}
|
||||
|
||||
impl<'s> Lexer<'s> {
|
||||
/// A lexer of `src`. `preprocessor_lines` turns on the reading of preprocessor lines;
|
||||
/// `max_depth` limits how deeply a regular expression literal's groups may nest.
|
||||
pub fn new(src: &'s [u16], preprocessor_lines: bool, max_depth: usize) -> Self {
|
||||
Self { src, pos: 0, line: 1, line_start: 0, blank_line: true, preprocessor_lines, max_depth }
|
||||
Self { src, pos: 0, line: 1, line_start: 0, blank_line: true, preprocessor_lines, max_depth, e4x: false }
|
||||
}
|
||||
|
||||
/// The same lexer, reading the E4X punctuators when `e4x` is true.
|
||||
pub fn with_e4x(mut self, e4x: bool) -> Self {
|
||||
self.e4x = e4x;
|
||||
self
|
||||
}
|
||||
|
||||
/// Moves to source offset `pos`, at the given line and column (both from 1), after the parser
|
||||
/// has read an XML literal up to there.
|
||||
pub(crate) fn seek(&mut self, pos: usize, line: u32, column: u32) {
|
||||
self.pos = pos;
|
||||
self.line = line;
|
||||
self.line_start = pos.saturating_sub(column.saturating_sub(1) as usize);
|
||||
self.blank_line = false;
|
||||
}
|
||||
|
||||
/// The code unit at `pos`, as a code point value.
|
||||
@@ -578,6 +595,9 @@ impl<'s> Lexer<'s> {
|
||||
fn punct(&mut self) -> Option<Punct> {
|
||||
let rest = &self.src[self.pos..];
|
||||
for (spelling, punct) in Punct::ALL {
|
||||
if !self.e4x && matches!(punct, Punct::DotDot | Punct::ColonColon | Punct::At) {
|
||||
continue;
|
||||
}
|
||||
let bytes = spelling.as_bytes();
|
||||
if rest.len() >= bytes.len() && rest.iter().zip(bytes).all(|(&u, &b)| u == u16::from(b)) {
|
||||
self.pos += bytes.len();
|
||||
|
||||
+19
-3
@@ -37,6 +37,13 @@
|
||||
//! by [`Limits`]: instructions run (fuel), heap bytes, frames, nested host calls, and an
|
||||
//! [`Interrupt`] flag another thread can set. A run that reaches a limit ends with
|
||||
//! [`RunErrorKind::Limit`], which a script's `try` cannot catch.
|
||||
//!
|
||||
//! With [`Options::e4x`], the parser also reads E4X (ECMA-357, second edition, December 2005):
|
||||
//! XML and XMLList literals, the `.@`, `..`, `::` and `.( )` operators, `for each … in` and
|
||||
//! `default xml namespace`; the realm then provides `XML`, `XMLList`, `Namespace`, `QName`,
|
||||
//! `isXMLName` and `setDefaultXMLNamespace`. Without the option, the language and the built-ins are
|
||||
//! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and
|
||||
//! serializing them use no native recursion and take fuel for each node.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
@@ -60,13 +67,16 @@ mod regexp_vm;
|
||||
mod string_builtins;
|
||||
mod token;
|
||||
mod value;
|
||||
mod xml;
|
||||
mod xml_builtins;
|
||||
|
||||
pub use ast::{
|
||||
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LogicalOp, Name, Program, Property,
|
||||
PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl,
|
||||
PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
};
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use host::{Arg, Data, DataLimits, HostError, HostFunction, HostItem};
|
||||
pub use host::{Arg, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
pub use number::to_string as number_to_string;
|
||||
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, UNKNOWN_SOURCE};
|
||||
@@ -84,11 +94,13 @@ pub struct Options {
|
||||
pub max_depth: usize,
|
||||
/// The most UTF-16 code units a source may hold.
|
||||
pub max_source_units: usize,
|
||||
/// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins.
|
||||
pub e4x: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20 }
|
||||
Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +199,8 @@ impl LineTable {
|
||||
#[cfg(test)]
|
||||
mod builtins_tests;
|
||||
#[cfg(test)]
|
||||
mod extension_tests;
|
||||
#[cfg(test)]
|
||||
mod host_tests;
|
||||
#[cfg(test)]
|
||||
mod interp_tests;
|
||||
@@ -194,3 +208,5 @@ mod interp_tests;
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod text_tests;
|
||||
#[cfg(test)]
|
||||
mod xml_tests;
|
||||
+51
-8
@@ -7,6 +7,8 @@
|
||||
//! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long
|
||||
//! runs of them do not nest at all.
|
||||
|
||||
mod xml;
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::LineTable;
|
||||
@@ -69,11 +71,13 @@ pub(crate) struct Parser<'s> {
|
||||
/// The next statement stands in a statement list, where a label's body may be a function
|
||||
/// declaration. Read and cleared as each statement starts.
|
||||
in_list: bool,
|
||||
/// Read E4X syntax.
|
||||
e4x: bool,
|
||||
}
|
||||
|
||||
impl<'s> Parser<'s> {
|
||||
pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result<Self> {
|
||||
let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth);
|
||||
let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x);
|
||||
let placeholder =
|
||||
Token { kind: TokenKind::Eof, span: Span::default(), line: 1, column: 1, newline_before: false, escaped: false, legacy_octal: false };
|
||||
let mut parser = Self {
|
||||
@@ -90,6 +94,7 @@ impl<'s> Parser<'s> {
|
||||
tokens: keep_tokens.then(Vec::new),
|
||||
function_allowed: false,
|
||||
in_list: false,
|
||||
e4x: options.e4x,
|
||||
};
|
||||
parser.tok = parser.next_significant()?;
|
||||
Ok(parser)
|
||||
@@ -391,6 +396,7 @@ impl<'s> Parser<'s> {
|
||||
self.semicolon()?;
|
||||
Ok(self.ast.push_stmt(Stmt::Debugger, self.span_from(start)))
|
||||
}
|
||||
Keyword::Default if self.at_default_xml_namespace() => self.parse_default_xml_namespace(start),
|
||||
_ => {
|
||||
let expr = self.parse_expression(false)?;
|
||||
self.semicolon()?;
|
||||
@@ -488,7 +494,14 @@ impl<'s> Parser<'s> {
|
||||
|
||||
fn parse_for(&mut self, start: Span) -> Result<StmtId> {
|
||||
self.bump()?;
|
||||
let each = self.e4x && self.tok.ident() == Some("each");
|
||||
if each {
|
||||
self.bump()?;
|
||||
}
|
||||
self.expect(Punct::LParen)?;
|
||||
if each {
|
||||
return self.parse_for_each(start);
|
||||
}
|
||||
let init = if self.at(Punct::Semicolon) {
|
||||
None
|
||||
} else if self.at_keyword(Keyword::Var) {
|
||||
@@ -501,14 +514,14 @@ impl<'s> Parser<'s> {
|
||||
if self.ctx.strict && decl.init.is_some() {
|
||||
return Err(self.error_at_token(&self.tok, "a for-in variable cannot have an initializer in strict mode code"));
|
||||
}
|
||||
return self.parse_for_in(ForInTarget::Var(decl), start);
|
||||
return self.parse_for_in(ForInTarget::Var(decl), start, false);
|
||||
}
|
||||
Some(ForInit::Var(decls))
|
||||
} else {
|
||||
let expr = self.parse_expression(true)?;
|
||||
if self.at_keyword(Keyword::In) {
|
||||
self.check_target(expr, "invalid left-hand side in for-in loop")?;
|
||||
return self.parse_for_in(ForInTarget::Expr(expr), start);
|
||||
return self.parse_for_in(ForInTarget::Expr(expr), start, false);
|
||||
}
|
||||
Some(ForInit::Expr(expr))
|
||||
};
|
||||
@@ -522,12 +535,27 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
|
||||
/// The rest of `for (target in object) body`, from `in`.
|
||||
fn parse_for_in(&mut self, target: ForInTarget, start: Span) -> Result<StmtId> {
|
||||
fn parse_for_in(&mut self, target: ForInTarget, start: Span, each: bool) -> Result<StmtId> {
|
||||
self.expect_keyword(Keyword::In)?;
|
||||
let object = self.parse_expression(false)?;
|
||||
self.expect(Punct::RParen)?;
|
||||
let body = self.parse_loop_body()?;
|
||||
Ok(self.ast.push_stmt(Stmt::ForIn { target, object, body }, self.span_from(start)))
|
||||
Ok(self.ast.push_stmt(Stmt::ForIn { target, object, body, each }, self.span_from(start)))
|
||||
}
|
||||
|
||||
/// `for each (target in object) body`, from the target (ECMA-357 section 12.3).
|
||||
fn parse_for_each(&mut self, start: Span) -> Result<StmtId> {
|
||||
if self.at_keyword(Keyword::Var) {
|
||||
self.bump()?;
|
||||
let mut decls = self.parse_var_decls(true)?;
|
||||
let (Some(decl), true) = (decls.pop(), decls.is_empty()) else {
|
||||
return Err(self.error_at_token(&self.tok, "for each takes one variable"));
|
||||
};
|
||||
return self.parse_for_in(ForInTarget::Var(decl), start, true);
|
||||
}
|
||||
let expr = self.parse_expression(true)?;
|
||||
self.check_target(expr, "invalid left-hand side in for each loop")?;
|
||||
self.parse_for_in(ForInTarget::Expr(expr), start, true)
|
||||
}
|
||||
|
||||
/// `break` or `continue`, with an optional label on the same line, which must name a label
|
||||
@@ -608,7 +636,7 @@ impl<'s> Parser<'s> {
|
||||
let test = if self.at_keyword(Keyword::Case) {
|
||||
self.bump()?;
|
||||
Some(self.parse_expression(false)?)
|
||||
} else if self.at_keyword(Keyword::Default) {
|
||||
} else if self.at_keyword(Keyword::Default) && !self.at_default_xml_namespace() {
|
||||
if has_default {
|
||||
return Err(self.error_at_token(&self.tok, "more than one default clause in switch statement"));
|
||||
}
|
||||
@@ -620,7 +648,10 @@ impl<'s> Parser<'s> {
|
||||
};
|
||||
self.expect(Punct::Colon)?;
|
||||
let mut body = Vec::new();
|
||||
while !(self.at_keyword(Keyword::Case) || self.at_keyword(Keyword::Default) || self.at(Punct::RBrace)) {
|
||||
while !(self.at_keyword(Keyword::Case)
|
||||
|| (self.at_keyword(Keyword::Default) && !self.at_default_xml_namespace())
|
||||
|| self.at(Punct::RBrace))
|
||||
{
|
||||
if self.tok.kind == TokenKind::Eof {
|
||||
return Err(self.unexpected());
|
||||
}
|
||||
@@ -953,8 +984,13 @@ impl<'s> Parser<'s> {
|
||||
let mut expr = self.parse_primary()?;
|
||||
loop {
|
||||
match &self.tok.kind {
|
||||
TokenKind::Punct(Punct::DotDot) => expr = self.parse_xml_descendants(expr)?,
|
||||
TokenKind::Punct(Punct::Dot) => {
|
||||
self.bump()?;
|
||||
if self.e4x && self.at_e4x_member() {
|
||||
expr = self.parse_xml_member(expr)?;
|
||||
continue;
|
||||
}
|
||||
let Some(name) = self.tok.identifier_name().map(str::to_string) else {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a property name but found {}", describe(&self.tok))));
|
||||
};
|
||||
@@ -1050,10 +1086,16 @@ impl<'s> Parser<'s> {
|
||||
self.expect(Punct::RParen)?;
|
||||
return Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start)));
|
||||
}
|
||||
TokenKind::Punct(Punct::Lt) if self.e4x => return self.parse_xml_literal(),
|
||||
TokenKind::Punct(Punct::At | Punct::Star) if self.e4x => return self.parse_xml_scope_name(),
|
||||
_ => return Err(self.unexpected()),
|
||||
};
|
||||
let token = self.bump()?;
|
||||
Ok(self.ast.push_expr(expr, token.span))
|
||||
let id = self.ast.push_expr(expr, token.span);
|
||||
if self.e4x && self.at(Punct::ColonColon) && matches!(token.kind, TokenKind::Ident(_)) {
|
||||
return self.parse_xml_qualified_primary(id);
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn parse_function_expression(&mut self) -> Result<ExprId> {
|
||||
@@ -1232,5 +1274,6 @@ fn describe(token: &Token) -> String {
|
||||
TokenKind::String(_) => "string".into(),
|
||||
TokenKind::RegExp { .. } => "regular expression".into(),
|
||||
TokenKind::Directive(_) => "preprocessor line".into(),
|
||||
TokenKind::XmlLiteral => "XML literal".into(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
//! E4X syntax (ECMA-357 sections 11.1 and 12.1): literals, names and the operators on them.
|
||||
//!
|
||||
//! A literal is read by scanning the source units with an explicit stack of open tags, so tag
|
||||
//! nesting uses no native recursion and is held to [`crate::Options::max_depth`]. Only an embedded
|
||||
//! `{expression}` re-enters the expression parser, and that recursion is counted as any other.
|
||||
|
||||
use super::{Parser, Result, describe};
|
||||
use crate::ast::{Expr, ExprId, Stmt, StmtId, XmlNamePart, XmlPart, XmlQualifier};
|
||||
use crate::error::TOO_DEEP;
|
||||
use crate::token::{Keyword, Punct, Span, TokenKind};
|
||||
use crate::xml::{is_name_start, is_xml_space, scan_name, scan_reference};
|
||||
|
||||
const LT: u16 = b'<' as u16;
|
||||
const GT: u16 = b'>' as u16;
|
||||
const SLASH: u16 = b'/' as u16;
|
||||
const AMP: u16 = b'&' as u16;
|
||||
const LBRACE: u16 = b'{' as u16;
|
||||
const EQ: u16 = b'=' as u16;
|
||||
const DQUOTE: u16 = b'"' as u16;
|
||||
const SQUOTE: u16 = b'\'' as u16;
|
||||
|
||||
/// A literal being read: the markup since the last embedded expression, and the finished parts.
|
||||
#[derive(Default)]
|
||||
struct Scan {
|
||||
text: Vec<u16>,
|
||||
parts: Vec<XmlPart>,
|
||||
}
|
||||
|
||||
impl Scan {
|
||||
fn flush(&mut self) {
|
||||
if !self.text.is_empty() {
|
||||
self.parts.push(XmlPart::Text(std::mem::take(&mut self.text)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
pub(super) fn at_default_xml_namespace(&self) -> bool {
|
||||
self.e4x && self.peek().is_some_and(|t| t.ident() == Some("xml"))
|
||||
}
|
||||
|
||||
/// `default xml namespace = expression;`, from `default`.
|
||||
pub(super) fn parse_default_xml_namespace(&mut self, start: Span) -> Result<StmtId> {
|
||||
self.expect_keyword(Keyword::Default)?;
|
||||
self.bump()?;
|
||||
if self.tok.ident() != Some("namespace") {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected 'namespace' but found {}", describe(&self.tok))));
|
||||
}
|
||||
self.bump()?;
|
||||
self.expect(Punct::Eq)?;
|
||||
let value = self.parse_expression(false)?;
|
||||
self.semicolon()?;
|
||||
Ok(self.ast.push_stmt(Stmt::DefaultXmlNamespace(value), self.span_from(start)))
|
||||
}
|
||||
|
||||
/// After a `.`: the next token starts an E4X name or a filter rather than a property name.
|
||||
pub(super) fn at_e4x_member(&self) -> bool {
|
||||
match &self.tok.kind {
|
||||
TokenKind::Punct(Punct::At | Punct::Star | Punct::LParen) => true,
|
||||
_ => self.tok.identifier_name().is_some() && self.peek().is_some_and(|t| t.is_punct(Punct::ColonColon)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `object.@name`, `object.*`, `object.ns::name` or `object.(predicate)`, from the token after
|
||||
/// the `.`.
|
||||
pub(super) fn parse_xml_member(&mut self, object: ExprId) -> Result<ExprId> {
|
||||
let start = self.ast.expr_span(object);
|
||||
if self.at(Punct::LParen) {
|
||||
self.bump()?;
|
||||
let predicate = self.parse_expression(false)?;
|
||||
self.expect(Punct::RParen)?;
|
||||
return Ok(self.ast.push_expr(Expr::XmlFilter { object, predicate }, self.span_from(start)));
|
||||
}
|
||||
let index = self.parse_xml_name()?;
|
||||
Ok(self.ast.push_expr(Expr::Index { object, index }, self.span_from(start)))
|
||||
}
|
||||
|
||||
/// `object..name`, from the `..`.
|
||||
pub(super) fn parse_xml_descendants(&mut self, object: ExprId) -> Result<ExprId> {
|
||||
let start = self.ast.expr_span(object);
|
||||
self.bump()?;
|
||||
let name = self.parse_xml_name()?;
|
||||
Ok(self.ast.push_expr(Expr::XmlDescendants { object, name }, self.span_from(start)))
|
||||
}
|
||||
|
||||
/// `@name`, `*` or `@*` standing alone as a primary expression.
|
||||
pub(super) fn parse_xml_scope_name(&mut self) -> Result<ExprId> {
|
||||
let start = self.tok.span;
|
||||
let name = self.parse_xml_name()?;
|
||||
Ok(self.ast.push_expr(Expr::XmlScopeName(name), self.span_from(start)))
|
||||
}
|
||||
|
||||
/// `qualifier::name` as a primary expression, from the `::`; `qualifier` is already read.
|
||||
pub(super) fn parse_xml_qualified_primary(&mut self, qualifier: ExprId) -> Result<ExprId> {
|
||||
let start = self.ast.expr_span(qualifier);
|
||||
self.bump()?;
|
||||
let name = self.parse_xml_name_part()?;
|
||||
let qualifier = Some(XmlQualifier::Expr(qualifier));
|
||||
let id = self.ast.push_expr(Expr::XmlName { attribute: false, qualifier, name }, self.span_from(start));
|
||||
Ok(self.ast.push_expr(Expr::XmlScopeName(id), self.span_from(start)))
|
||||
}
|
||||
|
||||
/// An E4X name: `@`, then `*`, a name or `[expression]`, with an optional `qualifier::`.
|
||||
fn parse_xml_name(&mut self) -> Result<ExprId> {
|
||||
let start = self.tok.span;
|
||||
let attribute = self.eat(Punct::At)?;
|
||||
let first_is_star = self.at(Punct::Star);
|
||||
let qualifier_ident = self.tok.identifier_name().map(str::to_string).filter(|_| matches!(self.tok.kind, TokenKind::Ident(_)));
|
||||
let first = self.parse_xml_name_part()?;
|
||||
let (qualifier, name) = if self.at(Punct::ColonColon) {
|
||||
let qualifier = if first_is_star {
|
||||
XmlQualifier::Any
|
||||
} else if let Some(name) = qualifier_ident {
|
||||
let span = self.span_from(start);
|
||||
XmlQualifier::Expr(self.ast.push_expr(Expr::Ident(name), span))
|
||||
} else {
|
||||
return Err(self.error_at_token(&self.tok, "expected a namespace name before '::'"));
|
||||
};
|
||||
self.bump()?;
|
||||
(Some(qualifier), self.parse_xml_name_part()?)
|
||||
} else {
|
||||
(None, first)
|
||||
};
|
||||
Ok(self.ast.push_expr(Expr::XmlName { attribute, qualifier, name }, self.span_from(start)))
|
||||
}
|
||||
|
||||
fn parse_xml_name_part(&mut self) -> Result<XmlNamePart> {
|
||||
if self.eat(Punct::Star)? {
|
||||
return Ok(XmlNamePart::Star);
|
||||
}
|
||||
if self.eat(Punct::LBracket)? {
|
||||
let e = self.parse_expression(false)?;
|
||||
self.expect(Punct::RBracket)?;
|
||||
return Ok(XmlNamePart::Computed(e));
|
||||
}
|
||||
let Some(name) = self.tok.identifier_name().map(str::to_string) else {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected an XML name but found {}", describe(&self.tok))));
|
||||
};
|
||||
self.bump()?;
|
||||
Ok(XmlNamePart::Ident(name))
|
||||
}
|
||||
|
||||
/// An XML or XMLList literal, from its `<` (the current token).
|
||||
pub(super) fn parse_xml_literal(&mut self) -> Result<ExprId> {
|
||||
let start = self.tok.span;
|
||||
let token_slot = self.tokens.as_ref().map(Vec::len);
|
||||
if let Some(tokens) = &mut self.tokens {
|
||||
tokens.push(self.tok.clone());
|
||||
}
|
||||
let mut pos = start.start as usize;
|
||||
let list = self.unit(pos + 1) == Some(GT);
|
||||
if list {
|
||||
pos += 2;
|
||||
}
|
||||
let mut scan = Scan::default();
|
||||
// The name of each open element; `None` when it is computed.
|
||||
let mut open: Vec<Option<Vec<u16>>> = Vec::new();
|
||||
loop {
|
||||
if !list && open.is_empty() && !scan.text.is_empty() | !scan.parts.is_empty() {
|
||||
break;
|
||||
}
|
||||
let Some(c) = self.unit(pos) else { return Err(self.xml_error(pos, "unterminated XML literal")) };
|
||||
if c == LT {
|
||||
if self.unit(pos + 1) == Some(SLASH) {
|
||||
if open.is_empty() {
|
||||
if list && self.unit(pos + 2) == Some(GT) {
|
||||
pos += 3;
|
||||
break;
|
||||
}
|
||||
return Err(self.xml_error(pos, "a closing tag has no matching open tag"));
|
||||
}
|
||||
pos = self.xml_close_tag(pos, &mut open, &mut scan)?;
|
||||
} else if self.starts_with(pos, "<!--") {
|
||||
pos = self.xml_comment(pos, &mut scan)?;
|
||||
} else if self.starts_with(pos, "<![CDATA[") {
|
||||
pos = self.xml_through(pos, "]]>", &mut scan, "unterminated CDATA section")?;
|
||||
} else if self.starts_with(pos, "<?") {
|
||||
pos = self.xml_instruction(pos, &mut scan)?;
|
||||
} else {
|
||||
pos = self.xml_open_tag(pos, &mut open, &mut scan)?;
|
||||
}
|
||||
} else if c == LBRACE {
|
||||
if open.is_empty() && !list {
|
||||
return Err(self.xml_error(pos, "expected an XML tag"));
|
||||
}
|
||||
scan.flush();
|
||||
let (e, after) = self.xml_embedded(pos)?;
|
||||
scan.parts.push(XmlPart::Content(e));
|
||||
pos = after;
|
||||
} else {
|
||||
if open.is_empty() && !list {
|
||||
return Err(self.xml_error(pos, "expected an XML tag"));
|
||||
}
|
||||
pos = self.xml_text(pos, &mut scan)?;
|
||||
}
|
||||
}
|
||||
scan.flush();
|
||||
// Reads the token after the literal for the division goal.
|
||||
let (line, column) = self.lines.line_column(pos as u32);
|
||||
self.lex.seek(pos, line, column);
|
||||
self.prev_end = pos as u32;
|
||||
self.tok = self.next_significant()?;
|
||||
if let (Some(slot), Some(tokens)) = (token_slot, &mut self.tokens)
|
||||
&& let Some(token) = tokens.get_mut(slot)
|
||||
{
|
||||
token.kind = TokenKind::XmlLiteral;
|
||||
token.span = Span::new(start.start, pos as u32);
|
||||
}
|
||||
Ok(self.ast.push_expr(Expr::XmlLiteral { parts: scan.parts, list }, Span::new(start.start, pos as u32)))
|
||||
}
|
||||
|
||||
fn unit(&self, pos: usize) -> Option<u16> {
|
||||
self.src.get(pos).copied()
|
||||
}
|
||||
|
||||
fn starts_with(&self, pos: usize, s: &str) -> bool {
|
||||
self.src.get(pos..).is_some_and(|rest| rest.iter().copied().take(s.len()).eq(s.encode_utf16()))
|
||||
}
|
||||
|
||||
fn xml_error(&self, pos: usize, message: &str) -> crate::SyntaxError {
|
||||
self.error_at_offset(pos as u32, message)
|
||||
}
|
||||
|
||||
/// Reads `{expression}` with `pos` at its `{`; returns the expression and the offset after `}`.
|
||||
fn xml_embedded(&mut self, pos: usize) -> Result<(ExprId, usize)> {
|
||||
let (line, column) = self.lines.line_column(pos as u32 + 1);
|
||||
self.lex.seek(pos + 1, line, column);
|
||||
self.tok = self.next_significant()?;
|
||||
let e = self.parse_expression(false)?;
|
||||
if !self.at(Punct::RBrace) {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected '}}' but found {}", describe(&self.tok))));
|
||||
}
|
||||
Ok((e, self.tok.span.end as usize))
|
||||
}
|
||||
|
||||
fn xml_copy(&self, from: usize, to: usize, scan: &mut Scan) {
|
||||
if let Some(units) = self.src.get(from..to) {
|
||||
scan.text.extend_from_slice(units);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies from `pos` through the first `end`, which must be there.
|
||||
fn xml_through(&self, pos: usize, end: &str, scan: &mut Scan, message: &str) -> Result<usize> {
|
||||
let mut at = pos;
|
||||
while at < self.src.len() {
|
||||
if self.starts_with(at, end) {
|
||||
let after = at + end.len();
|
||||
self.xml_copy(pos, after, scan);
|
||||
return Ok(after);
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
Err(self.xml_error(pos, message))
|
||||
}
|
||||
|
||||
fn xml_comment(&self, pos: usize, scan: &mut Scan) -> Result<usize> {
|
||||
let mut at = pos + 4;
|
||||
while at < self.src.len() {
|
||||
if self.starts_with(at, "--") {
|
||||
if self.unit(at + 2) != Some(GT) {
|
||||
return Err(self.xml_error(at, "'--' cannot appear in an XML comment"));
|
||||
}
|
||||
self.xml_copy(pos, at + 3, scan);
|
||||
return Ok(at + 3);
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
Err(self.xml_error(pos, "unterminated XML comment"))
|
||||
}
|
||||
|
||||
fn xml_instruction(&self, pos: usize, scan: &mut Scan) -> Result<usize> {
|
||||
if !self.unit(pos + 2).is_some_and(is_name_start) {
|
||||
return Err(self.xml_error(pos + 2, "invalid processing instruction name"));
|
||||
}
|
||||
self.xml_through(pos, "?>", scan, "unterminated processing instruction")
|
||||
}
|
||||
|
||||
/// Reads a static name at `pos`, which must be one, and returns the offset after it.
|
||||
fn xml_static_name(&self, pos: usize) -> Result<usize> {
|
||||
scan_name(self.src, pos).ok_or_else(|| self.xml_error(pos, "invalid XML name"))
|
||||
}
|
||||
|
||||
fn xml_skip_space(&self, mut pos: usize, scan: &mut Scan) -> usize {
|
||||
let from = pos;
|
||||
while self.unit(pos).is_some_and(is_xml_space) {
|
||||
pos += 1;
|
||||
}
|
||||
self.xml_copy(from, pos, scan);
|
||||
pos
|
||||
}
|
||||
|
||||
fn xml_open_tag(&mut self, pos: usize, open: &mut Vec<Option<Vec<u16>>>, scan: &mut Scan) -> Result<usize> {
|
||||
if open.len() >= self.max_depth {
|
||||
return Err(self.xml_error(pos, TOO_DEEP));
|
||||
}
|
||||
scan.text.push(LT);
|
||||
let mut at = pos + 1;
|
||||
let name = if self.unit(at) == Some(LBRACE) {
|
||||
scan.flush();
|
||||
let (e, after) = self.xml_embedded(at)?;
|
||||
scan.parts.push(XmlPart::Name(e));
|
||||
at = after;
|
||||
None
|
||||
} else {
|
||||
let end = self.xml_static_name(at)?;
|
||||
self.xml_copy(at, end, scan);
|
||||
let name = self.src.get(at..end).map(<[u16]>::to_vec);
|
||||
at = end;
|
||||
name
|
||||
};
|
||||
loop {
|
||||
let before = at;
|
||||
at = self.xml_skip_space(at, scan);
|
||||
match self.unit(at) {
|
||||
None => return Err(self.xml_error(at, "unterminated XML tag")),
|
||||
Some(SLASH) if self.unit(at + 1) == Some(GT) => {
|
||||
scan.text.extend_from_slice(&[SLASH, GT]);
|
||||
return Ok(at + 2);
|
||||
}
|
||||
Some(GT) => {
|
||||
scan.text.push(GT);
|
||||
open.push(name);
|
||||
return Ok(at + 1);
|
||||
}
|
||||
Some(LBRACE) => {
|
||||
if at == before {
|
||||
return Err(self.xml_error(at, "expected white space before attributes"));
|
||||
}
|
||||
scan.flush();
|
||||
let (e, after) = self.xml_embedded(at)?;
|
||||
let mut next = after;
|
||||
while self.unit(next).is_some_and(is_xml_space) {
|
||||
next += 1;
|
||||
}
|
||||
if self.unit(next) == Some(EQ) {
|
||||
scan.parts.push(XmlPart::Name(e));
|
||||
at = self.xml_attribute_value(after, scan)?;
|
||||
} else {
|
||||
scan.parts.push(XmlPart::Attributes(e));
|
||||
at = after;
|
||||
}
|
||||
}
|
||||
Some(_) if at == before => return Err(self.xml_error(at, "expected white space before an attribute")),
|
||||
Some(_) => at = self.xml_attribute(at, scan)?,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads an attribute at `pos` and returns the offset after it.
|
||||
fn xml_attribute(&mut self, pos: usize, scan: &mut Scan) -> Result<usize> {
|
||||
let end = self.xml_static_name(pos)?;
|
||||
self.xml_copy(pos, end, scan);
|
||||
self.xml_attribute_value(end, scan)
|
||||
}
|
||||
|
||||
/// Reads the `=` and value of an attribute whose name ends at `pos` and returns the offset after them.
|
||||
fn xml_attribute_value(&mut self, pos: usize, scan: &mut Scan) -> Result<usize> {
|
||||
let at = self.xml_skip_space(pos, scan);
|
||||
if self.unit(at) != Some(EQ) {
|
||||
return Err(self.xml_error(at, "expected '=' after an attribute name"));
|
||||
}
|
||||
scan.text.push(EQ);
|
||||
let at = self.xml_skip_space(at + 1, scan);
|
||||
match self.unit(at) {
|
||||
Some(LBRACE) => {
|
||||
scan.text.push(DQUOTE);
|
||||
scan.flush();
|
||||
let (e, after) = self.xml_embedded(at)?;
|
||||
scan.parts.push(XmlPart::Attribute(e));
|
||||
scan.text.push(DQUOTE);
|
||||
Ok(after)
|
||||
}
|
||||
Some(q @ (DQUOTE | SQUOTE)) => {
|
||||
let mut end = at + 1;
|
||||
loop {
|
||||
match self.unit(end) {
|
||||
None => return Err(self.xml_error(at, "unterminated attribute value")),
|
||||
Some(c) if c == q => break,
|
||||
Some(LT) => return Err(self.xml_error(end, "'<' cannot appear in an attribute value")),
|
||||
Some(AMP) => end = self.xml_reference(end)?,
|
||||
Some(_) => end += 1,
|
||||
}
|
||||
}
|
||||
self.xml_copy(at, end + 1, scan);
|
||||
Ok(end + 1)
|
||||
}
|
||||
_ => Err(self.xml_error(at, "expected an attribute value")),
|
||||
}
|
||||
}
|
||||
|
||||
fn xml_reference(&self, pos: usize) -> Result<usize> {
|
||||
match scan_reference(self.src, pos) {
|
||||
Some((after, _)) => Ok(after),
|
||||
None => Err(self.xml_error(pos, "invalid XML character or entity reference")),
|
||||
}
|
||||
}
|
||||
|
||||
fn xml_close_tag(&mut self, pos: usize, open: &mut Vec<Option<Vec<u16>>>, scan: &mut Scan) -> Result<usize> {
|
||||
scan.text.extend_from_slice(&[LT, SLASH]);
|
||||
let mut at = pos + 2;
|
||||
let name = if self.unit(at) == Some(LBRACE) {
|
||||
scan.flush();
|
||||
let (e, after) = self.xml_embedded(at)?;
|
||||
scan.parts.push(XmlPart::Name(e));
|
||||
at = after;
|
||||
None
|
||||
} else {
|
||||
let end = self.xml_static_name(at)?;
|
||||
self.xml_copy(at, end, scan);
|
||||
let name = self.src.get(at..end).map(<[u16]>::to_vec);
|
||||
at = end;
|
||||
name
|
||||
};
|
||||
at = self.xml_skip_space(at, scan);
|
||||
if self.unit(at) != Some(GT) {
|
||||
return Err(self.xml_error(at, "expected '>' at the end of a closing tag"));
|
||||
}
|
||||
scan.text.push(GT);
|
||||
if let (Some(Some(opened)), Some(closed)) = (open.last(), &name)
|
||||
&& opened != closed
|
||||
{
|
||||
return Err(self.xml_error(pos, "the closing tag does not match the open tag"));
|
||||
}
|
||||
open.pop();
|
||||
Ok(at + 1)
|
||||
}
|
||||
|
||||
fn xml_text(&self, pos: usize, scan: &mut Scan) -> Result<usize> {
|
||||
let mut at = pos;
|
||||
while let Some(c) = self.unit(at) {
|
||||
if c == LT || c == LBRACE {
|
||||
break;
|
||||
}
|
||||
at = if c == AMP { self.xml_reference(at)? } else { at + 1 };
|
||||
}
|
||||
self.xml_copy(pos, at, scan);
|
||||
Ok(at)
|
||||
}
|
||||
}
|
||||
@@ -229,9 +229,13 @@ impl Realm {
|
||||
interp.source_units = 0;
|
||||
interp.throw_site = None;
|
||||
interp.last_thrown = Value::Undefined;
|
||||
interp.last_error = Value::Null;
|
||||
interp.host_abort = None;
|
||||
interp.waiting = false;
|
||||
interp.error_tag = UNKNOWN_SOURCE;
|
||||
interp.thrown_mark = None;
|
||||
interp.finally_marks.clear();
|
||||
interp.error_mark = None;
|
||||
let strict = interp.options.strict;
|
||||
interp.source_tag = 0;
|
||||
let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global));
|
||||
@@ -252,11 +256,14 @@ impl Realm {
|
||||
let site = interp.throw_site.take();
|
||||
interp.error_tag = site.as_ref().map_or(UNKNOWN_SOURCE, |(code, _)| code.source.tag);
|
||||
let (line, column) = site.map_or((0, 0), |(code, pc)| code.line_column(pc));
|
||||
interp.error_mark = interp.thrown_mark.take().filter(|_| matches!(result, Err(Abrupt::Throw(_) | Abrupt::Limit(LimitKind::Host))));
|
||||
interp.finally_marks.clear();
|
||||
interp.stack.clear();
|
||||
interp.frames.clear();
|
||||
interp.temp_roots.clear();
|
||||
interp.join_stack.clear();
|
||||
interp.waiting = false;
|
||||
interp.passing = Value::Undefined;
|
||||
match result {
|
||||
Ok(v) => Ok(interp.to_js_value(&v)),
|
||||
Err(Abrupt::Throw(v)) => {
|
||||
@@ -367,6 +374,12 @@ impl Realm {
|
||||
self.interp.error_tag
|
||||
}
|
||||
|
||||
/// The mark of the host error ([`crate::HostError::Marked`]) the last run ended with, when no
|
||||
/// `catch` clause took that error's exception on its way out; `None` otherwise.
|
||||
pub fn error_mark(&self) -> Option<u32> {
|
||||
self.interp.error_mark
|
||||
}
|
||||
|
||||
/// Fuel the run has left.
|
||||
pub fn fuel_left(&self) -> u64 {
|
||||
self.interp.fuel
|
||||
@@ -387,6 +400,17 @@ impl Realm {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the script extensions: the global `localize(object, ...values)`, which gives a
|
||||
/// localization object's text for the locale of [`Realm::localization`], the global
|
||||
/// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text,
|
||||
/// and the localized `Object.prototype.toString` while [`crate::Localization::enabled`].
|
||||
pub fn add_script_extensions(&mut self) -> Result<(), RunError> {
|
||||
match crate::builtins::extensions::install(&mut self.interp) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => self.outcome(Err(e)).map(drop),
|
||||
}
|
||||
}
|
||||
|
||||
/// Defines the global function `name`, whose arguments arrive converted as `args` says
|
||||
/// ([`crate::HostItem::Converted`]). Unlike a host object, a script may replace or delete it, as
|
||||
/// it may a built-in function.
|
||||
@@ -397,6 +421,11 @@ impl Realm {
|
||||
}
|
||||
}
|
||||
|
||||
/// The locale `localize` reads, which the host's functions may change during a run.
|
||||
pub fn localization(&self) -> std::rc::Rc<crate::Localization> {
|
||||
self.interp.localization.clone()
|
||||
}
|
||||
|
||||
/// Defines the global variable `name` holding the exception the last run did not catch
|
||||
/// (`undefined` if there was none).
|
||||
pub fn bind_last_thrown(&mut self, name: &str) {
|
||||
|
||||
@@ -204,6 +204,12 @@ pub enum Punct {
|
||||
CaretEq,
|
||||
Slash,
|
||||
SlashEq,
|
||||
/// `..`, read only with [`crate::Options::e4x`].
|
||||
DotDot,
|
||||
/// `::`, read only with [`crate::Options::e4x`].
|
||||
ColonColon,
|
||||
/// `@`, read only with [`crate::Options::e4x`].
|
||||
At,
|
||||
}
|
||||
|
||||
impl Punct {
|
||||
@@ -233,6 +239,9 @@ impl Punct {
|
||||
("|=", Punct::PipeEq),
|
||||
("^=", Punct::CaretEq),
|
||||
("/=", Punct::SlashEq),
|
||||
("..", Punct::DotDot),
|
||||
("::", Punct::ColonColon),
|
||||
("@", Punct::At),
|
||||
("{", Punct::LBrace),
|
||||
("}", Punct::RBrace),
|
||||
("(", Punct::LParen),
|
||||
@@ -341,6 +350,8 @@ pub enum TokenKind {
|
||||
},
|
||||
/// A preprocessor line.
|
||||
Directive(Directive),
|
||||
/// An XML or XMLList literal; the tokens of its embedded expressions follow it.
|
||||
XmlLiteral,
|
||||
}
|
||||
|
||||
/// A token, with where it is and the facts the grammar's rules need about it.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -129,10 +129,17 @@ impl Headless {
|
||||
fn exec(&mut self, id: &str, params: &Value) -> Result<Value, String> {
|
||||
// A key the command's description doesn't name is an error, not a default (#1442).
|
||||
match HOST_COMMANDS.iter().find(|c| c.0 == id) {
|
||||
Some((_, _, doc)) => vectorcraft_engine::check_keys(id, doc, params),
|
||||
None => self.session.check_params(id, params),
|
||||
Some((_, _, doc)) => vectorcraft_engine::check_keys(id, doc, params).map_err(|e| e.to_string())?,
|
||||
None if vectorcraft_engine::find_command(id).is_some() => {
|
||||
self.session.check_params(id, params).map_err(|e| e.to_string())?;
|
||||
}
|
||||
None if crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| *cid == id) => {
|
||||
return Err(format!(
|
||||
"`{id}` is a desktop UI command (`ui: true`); start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`"
|
||||
));
|
||||
}
|
||||
None => self.session.check_params(id, params).map_err(|e| e.to_string())?,
|
||||
}
|
||||
.map_err(|e| e.to_string())?;
|
||||
match id {
|
||||
"file.open" => self.open(params),
|
||||
"file.save" => self.save(params),
|
||||
@@ -146,9 +153,30 @@ impl Headless {
|
||||
|
||||
fn commands(&self) -> Value {
|
||||
let mut v: Vec<Value> = self.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect();
|
||||
let mut seen: std::collections::HashSet<String> = v.iter().filter_map(|c| c.get("id").and_then(Value::as_str).map(str::to_owned)).collect();
|
||||
for (id, label, params) in HOST_COMMANDS {
|
||||
if !seen.insert((*id).to_owned()) {
|
||||
continue;
|
||||
}
|
||||
v.push(json!({"id": id, "label": label, "menu": [], "shortcut": null, "params": params, "enabled": true, "host": true}));
|
||||
}
|
||||
// Desktop menu commands (`UI_COMMANDS`): listed for discovery with `ui: true`. Running one
|
||||
// that only the desktop app implements still needs `--connect` (see `exec`).
|
||||
for (id, label, shortcut, params) in crate::ui_catalog::UI_COMMANDS {
|
||||
if !seen.insert((*id).to_owned()) {
|
||||
continue;
|
||||
}
|
||||
let sc = if shortcut.is_empty() { Value::Null } else { json!(shortcut) };
|
||||
v.push(json!({
|
||||
"id": id,
|
||||
"label": label,
|
||||
"menu": [],
|
||||
"shortcut": sc,
|
||||
"params": params,
|
||||
"enabled": true,
|
||||
"ui": true,
|
||||
}));
|
||||
}
|
||||
Value::Array(v)
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ mod prompts;
|
||||
mod resources;
|
||||
mod server;
|
||||
mod tools;
|
||||
mod ui_catalog;
|
||||
|
||||
pub use backend::{Backend, Remote};
|
||||
pub use headless::Headless;
|
||||
|
||||
@@ -365,6 +365,110 @@ Method:
|
||||
Live effects are kept on export (geometry baked; shadows, glows and blur become SVG filters),
|
||||
and text stays text unless you pass outlineText.",
|
||||
},
|
||||
PromptDef {
|
||||
name: "check-spelling",
|
||||
title: "Check spelling",
|
||||
description: "Run text.spelling.check on the selection or document, then apply suggestions or dictionary changes.",
|
||||
arguments: &[
|
||||
PromptArg {
|
||||
name: "scope",
|
||||
description: "What to check",
|
||||
required: false,
|
||||
default: "the selection, or every story when nothing is selected",
|
||||
values: Values::Fixed(&[
|
||||
"the selection, or every story when nothing is selected",
|
||||
"the active story only",
|
||||
"every story in the document",
|
||||
]),
|
||||
},
|
||||
PromptArg {
|
||||
name: "action",
|
||||
description: "What to do with each unknown word",
|
||||
required: false,
|
||||
default: "list suggestions and ask before changing",
|
||||
values: Values::Fixed(&[
|
||||
"list suggestions and ask before changing",
|
||||
"apply the first suggestion for each word",
|
||||
"add unknown words to the custom dictionary",
|
||||
"ignore all for this document",
|
||||
]),
|
||||
},
|
||||
],
|
||||
text: "\
|
||||
Check spelling in VectorCraft for {scope}, then {action}.
|
||||
|
||||
Method:
|
||||
1. inspect_document to see the selection and type objects.
|
||||
2. run_command text.spelling.check (and text.spelling.suggest for each unknown word). Offsets are
|
||||
byte ranges for text.editRange / text.spelling.changeWord.
|
||||
3. For a fix, text.spelling.changeWord; for the custom dictionary, text.spelling.addWord /
|
||||
removeWord / dictionary; for this document only, text.spelling.ignoreAll.
|
||||
4. Prefer those commands over inventing replacements. screenshot if the layout may reflow.
|
||||
|
||||
Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); use --connect for the underlines.",
|
||||
},
|
||||
PromptDef {
|
||||
name: "variables-bind",
|
||||
title: "Bind variables",
|
||||
description: "Define text, visibility or image variables, bind them to art, and load or save a variable library.",
|
||||
arguments: &[
|
||||
PromptArg {
|
||||
name: "kind",
|
||||
description: "Which variable kinds to set up",
|
||||
required: false,
|
||||
default: "text",
|
||||
values: Values::Fixed(&["text", "visibility", "image", "graph", "mixed"]),
|
||||
},
|
||||
PromptArg {
|
||||
name: "source",
|
||||
description: "Where the data comes from",
|
||||
required: false,
|
||||
default: "define variables on the selection by hand",
|
||||
values: Values::Fixed(&["define variables on the selection by hand", "import a CSV or TSV data set", "load a variable library XML"]),
|
||||
},
|
||||
],
|
||||
text: "\
|
||||
Set up {kind} variables in VectorCraft from {source}.
|
||||
|
||||
Method:
|
||||
1. inspect_document and variable.list (or the Variables panel commands) to see what exists.
|
||||
2. variable.define / variable.bind for text, visibility, image or graph bindings; one text
|
||||
variable per type object.
|
||||
3. For CSV/TSV, dataset.import; for a library file, variable.loadLibrary / variable.saveLibrary.
|
||||
4. Switch data sets with dataset.apply and verify with inspect_document / screenshot.
|
||||
5. Prefer run_command over inventing panel clicks. Undo covers each binding step.",
|
||||
},
|
||||
PromptDef {
|
||||
name: "path-tools",
|
||||
title: "Path Tools add-on",
|
||||
description: "Use addon.pathtools.* commands (and addon.path.* live effects) to edit path geometry.",
|
||||
arguments: &[PromptArg {
|
||||
name: "task",
|
||||
description: "What to do to the selection",
|
||||
required: true,
|
||||
default: "",
|
||||
values: Values::Fixed(&[
|
||||
"extend open ends",
|
||||
"close paths",
|
||||
"add anchors along curves",
|
||||
"simplify anchors",
|
||||
"split at anchors",
|
||||
"expand dashes to geometry",
|
||||
"create a parametric shape",
|
||||
]),
|
||||
}],
|
||||
text: "\
|
||||
Perform this Path Tools task in VectorCraft: {task}.
|
||||
|
||||
Method:
|
||||
1. command_list with filter \"addon.pathtools\" for the command ids (extend, close, addPoints,
|
||||
simplify, crossings, shape.create, …). Those are commands.
|
||||
2. Live Path Effects keep the effect ids addon.path.* (dashes, addAnchors, extend, close,
|
||||
smooth, retract, reverse, simplify, split). Apply them with apply_effect / effect.apply;
|
||||
they are not command ids.
|
||||
3. inspect_document the selection, run the command or effect, then screenshot.
|
||||
4. Expand Appearance (effect.expandAppearance) only when the brief needs baked geometry.",
|
||||
},
|
||||
];
|
||||
|
||||
/// The message body as a client should receive it.
|
||||
|
||||
@@ -209,9 +209,77 @@ fn tool_schemas_are_valid() {
|
||||
"export",
|
||||
"undo",
|
||||
"redo",
|
||||
"command_list",
|
||||
"command_run",
|
||||
"command_batch",
|
||||
"doc_inspect",
|
||||
"render_preview",
|
||||
"ui_inspect",
|
||||
"ui_screenshot",
|
||||
"type_text",
|
||||
"answer_dialog",
|
||||
"add_text",
|
||||
"apply_effect",
|
||||
"pathfinder",
|
||||
"transform",
|
||||
"create_graph",
|
||||
"text_wrap",
|
||||
] {
|
||||
assert!(names.contains(want), "missing tool {want}");
|
||||
}
|
||||
assert_eq!(tools.len(), 33, "parity docs and #6460 expect 33 MCP tools");
|
||||
}
|
||||
|
||||
/// Headless `command_list` must expose engine commands that a stale release CLI used to omit (#6460).
|
||||
#[test]
|
||||
fn headless_command_list_includes_post_022_engine_commands() {
|
||||
let mut s = server();
|
||||
rpc(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION}));
|
||||
s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
|
||||
let want = [
|
||||
"actionSet.read",
|
||||
"engine.apiReference",
|
||||
"script.run",
|
||||
"script.stop",
|
||||
"text.spelling.check",
|
||||
"document.move",
|
||||
"document.compare",
|
||||
"edit.newDocumentFromState",
|
||||
];
|
||||
for (n, id) in want.iter().enumerate() {
|
||||
let r = call(&mut s, 10 + n as u64, "command_list", json!({"filter": id, "brief": true}));
|
||||
assert_eq!(r["isError"], false, "{id}: {r}");
|
||||
let list: Value = serde_json::from_str(&text_of(&r)).unwrap();
|
||||
assert!(list.as_array().unwrap().iter().any(|c| c["id"] == *id), "missing {id} in {list}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Headless `command_list` lists desktop UI commands with `ui: true` (#6460).
|
||||
#[test]
|
||||
fn headless_command_list_includes_ui_commands() {
|
||||
let mut s = server();
|
||||
rpc(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION}));
|
||||
s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
|
||||
let want = [
|
||||
"addon.arrange.zoomSelection",
|
||||
"file.newDialog",
|
||||
"view.fitArtboard",
|
||||
"view.rotateReset",
|
||||
"app.quit",
|
||||
"window.arrange.tile",
|
||||
"align.horizontalLeft",
|
||||
"ui.action.play",
|
||||
];
|
||||
for (n, id) in want.iter().enumerate() {
|
||||
let r = call(&mut s, 20 + n as u64, "command_list", json!({"filter": id, "brief": true}));
|
||||
assert_eq!(r["isError"], false, "{id}: {r}");
|
||||
let list: Value = serde_json::from_str(&text_of(&r)).unwrap();
|
||||
let entry = list.as_array().unwrap().iter().find(|c| c["id"] == *id).unwrap_or_else(|| panic!("missing {id} in {list}"));
|
||||
assert_eq!(entry["ui"], true, "{entry}");
|
||||
}
|
||||
let r = call(&mut s, 40, "command_run", json!({"id": "view.fitArtboard", "params": {}}));
|
||||
assert_eq!(r["isError"], true, "{r}");
|
||||
assert!(text_of(&r).contains("--connect"), "{r}");
|
||||
}
|
||||
|
||||
// ---------- headless end-to-end ----------
|
||||
|
||||
@@ -98,7 +98,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"command_list",
|
||||
"List commands",
|
||||
"Discover command ids, labels, parameter descriptions and enabled state. A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}.",
|
||||
"Discover command ids, labels, parameter descriptions and enabled state. Lists engine and plug-in commands, and desktop UI menu commands (ui: true; running a UI-only id headless needs --connect). A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}. Effect ids (effect.list) are not command ids.",
|
||||
obj(
|
||||
json!({"filter": string("Case-insensitive id, label or menu substring"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabled_only": {"type":"boolean"}, "brief": {"type":"boolean", "description": BRIEF}}),
|
||||
&[],
|
||||
@@ -156,7 +156,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"list_commands",
|
||||
"List commands",
|
||||
"List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Every editing action is a command; run any of them with run_command. Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only.",
|
||||
"List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Includes engine commands and desktop UI menu commands (ui: true; a UI-only id run headless needs --connect). Every editing action is a command; run any of them with run_command (or invoke_menu for a menu path). Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only. Effect ids (effect.list) are not command ids.",
|
||||
obj(
|
||||
json!({"filter": string("Case-insensitive substring matched against id, label and menu path (e.g. \"align\", \"Object\")"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabledOnly": {"type": "boolean", "description": "Only commands that can run right now"}, "brief": {"type": "boolean", "description": BRIEF}}),
|
||||
&[],
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -84,11 +84,14 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData {
|
||||
PathData::new(out)
|
||||
}
|
||||
|
||||
/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it.
|
||||
/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed subpath
|
||||
/// whose refit is one segment, or two lines that enclose no area, is refitted in two parts, cut at
|
||||
/// the point farthest from its start, or in three when two still give that; one of a single segment
|
||||
/// stays as it is.
|
||||
fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option<SubPath> {
|
||||
let mut segs = subpath_segs(sp);
|
||||
let n = segs.len();
|
||||
if n == 0 {
|
||||
if n == 0 || sp.closed && n < 2 {
|
||||
return Some(sp.clone());
|
||||
}
|
||||
if sp.closed {
|
||||
@@ -101,7 +104,34 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option<SubPath> {
|
||||
// along its chord, and `no_worse` can return the original subpath, so the start can keep a kink.
|
||||
let across = if sp.closed && opts.smooth > 0.0 { unit(end_tangent(&segs[n - 1].c) + start_tangent(&segs[0].c)) } else { None };
|
||||
let across = across.filter(|_| (0..n).all(|i| turn_deg(&segs[(i + n - 1) % n], &segs[i]) <= opts.corner_angle_deg));
|
||||
let result = simplify_run_within(&segs, opts, MAX_RUN_SAMPLES, across);
|
||||
let mut result = simplify_run_within(&segs, opts, MAX_RUN_SAMPLES, across);
|
||||
let flat = |r: &[Seg]| r.len() < 2 || r.len() == 2 && r.iter().all(|s| s.line);
|
||||
if sp.closed && flat(&result) {
|
||||
// Each segment in two, and the loop cut where they meet: first at the point farthest from its
|
||||
// start, then also at the point farthest from the line between those two.
|
||||
let halves: Vec<Seg> = segs
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
let (a, b) = s.c.subdivide();
|
||||
[Seg { c: a, line: s.line }, Seg { c: b, line: s.line }]
|
||||
})
|
||||
.collect();
|
||||
let m = halves.len();
|
||||
let at = |i: usize| halves[i].c.p0;
|
||||
let farthest = |from: &dyn Fn(Point) -> f64, skip: usize| (1..m).filter(|&i| i != skip).max_by(|&a, &b| from(at(a)).total_cmp(&from(at(b))));
|
||||
let p0 = at(0);
|
||||
let j = farthest(&|p| p.distance(p0), 0).unwrap_or(m / 2);
|
||||
let chord = at(j) - p0;
|
||||
let off_chord = |p: Point| if chord.hypot2() > 0.0 { chord.cross(p - p0).abs() } else { p.distance(p0) };
|
||||
let k = farthest(&off_chord, j).unwrap_or(m / 2);
|
||||
let refit = |cuts: &[usize]| -> Vec<Seg> {
|
||||
cuts.windows(2).flat_map(|w| simplify_run_within(&halves[w[0]..w[1]], opts, MAX_RUN_SAMPLES / 3, None)).collect()
|
||||
};
|
||||
result = refit(&[0, j, m]);
|
||||
if flat(&result) && k != j {
|
||||
result = refit(&[0, j.min(k), j.max(k), m]);
|
||||
}
|
||||
}
|
||||
let s = segs_to_subpath(&result, sp.closed)?;
|
||||
Some(if opts.straight_lines { s } else { no_worse(sp, s) })
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::f64::consts::PI;
|
||||
|
||||
use kurbo::{ParamCurve, Point, Rect, Shape as _};
|
||||
use vectorcraft_geom::{AnchorKind, FillRule, PathData, SubPath};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, FillRule, PathData, SubPath};
|
||||
use vectorcraft_pathops::*;
|
||||
|
||||
const NZ: FillRule = FillRule::NonZero;
|
||||
@@ -408,6 +408,35 @@ fn simplify_straight_lines_option() {
|
||||
assert!(max_deviation(&c, &s) <= 1.0 + 1e-6);
|
||||
}
|
||||
|
||||
/// A closed subpath whose refit is one curve stays a closed subpath that encloses an area, in a
|
||||
/// compound path and on its own, with curves and with Convert to Straight Lines.
|
||||
#[test]
|
||||
fn simplify_keeps_a_closed_subpath_that_refits_to_one_curve() {
|
||||
let small = |cx: f64, cy: f64| circle(cx, cy, 2.0).subpaths.remove(0);
|
||||
let square = rect(0.0, 0.0, 1000.0, 1000.0).subpaths.remove(0);
|
||||
let compound = PathData::new(vec![square, small(500.0, 500.0)]);
|
||||
let lone = PathData::single(small(0.0, 0.0));
|
||||
// A straight edge and a curve that bows 2.25 pt from it.
|
||||
let bow = PathData::single(SubPath::new(
|
||||
vec![
|
||||
Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 3.0), Point::new(0.0, 0.0)),
|
||||
Anchor::with_handles(Point::new(100.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 3.0)),
|
||||
],
|
||||
true,
|
||||
));
|
||||
for straight_lines in [false, true] {
|
||||
for tolerance in [4.0, 10.0, 32.0] {
|
||||
let opts = SimplifyOptions { tolerance, straight_lines, ..Default::default() };
|
||||
for path in [&compound, &lone, &bow] {
|
||||
let s = simplify_with(path, &opts);
|
||||
assert_eq!(s.subpaths.len(), path.subpaths.len(), "{tolerance} pt, straight lines {straight_lines}: {s:?}");
|
||||
assert!(s.subpaths.iter().all(|sp| sp.closed && sp.anchors.len() >= 2 && sp.area().abs() > 1.0), "{s:?}");
|
||||
assert!(max_deviation(path, &s) <= tolerance + 1e-6, "{tolerance} pt: {}", max_deviation(path, &s));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Simplify slider's levels: 1 pt at 50, doubled for every 10 levels down and halved for every
|
||||
/// 10 up; Auto-Simplify takes the lowest level whose tolerance is at most 1/400 of the size, and
|
||||
/// level 100 for a size under 12.5 pt.
|
||||
|
||||
@@ -156,8 +156,6 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
} else if n == catalog::DOLLAR_EVAL_FILE {
|
||||
self.acc.feature(FeatureId::DollarEvalFile, line);
|
||||
self.acc.outside(OutsideId::UnseenCode, line, None);
|
||||
} else if n == catalog::LOCALIZE {
|
||||
self.acc.feature(FeatureId::Localize, line);
|
||||
} else {
|
||||
self.acc.feature(FeatureId::Dollar, line);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ pub(crate) const DOLLAR_EVAL_FILE: &str = "evalFile";
|
||||
// https://extendscript.docsforadobe.dev/extendscript-tools-features/user-notification-dialogs/
|
||||
pub(crate) const NOTIFY: &[&str] = &["alert", "confirm", "prompt"];
|
||||
|
||||
// The global function. `$.localize` is a property of `$` (the Dollar object page above), so it is
|
||||
// a `$` member:
|
||||
// https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/
|
||||
pub(crate) const LOCALIZE: &str = "localize";
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ const FEATURE_CASES: &[(&str, &str, &str)] = &[
|
||||
("directive.target", " //@target acme", "x(); //@target acme"),
|
||||
("directive.targetengine", "#targetengine session", "var targetengine = 'session';"),
|
||||
("dollar", "$.writeln('hi');", "log.writeln('hi');"),
|
||||
("dollar", "$.localize = true;", "obj.localize = true;"),
|
||||
("dollar.env", "var home = $.getenv('HOME');", "var home = env.getenv('HOME');"),
|
||||
("dollar.evalFile", "$.evalFile(f);", "loader.evalFile(f);"),
|
||||
("dynamicCode", "eval(code);", "safe.eval(code);"),
|
||||
@@ -68,7 +69,6 @@ const FEATURE_CASES: &[(&str, &str, &str)] = &[
|
||||
("file.write", "Folder.temp.remove();", "cache.temp.remove();"),
|
||||
("hostCheck", "if (parseInt(app.version) < 20) {}", "if (parseInt(appVersion) < 20) {}"),
|
||||
("localize", "var s = localize(text);", "var s = text.localize;"),
|
||||
("localize", "var s = $.localize(text);", "var s = obj.localize(text);"),
|
||||
("menuCommand", "app.executeMenuCommand('acmecopyall');", "executeMenuCommand('acmecopyall');"),
|
||||
("notify", "alert('done');", "panel.alert('done');"),
|
||||
("notify", "if (confirm('Go?')) {}", "function confirm(m) {}"),
|
||||
@@ -103,6 +103,15 @@ fn each_feature_is_found_where_it_is_and_nowhere_else() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dollar_objects_localize_property_is_not_the_global_localize_function() {
|
||||
for src in ["$.localize = true;", "if ($.localize) {}", "var s = $.localize(text);"] {
|
||||
let r = report(src);
|
||||
assert!(feature(&r, "dollar").is_some(), "{src}: {:?}", r.features);
|
||||
assert!(feature(&r, "localize").is_none(), "{src}: {:?}", r.features);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn features_are_listed_in_alphabetical_order_of_their_ids() {
|
||||
let ids: Vec<&str> = FeatureId::ALL.iter().map(|f| f.id()).collect();
|
||||
|
||||
@@ -782,8 +782,10 @@ impl Tool for GestureTool {
|
||||
};
|
||||
let color = if self.id == "eraser" { [0x80, 0x80, 0x80] } else { FEEDBACK };
|
||||
// A tip that is not round shows the outline of the area it covers, each step of the drag
|
||||
// as wide as the pen pressed there with Size set to Pressure.
|
||||
if matches!(self.id, "eraser" | "blobBrush") && self.roundness < 100.0 && !self.smoothing {
|
||||
// as wide as the pen pressed there with Size set to Pressure. So does a round Blob Brush
|
||||
// tip: a line as wide as the brush would end square, where the stroke it adds is round at
|
||||
// both ends (#4343).
|
||||
if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || self.id == "blobBrush") && !self.smoothing {
|
||||
let area = |pts: &[Point], size| {
|
||||
if self.id == "blobBrush" {
|
||||
blob_area(pts, size, self.angle, self.roundness)
|
||||
|
||||
@@ -382,6 +382,36 @@ fn blob_brush_drag_shows_scrub_length_measurement_labels() {
|
||||
assert!(!quiet.overlays(&off).iter().any(|o| matches!(o, Overlay::Measure { .. })));
|
||||
}
|
||||
|
||||
/// #4343: while it is dragged, a round Blob Brush shows the outline of the area `path.blob` adds,
|
||||
/// which reaches half the brush beyond the ends of the stroke (round tips), not a line as wide as
|
||||
/// the brush that ends square at them.
|
||||
#[test]
|
||||
fn blob_brush_preview_is_the_outline_of_the_area_with_round_tips() {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = GestureTool::new("blobBrush");
|
||||
t.size = 20.0;
|
||||
assert_eq!(t.roundness, 100.0, "a round tip by default");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 300.0));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 300.0));
|
||||
let outlines: Vec<_> =
|
||||
t.overlays(&cx).into_iter().filter_map(|o| if let Overlay::Path { path, width, .. } = o { Some((path, width)) } else { None }).collect();
|
||||
assert!(outlines.iter().all(|(_, width)| f64::from(*width) < t.size / 2.0), "no line as wide as the brush: {outlines:?}");
|
||||
// The stroke's outline is the widest one (the tip at the pointer is another).
|
||||
let Some((path, _)) = outlines.iter().max_by(|a, b| a.0.bounding_box().width().total_cmp(&b.0.bounding_box().width())) else {
|
||||
panic!("no outline")
|
||||
};
|
||||
let b = path.bounding_box();
|
||||
assert!((b.x0 - 40.0).abs() < 0.5 && (b.x1 - 160.0).abs() < 0.5, "round tips reach half the size past the ends: {b:?}");
|
||||
assert!((b.y0 - 290.0).abs() < 0.5 && (b.y1 - 310.0).abs() < 0.5, "{b:?}");
|
||||
// Round, not square: the corner of the box a square-ended line would fill is outside the area.
|
||||
assert!(!path.contains(vectorcraft_geom::Point::new(41.0, 291.0)));
|
||||
assert!(path.contains(vectorcraft_geom::Point::new(45.0, 300.0)));
|
||||
}
|
||||
|
||||
/// The Blob Brush has Keep selected and Merge only with selection, both off by default, and its
|
||||
/// stroke sends both.
|
||||
#[test]
|
||||
|
||||
@@ -1194,6 +1194,47 @@ impl Targets {
|
||||
(d, ov, held.contains(&true))
|
||||
}
|
||||
|
||||
/// [`Self::snap_moved_to_rulers`] for a selection a move Shift keeps to its line (through the
|
||||
/// grabbed point `p`, along `dir`), its bounds now `r`: the edge or centre of `r` that a ruler
|
||||
/// guide runs past within `tol` goes onto it by sliding along the line, the way needing the
|
||||
/// shortest slide winning and at most twice `tol` (a line nearly parallel to a guide would
|
||||
/// carry the selection far to meet it). Returns the shift along the line and the guides.
|
||||
pub(crate) fn snap_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64) -> (Vec2, Vec<Overlay>) {
|
||||
let len = dir.hypot();
|
||||
if !len.is_finite() || len <= 1e-9 {
|
||||
return (Vec2::ZERO, vec![]);
|
||||
}
|
||||
let u = dir / len;
|
||||
// The way along the line, where the guide is and where it starts, and whether it is upright.
|
||||
let mut best: Option<(f64, f64, Point, bool)> = None;
|
||||
for (vertical, c) in [(true, u.x), (false, u.y)] {
|
||||
if c.abs() <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let vs = if vertical { [r.x0, r.center().x, r.x1] } else { [r.y0, r.center().y, r.y1] };
|
||||
let (mid, half) =
|
||||
if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) };
|
||||
for (t, from, _) in self.rulers.iter().filter(|g| g.vertical == vertical).filter_map(|g| g.line_at(mid, tol + half)) {
|
||||
for v in vs {
|
||||
let s = (t - v) / c;
|
||||
if (t - v).abs() <= tol && s.abs() <= 2.0 * tol && best.is_none_or(|b| s.abs() < b.0.abs()) {
|
||||
best = Some((s, t, from, vertical));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((s, t, from, vertical)) = best else { return (Vec2::ZERO, vec![]) };
|
||||
let moved = r + u * s;
|
||||
let line = if vertical {
|
||||
self.line(Point::new(t, from.y.min(moved.y0)), Point::new(t, from.y.max(moved.y1)))
|
||||
} else {
|
||||
self.line(Point::new(from.x.min(moved.x0), t), Point::new(from.x.max(moved.x1), t))
|
||||
};
|
||||
let mut ov: Vec<Overlay> = line.into_iter().collect();
|
||||
ov.extend(self.label(p + u * s, "align"));
|
||||
(u * s, ov)
|
||||
}
|
||||
|
||||
/// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for
|
||||
/// dragging `handle` of the box `bx` (about the centre when `from_center`), in the box's own
|
||||
/// frame, and so is the result. The handle lands on an anchor or centre within `tol` on the page
|
||||
|
||||
@@ -22,6 +22,25 @@ fn snaps_to_anchor_and_alignment() {
|
||||
assert_eq!(p.y, 200.0);
|
||||
}
|
||||
|
||||
/// #4312: a Shift move slides the selection along its line onto a ruler guide, but not far to
|
||||
/// meet one a nearly parallel line only reaches a long way off.
|
||||
#[test]
|
||||
fn a_slide_along_a_line_lands_the_bounds_on_a_ruler_guide_within_reach() {
|
||||
let t = Targets { rulers: vec![Ruler { vertical: true, pos: 300.0, span: None }], ..Targets::default() };
|
||||
let r = Rect::new(248.0, 10.0, 298.0, 40.0);
|
||||
let p = Point::new(270.0, 25.0);
|
||||
// Level: the right edge is 2 short of the guide, which is the way along the line.
|
||||
assert_eq!(t.snap_moved_along_to_rulers(p, r, Vec2::new(1.0, 0.0), 4.0).0, Vec2::new(2.0, 0.0));
|
||||
// On the diagonal it is 2.8 along.
|
||||
let (d, ov) = t.snap_moved_along_to_rulers(p, r, Vec2::new(1.0, 1.0), 4.0);
|
||||
assert!((d - Vec2::new(2.0, 2.0)).hypot() < 1e-9 && !ov.is_empty(), "{d:?}");
|
||||
// Nearly upright, it would take about 118 along the line to meet the guide.
|
||||
assert_eq!(t.snap_moved_along_to_rulers(p, r, Vec2::new(0.017, 1.0), 4.0).0, Vec2::ZERO);
|
||||
// A guide of an artboard needs the selection to run past it.
|
||||
let bounded = Targets { rulers: vec![Ruler { vertical: true, pos: 300.0, span: Some((100.0, 200.0)) }], ..Targets::default() };
|
||||
assert_eq!(bounded.snap_moved_along_to_rulers(p, r, Vec2::new(1.0, 0.0), 4.0).0, Vec2::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_snap_aligns_edges() {
|
||||
let (d, id) = doc_with_rect();
|
||||
|
||||
@@ -368,6 +368,14 @@ impl MoveSnap {
|
||||
if q != start + d {
|
||||
d = q - start;
|
||||
guides = ov;
|
||||
} else if guides.is_empty()
|
||||
&& let Some(b) = self.bounds
|
||||
{
|
||||
// Nothing else lined up: the bounds slide along the line onto a ruler guide, as
|
||||
// they do without Shift (#4312).
|
||||
let (adj, ov) = t.snap_moved_along_to_rulers(start + d, b + d, u, cx.tol(cx.snap_tolerance));
|
||||
d += adj;
|
||||
guides = ov;
|
||||
}
|
||||
}
|
||||
if cx.snap_to_pixel
|
||||
|
||||
@@ -770,6 +770,30 @@ fn a_move_snaps_the_grabbed_point_to_a_ruler_guide_with_smart_guides_on() {
|
||||
assert_eq!(dx(&ToolContext { snap_to_point: false, ..cx(&d, &s, &p) }, 172.0), 22.0);
|
||||
}
|
||||
|
||||
/// #4312: a Shift move keeps to its line while its edges and centre land on a ruler guide, as a
|
||||
/// move without Shift does (#5746).
|
||||
#[test]
|
||||
fn a_shift_move_lands_the_edges_on_a_ruler_guide() {
|
||||
let (mut d, id) = doc_with_rect();
|
||||
d.guides = vec![vectorcraft_doc::Guide::new(true, 333.0)];
|
||||
let mut s = Selection::default();
|
||||
s.add(id);
|
||||
let p = paint();
|
||||
let c = cx(&d, &s, &p);
|
||||
// Level; the left edge (100) would end 2 short of the guide, the pointer far from it.
|
||||
let (m, _) = shift_moved(&c, (150.0 + 231.0, 150.0));
|
||||
assert!(moved_by(m, (233.0, 0.0)), "{m:?}");
|
||||
// The right edge, 1 past the guide.
|
||||
let (m, _) = shift_moved(&c, (150.0 + 134.0, 150.0));
|
||||
assert!(moved_by(m, (133.0, 0.0)), "{m:?}");
|
||||
// Out of reach, or with Snap to Point off, the move stays as dragged.
|
||||
let (m, _) = shift_moved(&c, (150.0 + 221.0, 150.0));
|
||||
assert!(moved_by(m, (221.0, 0.0)), "{m:?}");
|
||||
let off = ToolContext { snap_to_point: false, ..cx(&d, &s, &p) };
|
||||
let (m, _) = shift_moved(&off, (150.0 + 231.0, 150.0));
|
||||
assert!(moved_by(m, (231.0, 0.0)), "{m:?}");
|
||||
}
|
||||
|
||||
/// Alt pressed during a move makes a copy, which snaps to the original it leaves behind (as
|
||||
/// gathered before the previews moved it); released, the move doesn't.
|
||||
#[test]
|
||||
@@ -2426,3 +2450,30 @@ fn a_ruler_guide_under_the_centre_point_keeps_the_pointer() {
|
||||
let drag = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 150.0));
|
||||
assert!(drag.iter().any(|a| matches!(a, Action::Preview(cmd, _) if cmd == "guide.move")), "the guide drags: {down:?} {drag:?}");
|
||||
}
|
||||
|
||||
/// #6437: in Outline view, where an image is drawn as its frame, a click inside it on the edge of
|
||||
/// a path behind selects that path, with the image selected or not. In Preview the image takes
|
||||
/// the click.
|
||||
#[test]
|
||||
fn outline_view_click_through_an_image_selects_the_path_behind() {
|
||||
use vectorcraft_doc::{Appearance, Document, ImageObject, Node, NodeKind};
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let layer = d.layers[0].id;
|
||||
let (back, image) = (d.alloc_id(), d.alloc_id());
|
||||
let square = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0));
|
||||
d.insert(Some(layer), 0, Node::path(back, square, Appearance::default_art())).unwrap();
|
||||
let xf = vectorcraft_geom::Affine::translate((150.0, 150.0));
|
||||
let im = ImageObject { key: "k".into(), width: 100, height: 100, xf, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(layer), 1, Node::new(image, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
let selects = |a: &[Action], id: NodeId| a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([id.0])));
|
||||
let p = paint();
|
||||
for picked in [vec![], vec![image]] {
|
||||
let mut s = Selection::default();
|
||||
s.set(picked.clone());
|
||||
let outline = ToolContext { outline: true, ..cx(&d, &s, &p) };
|
||||
let a = SelectionTool::default().pointer(&outline, &ev(PointerKind::Down, 200.0, 180.0));
|
||||
assert!(selects(&a, back), "outline, {picked:?} selected: {a:?}");
|
||||
let a = SelectionTool::default().pointer(&cx(&d, &s, &p), &ev(PointerKind::Down, 200.0, 180.0));
|
||||
assert!(!selects(&a, back), "preview, {picked:?} selected: {a:?}");
|
||||
}
|
||||
}
|
||||
@@ -343,7 +343,11 @@ impl VectorcraftApp {
|
||||
crate::script_runs::poll(self);
|
||||
crate::scripts_menu::poll(self, ctx);
|
||||
if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() {
|
||||
ctx.request_repaint();
|
||||
// A script in `$.sleep` goes on when its time is up; until then the app can idle.
|
||||
match self.session.script_sleep_left() {
|
||||
Some(left) => ctx.request_repaint_after(left),
|
||||
None => ctx.request_repaint(),
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.tick_link_updates(ctx, now);
|
||||
|
||||
@@ -136,7 +136,7 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option<usize>, room: f32)
|
||||
/// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`]
|
||||
/// above or below the strip floats its view in a window under the pointer; one dragged along the
|
||||
/// strip moves its document among the others (`document.move`, #5663), a line marking where it
|
||||
/// will go.
|
||||
/// will go. A middle-click on a tab closes it, as its × does (#6506).
|
||||
pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
/// The width of the » button.
|
||||
const MORE: f32 = 30.0;
|
||||
@@ -200,7 +200,9 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
icons::paint(ui, "x", xr, if xresp.hovered() { t.text_strong } else { t.text });
|
||||
ui.painter().galley(egui::pos2(title_left, r.center().y - galley.size().y / 2.0), galley.clone(), t.text);
|
||||
hovering_art |= crate::document_drag::hover_tab(app, &resp, win, xr.expand(3.0));
|
||||
if xresp.clicked() {
|
||||
// A middle-click anywhere on the tab closes it as the × does (#6506), so closing a
|
||||
// modified document's last view still asks to save first.
|
||||
if xresp.clicked() || resp.middle_clicked() || xresp.middle_clicked() {
|
||||
close = Some(win);
|
||||
} else if resp.clicked() {
|
||||
activate = Some(win);
|
||||
|
||||
@@ -505,6 +505,65 @@ fn a_tabs_close_box_sits_where_the_platform_puts_it() {
|
||||
assert!(super::CLOSE_BEFORE_TITLE == cfg!(target_os = "macos"));
|
||||
}
|
||||
|
||||
/// A middle-click on a document tab closes it as the × does (#6506): a saved document closes, and
|
||||
/// a modified one asks to save first instead of losing its changes.
|
||||
#[test]
|
||||
fn a_middle_click_on_a_tab_closes_it_as_the_close_box_does() {
|
||||
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
for _ in 0..3 {
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
}
|
||||
// The second document has unsaved changes; the third stays the current one.
|
||||
app.session.set_active(1);
|
||||
app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.session.set_active(2);
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 200.0));
|
||||
let frame = |app: &mut crate::VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::doc_tabs(app, ui));
|
||||
out.textures_delta.clear();
|
||||
let mut titles = vec![];
|
||||
for c in &out.shapes {
|
||||
if let egui::Shape::Text(t) = &c.shape
|
||||
&& t.visual_bounding_rect().width() > 30.0
|
||||
{
|
||||
titles.push(t.visual_bounding_rect());
|
||||
}
|
||||
}
|
||||
titles.sort_by(|a, b| a.left().total_cmp(&b.left()));
|
||||
titles
|
||||
};
|
||||
let middle_click = |app: &mut crate::VectorcraftApp, at: egui::Pos2| {
|
||||
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed, modifiers: Default::default() };
|
||||
frame(app, vec![egui::Event::PointerMoved(at), press(true)]);
|
||||
frame(app, vec![press(false)])
|
||||
};
|
||||
let titles = frame(&mut app, vec![]);
|
||||
assert_eq!(titles.len(), 3, "{titles:?}");
|
||||
// The modified document's tab: the save prompt comes up and the document stays open.
|
||||
let titles = middle_click(&mut app, titles[1].center());
|
||||
assert_eq!(app.session.documents().len(), 3, "a modified document is not closed without asking");
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::unsaved::KIND), "a modified document asks first");
|
||||
app.ui.dialog = None;
|
||||
// The first, saved document's tab: it closes, and the others stay open.
|
||||
let uid = |app: &crate::VectorcraftApp, i: usize| app.session.documents()[i].uid;
|
||||
let (second, third) = (uid(&app, 1), uid(&app, 2));
|
||||
middle_click(&mut app, titles[0].center());
|
||||
assert_eq!(app.session.documents().len(), 2, "the middle-click closed the first document");
|
||||
assert_eq!((uid(&app, 0), uid(&app, 1)), (second, third));
|
||||
assert!(app.ui.dialog.is_none(), "a saved document closes without asking");
|
||||
// A middle-click on the × itself closes too: the third, saved document's.
|
||||
let titles = frame(&mut app, vec![]);
|
||||
assert_eq!(titles.len(), 2, "{titles:?}");
|
||||
let title = titles[1];
|
||||
let x = if super::CLOSE_BEFORE_TITLE { title.left() - 16.0 } else { title.right() + 20.0 };
|
||||
middle_click(&mut app, egui::pos2(x, title.center().y));
|
||||
assert_eq!(app.session.documents().len(), 1, "the middle-click on the × closed the third document");
|
||||
assert_eq!(uid(&app, 0), second);
|
||||
assert!(app.ui.dialog.is_none(), "a saved document closes without asking");
|
||||
}
|
||||
|
||||
/// One headless frame of the status bar; returns the artboard navigator's buttons, left to
|
||||
/// right: first, previous, next, last.
|
||||
fn navigator(app: &mut crate::VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<egui::Rect> {
|
||||
|
||||
@@ -249,8 +249,9 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
|
||||
// the layout.
|
||||
if let Some(fields) = ui.as_object_mut() {
|
||||
fields.remove("floating_panels");
|
||||
leave_out_unreadable_paths(fields);
|
||||
}
|
||||
json!({
|
||||
let mut inspected = json!({
|
||||
"scriptRunning": app.session.script_running(),
|
||||
"scriptReport": app.session.script_report(),
|
||||
"tool": app.session.tool_id(),
|
||||
@@ -294,8 +295,9 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
|
||||
"nativeMenuBar": app.services.native_menu.is_some(),
|
||||
// Saves and exports still being written in the background (Background Save / Export).
|
||||
"background": app.background.jobs.iter().filter(|j| !j.label.is_empty()).map(|j| j.label.as_str()).collect::<Vec<_>>(),
|
||||
// Documents still being read off the UI thread (File › Open, Open Recent): their paths.
|
||||
"opening": app.opening.pending.iter().map(|p| p.path.as_str()).collect::<Vec<_>>(),
|
||||
// Documents still being read off the UI thread (File › Open, Open Recent): their paths, without
|
||||
// the ones outside the read root.
|
||||
"opening": app.opening.pending.iter().map(|p| p.path.as_str()).filter(|p| readable(p)).collect::<Vec<_>>(),
|
||||
// Files still being read off the UI thread for Place (the Place dialog's OK, drops): their
|
||||
// names, in the order they are placed.
|
||||
"placing": app.placing.pending.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(),
|
||||
@@ -305,7 +307,173 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
|
||||
// A native file dialog open off the UI thread (`open`, `place`, `save`, `folder`), waiting
|
||||
// for the person at the computer: what asked for it runs again when it answers.
|
||||
"fileDialog": app.picks.waiting_kind(),
|
||||
})
|
||||
});
|
||||
let ids = unreadable_library_ids(app);
|
||||
hide_library_ids(&mut inspected, &ids);
|
||||
inspected
|
||||
}
|
||||
|
||||
/// The fields of the UI state, by their keys in `ui.inspect`'s `ui`, that hold panel ids: the panel
|
||||
/// popped out of the collapsed column, the docking layout, closed panels' places and groups, the panels
|
||||
/// shown as icons or collapsed, and the older floating panels' record.
|
||||
const PANEL_FIELDS: [&str; 7] =
|
||||
["open_panel", "docking", "docking_hidden", "docking_hidden_groups", "docking_icons", "docking_collapsed", "floating_panels"];
|
||||
|
||||
/// The ids of the loaded libraries (`loaded/<path>`) that the UI state refers to and whose file the
|
||||
/// request may not read, each with the id a reply shows instead: `loaded/<file name>`, as a library
|
||||
/// loaded without a path is named. The UI state refers to a library by its bare id in a library panel
|
||||
/// and the Color Guide's limit, and by a panel id (`library:<kind>:loaded/<path>`) in the fields of
|
||||
/// [`PANEL_FIELDS`] and the workspaces' layouts. Text the person types (a command palette query, a
|
||||
/// workspace's name) is not read. When another of those ids already shows that name, the next free one
|
||||
/// of `loaded/<file name> (2)`, `(3)` and so on is shown, in the sorted order of the full ids, so that
|
||||
/// two libraries stay two and `ui.inspect` and `ui.docking` show a library under the same id.
|
||||
fn unreadable_library_ids(app: &VectorcraftApp) -> Vec<(String, String)> {
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
let ui = serde_json::to_value(&app.ui).unwrap_or_default();
|
||||
for field in PANEL_FIELDS {
|
||||
collect_library_panel_ids(&ui[field], &mut ids);
|
||||
}
|
||||
for workspace in ["custom_workspaces", "workspace_changes"].iter().filter_map(|k| ui[k].as_array()).flatten() {
|
||||
for (_, layout) in workspace.as_object().into_iter().flatten().filter(|(k, _)| k.as_str() != "name") {
|
||||
collect_library_panel_ids(layout, &mut ids);
|
||||
}
|
||||
}
|
||||
collect_library_panel_ids(&json!(app.ui.transient_panel), &mut ids);
|
||||
for id in app.ui.library_panels.iter().map(|p| p.id.as_str()).chain([app.ui.color_guide_limit.as_str()]) {
|
||||
add_library_id(id, &mut ids);
|
||||
}
|
||||
let mut hidden = Vec::new();
|
||||
let mut taken = std::collections::BTreeSet::new();
|
||||
for id in ids {
|
||||
let path = &id["loaded/".len()..];
|
||||
let name = vectorcraft_engine::cmd::fileio::file_name(path);
|
||||
if name != path && !readable(path) {
|
||||
hidden.push((id, name));
|
||||
} else {
|
||||
taken.insert(id);
|
||||
}
|
||||
}
|
||||
let mut hidden = hidden
|
||||
.into_iter()
|
||||
.map(|(id, name)| {
|
||||
let mut shown = format!("loaded/{name}");
|
||||
let mut n = 2;
|
||||
while taken.contains(&shown) {
|
||||
shown = format!("loaded/{name} ({n})");
|
||||
n += 1;
|
||||
}
|
||||
taken.insert(shown.clone());
|
||||
(id, shown)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
// The longest first, so that an id that begins another one does not replace part of it.
|
||||
hidden.sort_by_key(|(id, _)| std::cmp::Reverse(id.len()));
|
||||
hidden
|
||||
}
|
||||
|
||||
/// Adds `id` to `ids` when it is a loaded library's id (`loaded/<path>`).
|
||||
fn add_library_id(id: &str, ids: &mut std::collections::BTreeSet<String>) {
|
||||
if id.len() > "loaded/".len() && id.starts_with("loaded/") {
|
||||
ids.insert(id.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to `ids` the loaded library id of every library panel id (`library:<kind>:loaded/<path>`)
|
||||
/// that `v` holds as a string or a key.
|
||||
fn collect_library_panel_ids(v: &Value, ids: &mut std::collections::BTreeSet<String>) {
|
||||
let add = |s: &str, ids: &mut std::collections::BTreeSet<String>| {
|
||||
if let Some((_, id)) = s.strip_prefix(crate::panels::library_panel::PREFIX).and_then(|rest| rest.split_once(':')) {
|
||||
add_library_id(id, ids);
|
||||
}
|
||||
};
|
||||
match v {
|
||||
Value::String(s) => add(s, ids),
|
||||
Value::Array(items) => items.iter().for_each(|item| collect_library_panel_ids(item, ids)),
|
||||
Value::Object(fields) => {
|
||||
for (key, item) in fields {
|
||||
add(key, ids);
|
||||
collect_library_panel_ids(item, ids);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes each id of `ids` as the id the reply shows instead, wherever `v` holds it: in a library's
|
||||
/// id, in its panel's id (`library:swatches:loaded/<path>`) and in keys.
|
||||
fn hide_library_ids(v: &mut Value, ids: &[(String, String)]) {
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
let hide = |s: &mut String| {
|
||||
for (id, shown) in ids {
|
||||
if s.contains(id.as_str()) {
|
||||
*s = s.replace(id.as_str(), shown);
|
||||
}
|
||||
}
|
||||
};
|
||||
match v {
|
||||
Value::String(s) => hide(s),
|
||||
Value::Array(items) => items.iter_mut().for_each(|item| hide_library_ids(item, ids)),
|
||||
Value::Object(fields) => {
|
||||
for (mut key, mut item) in std::mem::take(fields) {
|
||||
hide(&mut key);
|
||||
hide_library_ids(&mut item, ids);
|
||||
fields.insert(key, item);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The preferences that hold a folder, by their keys in `ui.engine_prefs` and the Preferences dialog.
|
||||
const PREF_FOLDERS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
|
||||
|
||||
/// The scratch disk choices that are not paths.
|
||||
const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"];
|
||||
|
||||
/// May the request being served read `path`? Under an automation read root (a control client's
|
||||
/// request), `ui.inspect` leaves out a path outside the root, as `ui.menu.list` leaves out a recent
|
||||
/// file or a listed script outside it.
|
||||
fn readable(path: &str) -> bool {
|
||||
vectorcraft_engine::file_access::check_read(path).is_ok()
|
||||
}
|
||||
|
||||
/// Takes out of `ui.inspect`'s copy of the UI state the paths the request may not read: recent files,
|
||||
/// a library panel's file and folder preferences (saved, and in an open Preferences dialog) outside
|
||||
/// the read root. The UI state itself is not changed.
|
||||
fn leave_out_unreadable_paths(ui: &mut serde_json::Map<String, Value>) {
|
||||
if let Some(Value::Array(files)) = ui.get_mut("recent_files") {
|
||||
files.retain(|f| f.as_str().is_some_and(readable));
|
||||
}
|
||||
if let Some(Value::Array(panels)) = ui.get_mut("library_panels") {
|
||||
for panel in panels.iter_mut().filter_map(Value::as_object_mut) {
|
||||
if panel.get("path").and_then(Value::as_str).is_some_and(|p| !readable(p)) {
|
||||
panel.remove("path");
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(Value::Object(prefs)) = ui.get_mut("engine_prefs") {
|
||||
leave_out_unreadable_folders(prefs);
|
||||
}
|
||||
if let Some(Value::Object(dialog)) = ui.get_mut("dialog")
|
||||
&& dialog.get("kind").and_then(Value::as_str) == Some("preferences")
|
||||
&& let Some(Value::Object(fields)) = dialog.get_mut("fields")
|
||||
{
|
||||
leave_out_unreadable_folders(fields);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes out of `prefs` the folder preferences ([`PREF_FOLDERS`]) the request may not read. An
|
||||
/// empty value (no folder) and a scratch disk choice ([`SCRATCH_CHOICES`]) stay.
|
||||
fn leave_out_unreadable_folders(prefs: &mut serde_json::Map<String, Value>) {
|
||||
for key in PREF_FOLDERS {
|
||||
let Some(path) = prefs.get(key).and_then(Value::as_str).map(str::trim) else { continue };
|
||||
if path.is_empty() || (key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path)) || readable(path) {
|
||||
continue;
|
||||
}
|
||||
prefs.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
fn key_from(name: &str) -> Option<egui::Key> {
|
||||
@@ -348,7 +516,12 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
|
||||
"engine.commands" => ok(all_commands(app)),
|
||||
"document.inspect" => wrap(app.run("document.inspect", p.clone())),
|
||||
"ui.inspect" => ok(inspect(app, ctx)),
|
||||
"ui.docking" => ok(crate::panel_docking::inspect(app, ctx)),
|
||||
"ui.docking" => {
|
||||
let mut docking = crate::panel_docking::inspect(app, ctx);
|
||||
let ids = unreadable_library_ids(app);
|
||||
hide_library_ids(&mut docking, &ids);
|
||||
ok(docking)
|
||||
}
|
||||
"ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_entries(app)).unwrap_or_default()),
|
||||
"ui.contextMenu.list" => ok(serde_json::to_value(crate::menus::context_entries(app)).unwrap_or_default()),
|
||||
"ui.tool.select" => wrap(app.run("tool.select", json!({"tool": s("tool").unwrap_or("")}))),
|
||||
|
||||
@@ -6521,8 +6521,14 @@ breakText Glyphs Глифи
|
||||
Ended at a limit Прекратен при лимит
|
||||
Stopped Спрян
|
||||
Ended by an internal fault Прекратен поради вътрешна грешка
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} извиквания към хоста
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} по-ранни реда премахнати, {cut} реда съкратени
|
||||
time unavailable времето не е налично
|
||||
{ms} ms {ms} ms
|
||||
{time}, {calls} {time}, {calls}
|
||||
slowest: {commands} най-бавни: {commands}
|
||||
{dropped}, {cut} {dropped}, {cut}
|
||||
@plural {n} host call|{n} host calls {n} извикване към хоста|{n} извиквания към хоста
|
||||
@plural {n} earlier line dropped|{n} earlier lines dropped {n} по-ранен ред премахнат|{n} по-ранни реда премахнати
|
||||
@plural {n} line cut|{n} lines cut {n} ред съкратен|{n} реда съкратени
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Обновяване на отложените ефекти
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6572,8 +6572,14 @@ shape Open Otvoren
|
||||
Ended at a limit Završeno na ograničenju
|
||||
Stopped Zaustavljeno
|
||||
Ended by an internal fault Završeno zbog interne greške
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} poziva hosta
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} ranijih redova uklonjeno, {cut} redova skraćeno
|
||||
time unavailable vrijeme nije dostupno
|
||||
{ms} ms {ms} ms
|
||||
{time}, {calls} {time}, {calls}
|
||||
slowest: {commands} najsporije: {commands}
|
||||
{dropped}, {cut} {dropped}, {cut}
|
||||
@plural {n} host call|{n} host calls {n} poziv hosta|{n} poziva hosta|{n} poziva hosta
|
||||
@plural {n} earlier line dropped|{n} earlier lines dropped {n} raniji red uklonjen|{n} ranija reda uklonjena|{n} ranijih redova uklonjeno
|
||||
@plural {n} line cut|{n} lines cut {n} red skraćen|{n} reda skraćena|{n} redova skraćeno
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Osvježi odgođene efekte
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6776,8 +6776,14 @@ breakText Glyphs Glifs
|
||||
Ended at a limit Acabat en un límit
|
||||
Stopped Aturat
|
||||
Ended by an internal fault Acabat per un error intern
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} crides a l’amfitrió
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} línies anteriors descartades, {cut} línies tallades
|
||||
time unavailable temps no disponible
|
||||
{ms} ms {ms} ms
|
||||
{time}, {calls} {time}, {calls}
|
||||
slowest: {commands} més lentes: {commands}
|
||||
{dropped}, {cut} {dropped}, {cut}
|
||||
@plural {n} host call|{n} host calls {n} crida a l’amfitrió|{n} crides a l’amfitrió
|
||||
@plural {n} earlier line dropped|{n} earlier lines dropped {n} línia anterior descartada|{n} línies anteriors descartades
|
||||
@plural {n} line cut|{n} lines cut {n} línia tallada|{n} línies tallades
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` i `last` han de ser números de línies que la consola conserva, `first` abans de `last`
|
||||
|
||||
# Deferred plug-in effects
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6795,8 +6795,14 @@ breakText Glyphs Glyfy
|
||||
Ended at a limit Ukončeno na limitu
|
||||
Stopped Zastaveno
|
||||
Ended by an internal fault Ukončeno vnitřní chybou
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} volání hostitele
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} starších řádků zahozeno, {cut} řádků zkráceno
|
||||
time unavailable čas není k dispozici
|
||||
{ms} ms {ms} ms
|
||||
{time}, {calls} {time}, {calls}
|
||||
slowest: {commands} nejpomalejší: {commands}
|
||||
{dropped}, {cut} {dropped}, {cut}
|
||||
@plural {n} host call|{n} host calls {n} volání hostitele|{n} volání hostitele|{n} volání hostitele
|
||||
@plural {n} earlier line dropped|{n} earlier lines dropped {n} starší řádek zahozen|{n} starší řádky zahozeny|{n} starších řádků zahozeno
|
||||
@plural {n} line cut|{n} lines cut {n} řádek zkrácen|{n} řádky zkráceny|{n} řádků zkráceno
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` a `last` musí být čísla řádků, které konzole uchovává, `first` před `last`
|
||||
|
||||
# Deferred plug-in effects
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6535,8 +6535,14 @@ breakText Glyphs Glyffer
|
||||
Ended at a limit Afsluttet ved en grænse
|
||||
Stopped Stoppet
|
||||
Ended by an internal fault Afsluttet af en intern fejl
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} værtskald
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} tidligere linjer fjernet, {cut} linjer afkortet
|
||||
time unavailable tid ikke tilgængelig
|
||||
{ms} ms {ms} ms
|
||||
{time}, {calls} {time}, {calls}
|
||||
slowest: {commands} langsomste: {commands}
|
||||
{dropped}, {cut} {dropped}, {cut}
|
||||
@plural {n} host call|{n} host calls {n} værtskald|{n} værtskald
|
||||
@plural {n} earlier line dropped|{n} earlier lines dropped {n} tidligere linje fjernet|{n} tidligere linjer fjernet
|
||||
@plural {n} line cut|{n} lines cut {n} linje afkortet|{n} linjer afkortet
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Opdatér udskudte effekter
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6382,8 +6382,14 @@ breakText Glyphs Glyphen
|
||||
Ended at a limit An einem Limit beendet
|
||||
Stopped Gestoppt
|
||||
Ended by an internal fault Durch einen internen Fehler beendet
|
||||
{ms} ms, {calls} host calls {ms} ms, {calls} Host-Aufrufe
|
||||
{dropped} earlier lines dropped, {cut} lines cut {dropped} ältere Zeilen verworfen, {cut} Zeilen gekürzt
|
||||
time unavailable Zeit nicht verfügbar
|
||||
{ms} ms {ms} ms
|
||||
{time}, {calls} {time}, {calls}
|
||||
slowest: {commands} langsamste: {commands}
|
||||
{dropped}, {cut} {dropped}, {cut}
|
||||
@plural {n} host call|{n} host calls {n} Host-Aufruf|{n} Host-Aufrufe
|
||||
@plural {n} earlier line dropped|{n} earlier lines dropped {n} ältere Zeile verworfen|{n} ältere Zeilen verworfen
|
||||
@plural {n} line cut|{n} lines cut {n} Zeile gekürzt|{n} Zeilen gekürzt
|
||||
@msg `first` and `last` must be numbers of lines the console holds, first before last `first` und `last` müssen Nummern von Zeilen sein, die die Konsole enthält, `first` vor `last`
|
||||
|
||||
# Deferred plug-in effects
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user