Merge main into fix/scriptcheck-linear-steps

This commit is contained in:
dotCooCoo
2026-11-28 22:20:45 -08:00
129 changed files with 7924 additions and 423 deletions
+159 -1
View File
@@ -6,7 +6,7 @@
//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also
//! take the comma-separated legacy form (<https://www.w3.org/TR/css-color-4/#legacy-color-syntax>).
//! Hues take the angle units of CSS Values 4 (<https://www.w3.org/TR/css-values-4/#angles>). A hex
//! color may leave out its `#`.
//! color may leave out its `#`. [`format`] writes a color in these forms.
//!
//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages,
//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`,
@@ -89,6 +89,126 @@ fn byte(v: f32) -> u8 {
(v.clamp(0.0, 1.0) * 255.0).round() as u8
}
/// The forms [`format`] writes a color in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Notation {
/// `#rrggbb`.
Hex,
/// `#rrggbbaa`, `ff` for a color without an alpha.
HexAlpha,
/// `rgb(51 102 153)`.
Rgb,
/// `hsl(210 50% 40%)`.
Hsl,
/// `oklch(49.93% 0.0987 250.43)`.
Oklch,
}
/// `rgb` (red, green and blue from 0 to 1) and the alpha `alpha` (0 to 1) as text of `notation`
/// that [`parse`] reads back to the same `#rrggbb`. Each channel is first rounded to the nearest of
/// 256 steps, as [`hex_of`] rounds it. `rgb()`, `hsl()` and `oklch()` use the space-separated form
/// and add the alpha as a percentage after a `/` when it rounds to less than 100 %; `hsl()` and
/// `oklch()` give their numbers to two places (chroma to four), without trailing zeros, and
/// `oklch()` takes one or two more places where fewer would read back to other bytes. The hue of a
/// gray is 0. [`Notation::Hex`] leaves the alpha out.
pub fn format(rgb: [f32; 3], alpha: Option<f32>, notation: Notation) -> String {
// A NaN alpha reads as none.
let alpha = alpha.filter(|a| !a.is_nan());
let bytes = rgb.map(byte);
let units = bytes.map(|v| f64::from(v) / 255.0);
let [r, g, b] = bytes;
match notation {
Notation::Hex => hex_of(rgb),
Notation::HexAlpha => format!("{}{:02x}", hex_of(rgb), byte(alpha.unwrap_or(1.0))),
Notation::Rgb => format!("rgb({r} {g} {b}{})", alpha_part(alpha)),
Notation::Hsl => {
let [h, s, l] = rgb_to_hsl(units);
format!("hsl({} {}% {}%{})", hue_text(h), number(s * 100.0, 2), number(l * 100.0, 2), alpha_part(alpha))
}
Notation::Oklch => {
let lch = oklab::to_oklch(units.map(|v| v as f32));
// The fewest places that read back to the same bytes, from two (four for chroma).
let fits = |p: i32| oklch_rounded(lch, p).filter(|&[l, c, h]| oklab::from_oklch(l, c, h).0.map(byte) == bytes);
let (p, [l, c, h]) = (0..3).find_map(|extra| fits(extra).map(|v| (extra, v))).unwrap_or((2, oklch_rounded(lch, 2).unwrap_or(lch)));
let places = |base: i32| usize::try_from(base + p).unwrap_or(2);
let c = number(c, places(4));
// A chroma that rounds to 0 is a gray, whose hue is 0.
let h = if c == "0" { "0".to_string() } else { hue_text_to(h, places(2)) };
format!("oklch({}% {c} {h}{})", number(l * 100.0, places(2)), alpha_part(alpha))
}
}
}
/// OKLCH `lch` rounded as [`format`] writes it with `extra` more places than two for the
/// lightness percentage and the hue and four for the chroma, or `None` when no chroma at or under
/// the rounded one within [`OKLCH_CHROMA_STEPS`] steps lies inside sRGB. A color on the edge of
/// sRGB can round to a point just outside it, where [`parse`] would lower the chroma to the edge at
/// the rounded lightness and hue; the chroma is lowered a step at a time instead.
fn oklch_rounded([l, c, h]: [f64; 3], extra: i32) -> Option<[f64; 3]> {
let (l, h) = (rounded(l, 4 + extra), rounded(h, 2 + extra));
let step = 10f64.powi(-(4 + extra));
let mut c = rounded(c, 4 + extra);
for _ in 0..OKLCH_CHROMA_STEPS {
if c <= 0.0 || oklab::in_srgb(oklab::oklch_to_srgb(l, c, h)) {
return Some([l, c.max(0.0), h]);
}
c = rounded(c - step, 4 + extra);
}
None
}
/// The most steps [`oklch_rounded`] lowers a chroma by to bring it inside sRGB.
const OKLCH_CHROMA_STEPS: usize = 50;
/// `v` rounded to `places` decimal places.
fn rounded(v: f64, places: i32) -> f64 {
let f = 10f64.powi(places);
(v * f).round() / f
}
/// ` / 50%` for an alpha that rounds to less than 100 %, else nothing.
fn alpha_part(alpha: Option<f32>) -> String {
let percent = number(f64::from(alpha.unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0, 2);
if percent == "100" { String::new() } else { format!(" / {percent}%") }
}
/// A hue in degrees to two places, 360 written as 0.
fn hue_text(h: f64) -> String {
hue_text_to(h, 2)
}
/// A hue in degrees to `places` places, 360 written as 0.
fn hue_text_to(h: f64, places: usize) -> String {
let text = number(h, places);
if text == "360" { "0".to_string() } else { text }
}
/// `v` to `places` decimal places, without trailing zeros or a sign on zero.
fn number(v: f64, places: usize) -> String {
let text = format!("{v:.places$}");
let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text.as_str() };
if text == "-0" { "0".to_string() } else { text.to_string() }
}
/// Hue in degrees (0 to 360), saturation and lightness (0 to 1) of `rgb`, by CSS Color 4's
/// rgbToHsl (<https://www.w3.org/TR/css-color-4/#rgb-to-hsl>); the hue of a gray is 0.
fn rgb_to_hsl([r, g, b]: [f64; 3]) -> [f64; 3] {
let (max, min) = (r.max(g).max(b), r.min(g).min(b));
let (d, l) = (max - min, (max + min) / 2.0);
if d == 0.0 {
return [0.0, 0.0, l];
}
let s = if l == 0.0 || l == 1.0 { 0.0 } else { (max - l) / l.min(1.0 - l) };
let h = if max == r {
(g - b) / d + if g < b { 6.0 } else { 0.0 }
} else if max == g {
(b - r) / d + 2.0
} else {
(r - g) / d + 4.0
};
[h * 60.0, s, l]
}
/// A hex color of 3, 4, 6 or 8 digits, with or without `#`.
fn hex(text: &str) -> Option<CssColor> {
let digits = text.strip_prefix('#').unwrap_or(text);
@@ -412,6 +532,26 @@ mod tests {
assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00");
}
#[test]
fn format_writes_each_notation_with_the_alpha_where_it_belongs() {
let rgb = [0.2, 0.4, 0.6];
let half = Some(0.5);
assert_eq!(format(rgb, half, Notation::Hex), "#336699");
assert_eq!(format(rgb, half, Notation::HexAlpha), "#33669980");
assert_eq!(format(rgb, None, Notation::HexAlpha), "#336699ff");
assert_eq!(format(rgb, Some(1.0), Notation::HexAlpha), "#336699ff");
assert_eq!(format(rgb, half, Notation::Rgb), "rgb(51 102 153 / 50%)");
assert_eq!(format(rgb, None, Notation::Rgb), "rgb(51 102 153)");
assert_eq!(format(rgb, Some(0.99999), Notation::Rgb), "rgb(51 102 153)", "an alpha that rounds to 100 % is left out");
assert_eq!(format(rgb, Some(0.125), Notation::Hsl), "hsl(210 50% 40% / 12.5%)");
assert_eq!(format(rgb, None, Notation::Oklch), "oklch(49.93% 0.0987 250.43)");
assert_eq!(format([0.5; 3], None, Notation::Hsl), "hsl(0 0% 50.2%)");
assert_eq!(format([1.0; 3], None, Notation::Oklch), "oklch(100% 0 0)");
assert_eq!(format([0.0; 3], Some(0.0), Notation::Oklch), "oklch(0% 0 0 / 0%)");
assert_eq!(format([1.0, 0.0, 0.0], None, Notation::Hsl), "hsl(0 100% 50%)");
assert_eq!(format([-1.0, 2.0, f32::NAN], Some(f32::NAN), Notation::Rgb), "rgb(0 255 0)");
}
proptest! {
#[test]
fn random_text_never_panics(text in "\\PC{0,60}") {
@@ -439,5 +579,23 @@ mod tests {
prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a));
prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}"));
}
#[test]
fn each_notation_reads_back_to_the_same_color(r: u8, g: u8, b: u8, a: u8) {
let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
let alpha = f32::from(a) / 255.0;
for notation in [Notation::Hex, Notation::HexAlpha, Notation::Rgb, Notation::Hsl, Notation::Oklch] {
let text = format(rgb, Some(alpha), notation);
let c = parse(&text).unwrap_or_else(|| panic!("{text} should parse"));
prop_assert_eq!(hex_of(c.rgb), hex_of(rgb), "{}", text);
let read = c.alpha.unwrap_or(1.0);
match notation {
Notation::Hex => prop_assert_eq!(c.alpha, None),
Notation::HexAlpha => prop_assert_eq!(byte(read), a),
// A percentage to two places, left out when it rounds to 100.
_ => prop_assert!((read - alpha).abs() <= 0.00006, "{} gives {}", text, read),
}
}
}
}
}
+34
View File
@@ -146,6 +146,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
parse_color
),
cmd!(
query "color.format",
"Format Color",
[],
None,
"{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four), and oklch() takes up to two more where fewer would read back to another color; cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB",
always,
format_color
),
cmd!(
query "color.contrast",
"Contrast",
@@ -158,6 +167,31 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
fn format_color(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.format";
let col = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
let opacity = super::paint::opacity_param(p, C)?;
let notation = match text_param(p, "notation", C)? {
Some("hex") => Some(css::Notation::Hex),
Some("hexAlpha") => Some(css::Notation::HexAlpha),
Some("rgb") => Some(css::Notation::Rgb),
Some("hsl") => Some(css::Notation::Hsl),
Some("oklch") => Some(css::Notation::Oklch),
Some("cmyk") => None,
_ => return Err(bad(C, "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk")),
};
let cms = vectorcraft_color::cms::active();
let intent = cms.settings().intent;
let text = match notation {
None => vectorcraft_doc::swatches::color_name(cms.convert(&col, Model::Cmyk, intent)),
Some(css::Notation::Oklch) if !cms.rgb_is_srgb() => return Err(bad(C, "OKLCH needs sRGB as the working RGB space")),
// The working RGB numbers, as the Color panel's hex field and color.parse read them; for
// oklch() the working RGB space is sRGB.
Some(n) => css::format(cms.convert(&col, Model::Rgb, intent).to_rgb_uncalibrated(), opacity, n),
};
Ok(json!({ "text": text }))
}
fn parse_color(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.parse";
let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?;
+173 -21
View File
@@ -91,6 +91,8 @@
//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving
//! one out is not an undo step.
use std::sync::Arc;
use serde::Serialize;
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer};
@@ -214,8 +216,18 @@ struct Form {
frame: Affine,
}
#[cfg(test)]
thread_local! {
/// Tests: how many times [`Form::of`] reduced an object to its form on this thread.
pub(crate) static FORMS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread.
pub(crate) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
impl Form {
fn of(n: &Node) -> Option<Self> {
#[cfg(test)]
FORMS_MADE.with(|c| c.set(c.get() + 1));
let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY };
f.add(n, 0)?;
let first = *f.points.first()?;
@@ -450,8 +462,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
),
};
let on = |r: Rect, b: Rect| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center());
let in_scope = |n: &Node| {
let Some(b) = n.geometric_bounds_with(&symbols) else { return false };
let in_scope = |b: Option<Rect>| {
let Some(b) = b else { return false };
if !d.artboards.iter().any(|a| on(a.rect, b)) {
return o.include_canvas;
}
@@ -459,14 +471,16 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
};
// A copy that lies the same way has the size of the selected object when their boxes are as
// wide and as high; a turned copy, when the transform that lays the object on it doesn't scale.
let same_size = |n: &Node, xf: Affine, turned: bool| {
let same_size = |b: Option<Rect>, xf: Affine, turned: bool| {
if turned {
close(xf.determinant().abs().sqrt(), 1.0)
} else {
matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))
matches!((key_size, b), (Some((w, h)), Some(b)) if close(w, b.width()) && close(h, b.height()))
}
};
let mut out = vec![(*id, Affine::IDENTITY)];
let mut cache = st.global_edit_forms.0.borrow_mut();
let mut pass = cache.forms.pass();
super::select::walk_selectable(d, st.isolation, |n| {
if n.id == *id || out.len() >= MAX_MEMBERS {
return false;
@@ -482,21 +496,134 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
_ => false,
};
// The object count first: it turns most objects down before their form is made.
if n.children().map(Vec::len) == count
&& let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n))
&& (!o.size || same_size(n, xf, turned))
&& (!o.appearance || same_look(key, n))
&& in_scope(n)
{
out.push((n.id, xf));
// A group taken is taken whole, as compound paths, symbol instances and the others are.
return false;
if n.children().map(Vec::len) != count {
return look_in;
}
let seen = pass.get(n, || Seen { form: Form::of(n).filter(|_| supported(n)), bounds: None });
if let Some((xf, turned)) = seen.form.as_ref().and_then(|f| form.onto(f)) {
let b = seen.bounds(n, &symbols);
if (!o.size || same_size(b, xf, turned)) && (!o.appearance || same_look(key, n)) && in_scope(b) {
out.push((n.id, xf));
// A group taken is taken whole, as compound paths, symbol instances and the others are.
return false;
}
}
look_in
});
cache.forms.end(pass, d);
Ok(out)
}
/// What [`matches`] and [`outlines`] found for each object they looked at, kept from one call to
/// the next so that after an edit only the objects the edit replaced are measured again. A clone
/// starts empty.
#[derive(Default)]
pub struct FormCache(std::cell::RefCell<FormCacheInner>);
#[derive(Default)]
struct FormCacheInner {
forms: ByNode<Seen>,
/// The outline of each highlighted object, or `None` when it has none and its box is shown.
outlines: ByNode<Option<BezPath>>,
}
/// An object as [`matches`] found it.
struct Seen {
/// Its form, or `None` when Global Edit doesn't support it.
form: Option<Form>,
/// Its geometric bounds, once measured; not kept for an object with symbol instances, whose
/// bounds follow the symbols' art.
bounds: Option<Option<Rect>>,
}
impl Seen {
fn bounds(&mut self, n: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> Option<Rect> {
if self.form.as_ref().is_some_and(|f| !f.symbols.is_empty()) {
return n.geometric_bounds_with(symbols);
}
*self.bounds.get_or_insert_with(|| n.geometric_bounds_with(symbols))
}
}
/// Values found for nodes of a document, by node address. The layers they were found in are held,
/// which keeps every node in them alive and unchanged (an edit replaces each node it changes), so
/// no other node can have that address while its entry is here.
struct ByNode<T> {
layers: Vec<Arc<Node>>,
values: ByAddress<T>,
}
impl<T> Default for ByNode<T> {
fn default() -> Self {
Self { layers: vec![], values: ByAddress::default() }
}
}
/// Values by node address.
type ByAddress<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHasher>>;
/// Hashes a node address: a multiply that spreads its bits, with the high half folded into the low
/// half (addresses are aligned, so their low bits are always the same).
#[derive(Default)]
struct AddressHasher(u64);
impl std::hash::Hasher for AddressHasher {
fn write(&mut self, bytes: &[u8]) {
for b in bytes {
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
}
}
fn write_usize(&mut self, n: usize) {
let x = (n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);
self.0 = x ^ (x >> 32);
}
fn finish(&self) -> u64 {
self.0
}
}
/// One walk of a document: the values it asks for, taken from the ones kept or found anew.
struct Pass<T> {
old: ByAddress<T>,
new: ByAddress<T>,
}
impl<T> Pass<T> {
fn get(&mut self, n: &Node, find: impl FnOnce() -> T) -> &mut T {
let at = std::ptr::from_ref(n) as usize;
let old = &mut self.old;
self.new.entry(at).or_insert_with(|| old.remove(&at).unwrap_or_else(find))
}
}
impl<T> ByNode<T> {
fn pass(&mut self) -> Pass<T> {
let old = std::mem::take(&mut self.values);
Pass { new: ByAddress::with_capacity_and_hasher(old.len(), Default::default()), old }
}
/// Keep the values `pass` asked for, found in `d`.
fn end(&mut self, pass: Pass<T>, d: &Document) {
self.values = pass.new;
self.layers.clone_from(&d.layers);
}
}
impl Clone for FormCache {
fn clone(&self) -> Self {
Self::default()
}
}
impl std::fmt::Debug for FormCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let c = self.0.borrow();
f.debug_struct("FormCache").field("forms", &c.forms.values.len()).field("outlines", &c.outlines.values.len()).finish()
}
}
fn can_toggle(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.global_edit.is_some() {
@@ -935,20 +1062,45 @@ pub fn similar(s: &Session) -> Outlines {
/// selected object, in their layer's color.
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
let symbols = st.doc.symbol_boxes();
members
let mut cache = st.global_edit_forms.0.borrow_mut();
let mut pass = cache.outlines.pass();
let out = members
.iter()
.filter_map(|(id, _)| {
let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?;
if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) {
return None;
// One look-up of the object's place, then down through its layers and groups: none of
// them may be selected, and the innermost layer gives the color.
let (mut nodes, mut found, mut layer) = (&st.doc.layers, None, None);
for i in st.doc.index_path(*id)? {
let c: &Node = nodes.get(i)?;
if st.selection.objects.contains(&c.id) {
return None;
}
if c.is_layer() {
layer = Some(c);
}
if let Some(ch) = c.children() {
nodes = ch;
}
found = Some(c);
}
let path = match n.stroke_path() {
Some(p) => p,
let n = found.filter(|n| n.id == *id && !holds(n, &st.selection.objects))?;
let color = match layer.map(|l| &l.kind) {
Some(NodeKind::Layer { color, .. }) => color.rgb(),
_ => vectorcraft_doc::LAYER_COLORS[0].1,
};
let path = match pass.get(n, || {
#[cfg(test)]
OUTLINES_MADE.with(|c| c.set(c.get() + 1));
n.stroke_path()
}) {
Some(p) => p.clone(),
None => n.geometric_bounds_with(&symbols)?.to_path(0.1),
};
Some((path, st.doc.layer_color(*id)))
Some((path, color))
})
.collect()
.collect();
cache.outlines.end(pass, &st.doc);
out
}
#[cfg(test)]
+3 -3
View File
@@ -913,9 +913,9 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
apply_paint_opacity(s, p, paint, opacity, fill)
}
/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None`
/// when it is left out or null.
fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
/// The `opacity` param of `paint.setFill`, `paint.setStroke` and `color.format` (a percentage) as
/// 0..1; `None` when it is left out or null.
pub(crate) fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
match p.get("opacity") {
None | Some(Value::Null) => Ok(None),
Some(v) => match v.as_f64() {
+158 -6
View File
@@ -8,7 +8,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer};
use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject};
use vectorcraft_doc::{AnchorRef, Appearance, Document, LockedArtboards, Node, NodeId, NodeKind, SegmentRef, TextObject};
use vectorcraft_geom::{FillRule, PathData, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_pathops::{BoolOp, PathfinderOp};
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clean Up…",
["Object", "Path"],
None,
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} remove them, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed}",
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers, objects at 0% opacity and their members, and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}",
has_doc,
clean_up
),
@@ -1715,12 +1715,152 @@ fn is_painted(a: &Appearance) -> bool {
})
}
/// Hairline Slivers' width by default, in points: 0.03 mm, VectorCraft's own value.
pub const HAIRLINE_SLIVER_WIDTH: f64 = 0.03 * 72.0 / 25.4;
/// The widths Hairline Slivers takes, in points.
pub const HAIRLINE_SLIVER_WIDTH_RANGE: std::ops::RangeInclusive<f64> = 0.001..=3.0;
/// The Hairline Slivers width `p` gives as `key` (by default [`HAIRLINE_SLIVER_WIDTH`]; a string
/// with a unit reads too): an error when it is not a distance in [`HAIRLINE_SLIVER_WIDTH_RANGE`].
pub(crate) fn sliver_width(p: &Value, key: &str, cmd: &str) -> Result<f64> {
let w = length_given(p, key, cmd)?.unwrap_or(HAIRLINE_SLIVER_WIDTH);
if !HAIRLINE_SLIVER_WIDTH_RANGE.contains(&w) {
let (lo, hi) = (HAIRLINE_SLIVER_WIDTH_RANGE.start(), HAIRLINE_SLIVER_WIDTH_RANGE.end());
return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi} pt")));
}
Ok(w)
}
/// Hairline Slivers: is `n` a path or compound path (not a guide or clipping path) whose subpaths
/// are all closed, with a visible fill, no visible stroke and no effect (on the object or on a fill or stroke),
/// whose fill no circle `width` across fits inside? A compound path is measured as one fill.
/// `None` when the fill can't be measured with what is left of `budget` ([`po::thinner_than_within`]).
/// A hidden member of a compound path is measured too, since the compound path paints it.
fn is_hairline_sliver(n: &Node, width: f64, budget: &mut po::ThicknessBudget) -> Option<bool> {
// A shape with no fill that paints is left to Unpainted Objects.
if !n.appearance.has_drawn_fill() || draws_beyond_its_fill(&n.appearance) {
return Some(false);
}
let (subpaths, rule): (Vec<&SubPath>, FillRule) = match &n.kind {
NodeKind::Path { path, rule, guide: false, clipping: false, .. } => (path.subpaths.iter().collect(), *rule),
NodeKind::Compound { children, rule } => {
let mut all = vec![];
for c in children {
let NodeKind::Path { path, guide: false, .. } = &c.kind else { return Some(false) };
all.extend(path.subpaths.iter());
}
(all, *rule)
}
_ => return Some(false),
};
// Paths of one anchor are stray points, and open paths are lines.
if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed || sp.anchors.len() < 2) {
return Some(false);
}
po::thinner_than_within(&PathData::new(subpaths.into_iter().cloned().collect()), rule, width, budget)
}
/// Does `a` paint anything beyond the fill of the geometry it is on: a stroke that draws, or an
/// effect on the object or on one of its fills and strokes?
fn draws_beyond_its_fill(a: &Appearance) -> bool {
a.has_drawn_stroke() || !a.effects.is_empty() || a.items.iter().any(|i| !i.effects().is_empty())
}
/// A group that stands for live or generated art (Live Paint, a graph, a dimension, a flare, a
/// tracing result, objects on a path, a compound shape, type's glyph outlines, the pieces a clipping
/// path paints and the like), as Artwork Cleanup's checks find most of them: Hairline Slivers
/// leaves its members alone.
fn holds_generated_art(n: &Node) -> bool {
let e = n.extras();
vectorcraft_tools::builder::is_live_paint(n)
|| e.type_outlines
|| e.clip_pieces
|| e.graph.is_some()
|| e.shaper.is_some()
|| e.dimension.is_some()
|| e.flare.is_some()
|| e.trace.is_some()
|| e.objects_on_path.is_some()
|| e.live_paint_gaps.is_some()
|| e.compound_shape
}
/// The objects Hairline Slivers finds in `d` for `width`.
pub(crate) struct Slivers {
pub ids: Vec<NodeId>,
/// Closed paths and compound paths whose fill couldn't be measured, which are left as they are.
pub unmeasured: Vec<NodeId>,
}
/// The status-bar warning for `count` shapes Hairline Slivers couldn't measure, when there are any.
pub(crate) fn unmeasured_warning(count: usize) -> Option<String> {
(count > 0).then(|| {
format!(
"Hairline Slivers: {count} shapes could not be measured (too complex, or past the limit of work for one run) and were left as they are"
)
})
}
/// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not
/// those on a locked artboard or in a template layer) for which `within` holds, in the layers and
/// groups of the whole document. A compound path counts as one object. The clipping paths of groups
/// and layers (and all of a clipping group used as one), the members of live and generated art,
/// objects at 0 % opacity and everything in a group or layer at 0 %, and the members of groups and
/// layers whose own stroke or effect paints them are left out.
pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers {
struct Walk<'a> {
width: f64,
locks: LockedArtboards<'a>,
within: &'a dyn Fn(NodeId) -> bool,
// One budget for the whole document, so that thousands of shapes that need a search take
// a bounded time; the shapes after it runs out count as unmeasured.
budget: po::ThicknessBudget,
out: Vec<(NodeId, Option<bool>)>,
}
fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) {
// An object at 0 % opacity, or anything in a group or layer at 0 %, paints nothing.
if !n.visible || n.locked || n.is_template() || clip_path || n.opacity <= 0.0 {
return;
}
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
if holds_generated_art(n) || draws_beyond_its_fill(&n.appearance) {
return;
}
let clips = n.clips();
for (i, c) in children.iter().enumerate() {
visit(c, clips && i == 0, w);
}
}
// Art on a locked artboard, or outside `within`, is left out before it is measured.
NodeKind::Path { .. } | NodeKind::Compound { .. } if !w.locks.holds_id(n.id) && (w.within)(n.id) => {
match is_hairline_sliver(n, w.width, &mut w.budget) {
Some(false) => {}
found => w.out.push((n.id, found)),
}
}
_ => {}
}
}
let mut w = Walk { width, locks: d.locked_artboards(), within, budget: po::ThicknessBudget::document(), out: vec![] };
for l in &d.layers {
visit(l, false, &mut w);
}
let mut found = w.out;
let editable = d.editable();
found.retain(|(id, _)| editable(*id));
let (sure, unsure): (Vec<_>, Vec<_>) = found.into_iter().partition(|(_, f)| f.is_some());
Slivers { ids: sure.into_iter().map(|(id, _)| id).collect(), unmeasured: unsure.into_iter().map(|(id, _)| id).collect() }
}
fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.path.cleanUp";
let stray = switch_or(p, "strayPoints", true, C)?;
let unpainted = switch_or(p, "unpaintedObjects", true, C)?;
let empty_text = switch_or(p, "emptyTextPaths", true, C)?;
let found = {
let slivers = switch_or(p, "hairlineSlivers", false, C)?;
let width = sliver_width(p, "sliverWidth", C)?;
let (found, warning) = {
let d = &s.doc()?.doc;
let mut v = vec![];
fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec<NodeId>, opts: (bool, bool, bool)) {
@@ -1763,10 +1903,22 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
}
let editable = d.editable();
v.retain(|id| editable(*id));
v
let mut warning = None;
if slivers {
let found = hairline_slivers(d, width, &|_| true);
let listed: BTreeSet<NodeId> = v.iter().copied().collect();
// A shape another option removes isn't left as it is.
warning = unmeasured_warning(found.unmeasured.iter().filter(|id| !listed.contains(id)).count());
v.extend(found.ids.into_iter().filter(|id| !listed.contains(id)));
}
(v, warning)
};
let reply = |removed: usize| match &warning {
Some(w) => json!({ "removed": removed, "warning": w }),
None => json!({ "removed": removed }),
};
if found.is_empty() {
return Ok(json!({ "removed": 0 }));
return Ok(reply(0));
}
s.edit("Clean Up", |d, _| {
let mut gone = Beside::replacing(d, &found);
@@ -1777,7 +1929,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
}
gone.finish(d)
})?;
Ok(json!({ "removed": found.len() }))
Ok(reply(found.len()))
}
// ---------- Divide Objects Below ----------
+7 -3
View File
@@ -1468,11 +1468,11 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
// A heavy plug-in is installed once a person agrees.
if plugin.manifest().budget == Budget::Heavy && !allow_heavy {
let (minutes, times) = vectorcraft_plugins::heavy_terms();
let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME);
return Err(bad(
C,
format!(
"“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants",
plugin.manifest().name
"“{name}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants"
),
));
}
@@ -1615,6 +1615,10 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
if !refused.is_empty() {
v["refusedCommands"] = json!(refused);
}
let translations = &plugin.manifest().translations;
if !translations.is_empty() {
v["translations"] = serde_json::to_value(translations).unwrap_or(Value::Null);
}
v
})
}
@@ -2447,7 +2451,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect Plug-in",
[],
None,
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has), refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module) and translations?: {language: {name?, params?, groups?, commands?}} (the manifest's translations as declared, when it gives any)",
always,
inspect
),
@@ -152,6 +152,7 @@ pub(super) const ALLOWED: &[&str] = &[
"charStyle.setAttrs",
"charStyle.unused",
"color.convert",
"color.format",
"color.gamutCheck",
"color.harmony",
"color.parse",
@@ -541,6 +542,7 @@ pub(super) const ALLOWED: &[&str] = &[
"select.object.brushStrokes",
"select.object.clippingMasks",
"select.object.directionHandles",
"select.object.hairlineSlivers",
"select.object.notAlignedToPixelGrid",
"select.object.pointText",
"select.object.slices",
File diff suppressed because one or more lines are too long
+28
View File
@@ -9,6 +9,7 @@ use vectorcraft_tools::builder::is_live_paint;
use super::object::can_align;
use super::panelcmds::artboard_at;
use super::pathops::{hairline_slivers, sliver_width, unmeasured_warning};
use super::wand::{fill_of, stroke_of};
use super::{
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param,
@@ -205,6 +206,15 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("select.object.strayPoints", "Stray Points", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
.path_data()
.is_some_and(|p| p.anchor_count() == 1))),
cmd!(
"select.object.hairlineSlivers",
"Hairline Slivers…",
["Select", "Object"],
None,
"{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, objects at 0% opacity and their members, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}",
has_doc,
select_hairline_slivers
),
cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
.path_data()
.is_some_and(|p| !p.is_closed()))),
@@ -1459,6 +1469,24 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result<Value> {
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
/// Select › Object › Hairline Slivers: the objects Clean Up's Hairline Slivers removes
/// ([`hairline_slivers`]), inside the isolated group while one is isolated.
fn select_hairline_slivers(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "select.object.hairlineSlivers";
let width = sliver_width(p, "width", C)?;
let st = s.doc()?;
let (d, iso) = (&st.doc, st.isolation);
let locks = d.locked_artboards();
let found = hairline_slivers(d, width, &|id| is_selectable(d, iso, &locks, id));
let warning = unmeasured_warning(found.unmeasured.len());
s.select(|_, sel| sel.set(found.ids))?;
let count = s.doc()?.selection.objects.len();
Ok(match warning {
Some(w) => json!({ "count": count, "warning": w }),
None => json!({ "count": count }),
})
}
/// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned
/// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk
/// does not look at the paths inside it.
+4
View File
@@ -86,6 +86,9 @@ pub struct DocState {
/// Whether Start Global Edit supports the one selected object
/// ([`cmd::globaledit::SupportCache`]), as of a revision. Not saved, not undoable.
pub(crate) global_edit_support: cmd::globaledit::SupportCache,
/// The forms Start Global Edit compared the selected object with
/// ([`cmd::globaledit::FormCache`]). Not saved, not undoable.
pub(crate) global_edit_forms: cmd::globaledit::FormCache,
/// What leaving symbol editing mode goes back to ([`cmd::symboledit`]).
pub(crate) symbol_edit_return: cmd::symboledit::Return,
pub interaction: Option<Interaction>,
@@ -481,6 +484,7 @@ impl DocState {
global_edit: None,
similar_outlines: Default::default(),
global_edit_support: Default::default(),
global_edit_forms: Default::default(),
symbol_edit_return: Default::default(),
interaction: None,
undo_group: None,
+28 -1
View File
@@ -715,6 +715,15 @@ impl ScriptScope {
/// The real path of the file at `path` and its first `max` bytes, at most.
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
match self.read_unless(path, max, |_| false)? {
(real, Some(bytes)) => Ok((real, bytes)),
(_, None) => Err(ScriptRead::Failed("the file was not read".to_string())),
}
}
/// [`ScriptScope::read`], except that a file whose real path `known` accepts is not opened:
/// → its real path and no bytes.
pub(crate) fn read_unless(&self, path: &Path, max: usize, known: impl Fn(&Path) -> bool) -> Result<(PathBuf, Option<Vec<u8>>), ScriptRead> {
use std::io::Read;
if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
return Err(ScriptRead::Refused);
@@ -730,6 +739,9 @@ impl ScriptScope {
if !self.allows(&real) {
return Err(ScriptRead::Refused);
}
if known(&real) {
return Ok((real, None));
}
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?;
if !meta.is_file() {
@@ -747,7 +759,7 @@ impl ScriptScope {
if std::fs::canonicalize(path).ok().as_ref() != Some(&real) {
return Err(ScriptRead::Refused);
}
Ok((real, bytes))
Ok((real, Some(bytes)))
}
/// The first granted folder, as people read it (`None` for a script given as text).
@@ -966,6 +978,21 @@ mod tests {
p.to_string_lossy().into_owned()
}
/// A file the caller already has is not opened: its size is not checked and no byte is read.
#[test]
fn a_known_script_file_is_not_read_again() {
let (base, _) = folders("known");
std::fs::write(base.join("in/big.js"), "x".repeat(64)).unwrap();
let scope = ScriptScope::of_folder(&base.join("in"));
let path = base.join("in/big.js");
assert_eq!(scope.read(&path, 16).map(|(_, b)| b.len()), Err(ScriptRead::TooLarge));
let real = std::fs::canonicalize(&path).unwrap();
assert_eq!(scope.read_unless(&path, 16, |r| r == real), Ok((real.clone(), None)));
assert_eq!(scope.read_unless(&path, 64, |_| false).map(|(_, b)| b.map(|b| b.len())), Ok(Some(64)));
assert_eq!(scope.read_unless(&base.join("outside/secret.svg"), 64, |_| true), Err(ScriptRead::Refused));
let _ = std::fs::remove_dir_all(base);
}
/// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind
/// only one grants is not granted.
#[test]
+1 -1
View File
@@ -33,7 +33,7 @@ pub use cmd::flare::flare_settings;
pub use cmd::gradient::{GradientEditPaints, StopOwner};
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
pub use cmd::params::{check_keys, check_params};
pub use cmd::pathops::{auto_simplify_level, can_outline_stroke};
pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level, can_outline_stroke};
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step};
pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE;
+28
View File
@@ -44,6 +44,9 @@
//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run.
//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`.
//! - `app.activeDocument` with no document open throws `No active document`.
//! - `app.undo()` and `app.redo()` act on the active document and reach only the steps the run
//! made; with no such step they change nothing, and with no document open they throw
//! `No active document`.
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
@@ -827,6 +830,28 @@ fn app_set_active(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// `app.undo()` and `app.redo()`: `edit.undo` or `edit.redo` in the active document, which reach
/// only the steps the run made. With no step to undo or redo they change nothing.
fn app_history(h: &Host, id: &str, redo: bool) -> Answer {
let has_step = {
let s = h.session.borrow();
let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
if redo { !st.history.redo.is_empty() } else { !st.history.undo.is_empty() }
};
if has_step {
command(h, id, &json!({}))?;
}
Ok(Data::Undefined)
}
fn app_undo(h: &Host, _: &[Data]) -> Answer {
app_history(h, "edit.undo", false)
}
fn app_redo(h: &Host, _: &[Data]) -> Answer {
app_history(h, "edit.redo", true)
}
fn app_selection(h: &Host, _: &[Data]) -> Answer {
let uid = h.session.borrow().active().map(|st| st.uid);
match uid {
@@ -1746,6 +1771,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
d => vec![d],
};
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
// The ids listed so far; `ids` keeps them in the order they were first listed.
let mut seen: HashSet<NodeId> = HashSet::with_capacity(list.len());
// The document is read once for every object: nothing changes it while the list is checked.
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
@@ -2677,6 +2703,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
("redraw", method(l, app_redraw), returns("undefined", &[])),
("undo", method(l, app_undo), returns("undefined", &[])),
("redo", method(l, app_redo), returns("undefined", &[])),
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
("toString", class_text("Application"), returns("string", &[])),
]);
+2 -2
View File
@@ -1,4 +1,4 @@
//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a
//! The Scripts folder: the `.js`, `.mjs` and `.jsx` files File › Scripts lists, with each subfolder as a
//! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]).
//!
//! A listing reads names and file types only, never a script's text. It follows no link: a symbolic
@@ -279,7 +279,7 @@ pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool {
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
}
/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most
/// Is `path` a script a listing of `root` can hold now: a `.js`, `.mjs` or `.jsx` file at most
/// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there
/// and none is a link, and neither the file nor a folder below `root` is marked hidden or system?
pub fn holds(root: &Path, path: &Path) -> bool {
+166 -8
View File
@@ -37,11 +37,21 @@
//!
//! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of
//! the file it is in.
//!
//! A `.mjs` script is a module ([`module_script`]): it has no preprocessor lines, and the modules
//! it imports are read by [`Files::module`]. A specifier is a path relative to the importing
//! module's file, starting with `./` or `../` and naming a `.mjs` or `.js` file; a bare name, a URL
//! and any other form are a `SyntaxError`. Its `..` names are taken off by name, and one that would
//! lead above the script's folder is refused. Modules are read through the same [`ScriptScope`],
//! so a link that leads out of the script's folder is refused as well. Module files count against
//! the same limits as included files, and the paths of one file (two spellings, a link, or names
//! that differ only in letter case on Windows) give one module.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use vectorcraft_js::{DirectiveName, Options};
use vectorcraft_js::{DirectiveName, LoadError, Options};
use crate::file_access::{ScriptRead, ScriptScope};
@@ -219,13 +229,65 @@ pub(crate) struct Files {
frames: Vec<Frame>,
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
es2015: bool,
/// The modules a module run has read, by key ([`module_key`]): the names of the folders each
/// is in, below the script's folder.
module_dirs: HashMap<String, Vec<String>>,
/// The key of each module path read, below the script's folder.
module_paths: HashMap<String, String>,
/// The key [`Files::module_entry`] gave the script, in a module run.
entry_key: Option<String>,
}
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
/// ECMAScript 5.1 with the ExtendScript extensions.
/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text
/// run as ECMAScript 5.1 with the ExtendScript extensions.
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs"))
}
/// A script at `path` runs as a module when its file name ends in `.mjs` (in any letter case).
pub(crate) fn module_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("mjs"))
}
/// What names the file at the real path `real` among a run's modules: on Unix its device and file
/// number, so two paths to one file give one module; elsewhere its real path, which on Windows
/// spells each name in the letter case the folder stores it in, so two spellings of one file in a
/// folder that ignores case give one module and two files in a folder that does not stay two.
fn module_key(real: &Path) -> String {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let Ok(m) = std::fs::metadata(real) {
return format!("{}:{}", m.dev(), m.ino());
}
}
display(real).to_string()
}
/// The names of the folders from `root` down to `dir`, both real paths, or `None` when `dir` is
/// not `root` or below it, or has a name that is not Unicode.
fn names_below(root: &Path, dir: &Path) -> Option<Vec<String>> {
dir.strip_prefix(root).ok()?.components().map(|c| c.as_os_str().to_str().map(str::to_string)).collect()
}
/// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between
/// names and names a `.mjs` or `.js` file. A specifier in any other form is a syntax error.
fn specifier_names(specifier: &str) -> Result<Vec<&str>, LoadError> {
let wrong = |why: &str| Err(LoadError::Syntax(format!("module specifier '{specifier}' {why}")));
if !(specifier.starts_with("./") || specifier.starts_with("../")) {
return wrong("must start with './' or '../'");
}
if specifier.chars().any(|c| matches!(c, '\\' | ':' | '\0') || c.is_control()) {
return wrong("must not contain \\, : or control characters");
}
let names: Vec<&str> = specifier.split('/').collect();
let file = names.last().copied().unwrap_or_default();
let ext = Path::new(file).extension().and_then(|e| e.to_str()).unwrap_or_default();
if !(ext.eq_ignore_ascii_case("mjs") || ext.eq_ignore_ascii_case("js")) {
return wrong("must name a .mjs or .js file");
}
Ok(names)
}
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
@@ -321,9 +383,91 @@ impl Files {
levels: 0,
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
es2015: es2015_script(path),
module_dirs: HashMap::new(),
module_paths: HashMap::new(),
entry_key: None,
}
}
/// Makes the run's files read ECMAScript 2015, as a module run given as text does.
pub(crate) fn read_es2015(&mut self) {
self.es2015 = true;
}
/// The module `text`, the script's own, as a source of one file. → its key and the source.
pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> {
self.bytes = self.bytes.saturating_add(text.len());
let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default();
self.module_dirs.insert(key.clone(), Vec::new());
self.entry_key = Some(key.clone());
let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None }))
}
/// The module `specifier` names for the module `referrer` (a key [`Files::module_entry`] or
/// this function gave). → the module's key, with its text and source map the first time the
/// run reads it.
pub(crate) fn module(&mut self, referrer: &str, specifier: &str) -> Result<(String, Option<(String, SourceMap)>), LoadError> {
let names = specifier_names(specifier)?;
let mut path = self.module_dirs.get(referrer).cloned().ok_or_else(|| LoadError::Other(format!("module not found: '{referrer}'")))?;
for name in names {
match name {
"" | "." => {}
".." => {
if path.pop().is_none() {
return Err(LoadError::Other(format!("module path leads out of the script's folder: '{specifier}'")));
}
}
name => path.push(name.to_string()),
}
}
let relative = path.join("/");
if let Some(key) = self.module_paths.get(&relative) {
return Ok((key.clone(), None));
}
let root =
self.frames.first().and_then(|f| f.dir.clone()).ok_or_else(|| LoadError::Other(format!("script file read refused: {specifier}")))?;
self.probes += 1;
if self.probes > MAX_PROBES {
return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached")));
}
let candidate = path.iter().fold(root.clone(), |p, name| p.join(name));
// Another path to a module already read gives that module: the file is not read again, and
// its text is not counted again.
let loaded = &self.module_dirs;
let read = self.scope.read_unless(&candidate, crate::script::MAX_SOURCE_BYTES, |real| loaded.contains_key(&module_key(real)));
let (real, bytes) = match read {
Ok(found) => found,
Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))),
Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))),
Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))),
Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))),
};
let key = module_key(&real);
let Some(bytes) = bytes else {
self.module_paths.insert(relative, key.clone());
return Ok((key, None));
};
if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES {
return Err(LoadError::Range("script source limit reached (32 MiB)".to_string()));
}
if self.files >= MAX_FILES {
return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached")));
}
let text = decode(&bytes, specifier).map_err(LoadError::Other)?;
self.bytes += bytes.len();
self.files += 1;
self.module_paths.insert(relative, key.clone());
// The module's relative imports start from the folder the file is in, whichever path to it
// was read first; the path as written stands in when that folder is not below the script's.
path.pop();
let dir = folder_of(&real).and_then(|d| names_below(&root, &d)).unwrap_or(path);
self.module_dirs.insert(key.clone(), dir);
let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
Ok((key, Some((text, map))))
}
/// The options a file of this run is parsed with, preprocessor lines aside.
pub(crate) fn options(&self) -> Options {
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
@@ -362,12 +506,26 @@ impl Files {
self.expand(shown, dir, text, true)
}
/// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its
/// preprocessor lines read. It becomes the file being run until [`Files::end_eval`].
pub(crate) fn eval_file(&mut self, path: &str) -> Result<Expanded, Failure> {
/// The folder of the module `key` ([`Files::module`] gave it), from the script's folder.
pub(crate) fn module_dir(&self, key: &str) -> Option<PathBuf> {
let names = self.module_dirs.get(key)?;
let root = self.frames.first().and_then(|f| f.dir.clone())?;
Some(names.iter().fold(root, |p, name| p.join(name)))
}
/// The script's folder when the run is a module run ([`Files::module_entry`] read the script),
/// or `None` for a script run.
pub(crate) fn entry_module_dir(&self) -> Option<PathBuf> {
self.module_dir(self.entry_key.as_deref()?)
}
/// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder
/// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It
/// becomes the file being run until [`Files::end_eval`].
pub(crate) fn eval_file(&mut self, path: &str, module_dir: Option<PathBuf>) -> Result<Expanded, Failure> {
let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 };
let dir = self.frames.last().and_then(|f| f.dir.clone());
let dir = module_dir.or_else(|| self.frames.last().and_then(|f| f.dir.clone()));
let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?;
let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?;
let shown = display(&real);
+75 -10
View File
@@ -66,7 +66,8 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind,
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress,
Realm, RunError, RunErrorKind,
};
use crate::{
@@ -207,6 +208,8 @@ pub(crate) struct Request {
pub locale: String,
/// The answers to the dialogs of a run with nobody to ask, in order.
pub answers: Vec<DialogAnswer>,
/// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]).
pub module: bool,
/// The actions `app.doScript` can play.
pub actions: Vec<actions::Playable>,
}
@@ -784,6 +787,9 @@ struct Host {
script_map: RefCell<include::SourceMap>,
/// The same for each source `$.evalFile` gave, in order.
eval_maps: RefCell<Vec<include::SourceMap>>,
/// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a
/// module's, by its index there.
module_maps: RefCell<HashMap<usize, String>>,
/// 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)>>,
@@ -979,6 +985,22 @@ impl Host {
}
}
/// The folder of the module whose source has `tag`, when it is a module of a module run: the
/// script itself or a module it imported (not a file `$.evalFile` gave, or code from another
/// run).
fn module_dir_at(&self, tag: u32) -> Option<std::path::PathBuf> {
let script = self.script_tag.get();
if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE {
return None;
}
let n = tag.checked_sub(script)?;
if n == 0 {
return self.files.borrow().entry_module_dir();
}
let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?;
self.files.borrow().module_dir(&key)
}
/// Adds a line to the run's console and, during a slice, to the session's.
fn line(&self, entry: console::Entry, cut: bool) {
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
@@ -1596,6 +1618,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
}
}),
strict_writes: Rc::new(move || current(&strict).ok().and_then(|h| h.eval_strict.get())),
site: true,
}
};
let mut items = vec![
@@ -1610,9 +1633,17 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
}
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
/// run, with its preprocessor lines read, which the interpreter then runs. `timeout`, in
/// milliseconds, is taken and not waited on: the file is read at once.
fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError> {
/// run (for a call in a module the script imported, that module's file), with its preprocessor
/// lines read, which the interpreter then runs. `timeout`, in milliseconds, is taken and not
/// waited on: the file is read at once. `args` starts with the call's place, as
/// [`HostItem::Evaluator`] gives it with `site`.
fn eval_file(host: &Host, mut args: Vec<Data>) -> std::result::Result<Data, HostError> {
let tag = match args.first() {
Some(Data::Number(n)) if args.len() >= 3 => *n as u32,
_ => vectorcraft_js::UNKNOWN_SOURCE,
};
args.drain(..3.min(args.len()));
let module_dir = host.module_dir_at(tag);
let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else {
return Err(HostError::Type(EVAL_NO_PATH.to_string()));
};
@@ -1626,7 +1657,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
return Err(HostError::Type(EVAL_ARGUMENTS.to_string()));
}
host.charge_call(path.len() as u64 + 2)?;
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
let expanded = host.files.borrow_mut().eval_file(path, module_dir).map_err(|f| {
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
let error = match f.kind {
include::FailKind::Limit => HostError::Abort(message),
@@ -1736,6 +1767,22 @@ fn explained(e: &RunError) -> String {
}
}
/// The module `specifier` names for the module `referrer` of the run of `host`, read through the
/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order
/// the modules are read, which is the order of their sources' tags.
fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result<LoadedModule, LoadError> {
let (key, read) = host.files.borrow_mut().module(referrer, specifier)?;
let source = read.map(|(text, map)| {
let mut maps = host.eval_maps.borrow_mut();
host.module_maps.borrow_mut().insert(maps.len(), key.clone());
maps.push(map);
drop(maps);
host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::<Vec<u16>>());
text
});
Ok(LoadedModule { key, source })
}
/// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own.
fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
let (kind, message) = match f.kind {
@@ -2153,7 +2200,19 @@ impl Session {
self.script_stop.clear();
self.script_report = None;
let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env());
let expanded = files.expand_script(&request.source);
if request.module {
files.read_es2015();
}
// A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines;
// `module_key` names it among the modules it imports.
let (expanded, module_key) = if request.module {
match files.module_entry(&request.source) {
Ok((key, expanded)) => (Ok(expanded), Some(key)),
Err(f) => (Err(f), None),
}
} else {
(files.expand_script(&request.source), None)
};
let name = match &expanded {
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
_ => request.name,
@@ -2184,9 +2243,8 @@ impl Session {
// from its first run, and they act for the run that calls them.
let fresh = realm.is_none();
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
// `.js` run that names it, and keeps it as it keeps its globals.
let es2015 = include::es2015_script(request.file.as_deref());
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
let es2015 = request.module || include::es2015_script(request.file.as_deref());
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
let strict = options.strict;
// A kept engine reads each run's code the way that run's script does.
@@ -2255,6 +2313,7 @@ impl Session {
files: RefCell::new(files),
script_map: RefCell::default(),
eval_maps: RefCell::default(),
module_maps: RefCell::default(),
eval_failures: RefCell::default(),
script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE),
report_name: Arc::from(name.as_str()),
@@ -2319,7 +2378,13 @@ impl Session {
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
.and_then(|()| {
let r = realm.start(&expanded.source);
let r = match &module_key {
None => realm.start(&expanded.source),
Some(key) => {
let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH };
realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier))
}
};
// Source that does not compile defines no code, so its map is not kept.
if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) {
host.script_tag.set(realm.script_tag());
+1
View File
@@ -184,6 +184,7 @@ mod script_engines;
mod script_folder;
mod script_include;
mod script_io;
mod script_modules;
mod script_run;
mod script_scriptui;
mod script_styles;
+67
View File
@@ -399,6 +399,73 @@ fn parse_err(s: &mut Session, p: Value) -> String {
s.execute("color.parse", &p).unwrap_err().to_string()
}
/// `color.format` writes each notation, with the opacity only where it belongs, and `color.parse`
/// reads every notation but CMYK back to the same color and opacity.
#[test]
fn format_writes_each_notation_and_parse_reads_it_back() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let s = &mut s;
let fmt = |s: &mut Session, color: Value, opacity: Value, notation: &str| {
let r = s.execute("color.format", &json!({ "color": color, "opacity": opacity, "notation": notation })).unwrap();
r["text"].as_str().unwrap().to_string()
};
let blue = json!("#336699");
for (notation, at_half, at_full) in [
("hex", "#336699", "#336699"),
("hexAlpha", "#33669980", "#336699ff"),
("rgb", "rgb(51 102 153 / 50%)", "rgb(51 102 153)"),
("hsl", "hsl(210 50% 40% / 50%)", "hsl(210 50% 40%)"),
] {
assert_eq!(fmt(s, blue.clone(), json!(50), notation), at_half, "{notation}");
assert_eq!(fmt(s, blue.clone(), Value::Null, notation), at_full, "{notation}");
}
let oklch = fmt(s, blue.clone(), json!(25), "oklch");
assert!(oklch.starts_with("oklch(") && oklch.ends_with(" / 25%)"), "{oklch}");
// The working CMYK numbers through the color settings, as color.convert gives them.
let cmyk = s.execute("color.convert", &json!({ "color": "#336699", "to": "cmyk" })).unwrap();
let pct: Vec<f64> = cmyk["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect();
let expected = format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3]);
assert_eq!(expected, "C=87 M=61 Y=19 K=0", "the default color settings, as docs/mcp.md gives them");
assert_eq!(fmt(s, blue.clone(), json!(50), "cmyk"), expected);
assert_eq!(fmt(s, json!({"c": 10, "m": 20, "y": 30, "k": 0}), Value::Null, "cmyk"), "C=10 M=20 Y=30 K=0", "a CMYK color keeps its values");
assert_eq!(fmt(s, json!({"gray": 40}), Value::Null, "cmyk"), "C=0 M=0 Y=0 K=40");
for color in [json!("#336699"), json!("#0a0b0c"), json!("#ff0000"), json!("#ffffff"), json!({"c": 100, "m": 0, "y": 0, "k": 0})] {
for (notation, opacity) in [("hex", Value::Null), ("hexAlpha", json!(40)), ("rgb", json!(12.5)), ("hsl", json!(99.99)), ("oklch", json!(0))] {
let text = fmt(s, color.clone(), opacity.clone(), notation);
let shown = fmt(s, color.clone(), Value::Null, "hex");
let r = s.execute("color.parse", &json!({ "text": text })).unwrap();
assert_eq!(r["hex"], json!(shown), "{color} {notation}: {text}");
match notation {
"hex" => assert_eq!(r["opacity"], Value::Null, "{text}"),
"hexAlpha" => assert_eq!(r["opacity"], json!(40.0), "{text}"),
_ => assert_eq!(r["opacity"], opacity.as_f64().map_or(Value::Null, |o| json!(o)), "{text}"),
}
}
}
}
/// `color.format` refuses a missing or wrong color, opacity or notation.
#[test]
fn format_refuses_bad_params() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut err = |p: Value| s.execute("color.format", &p).unwrap_err().to_string();
let notation = "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk";
assert!(err(json!({"color": "#336699"})).ends_with(notation));
assert!(err(json!({"color": "#336699", "notation": "css"})).ends_with(notation));
assert!(err(json!({"color": "#336699", "notation": "HEX"})).ends_with(notation));
assert!(err(json!({"color": "#336699", "notation": 1})).ends_with("`notation` must be a string"));
assert!(err(json!({"notation": "hex"})).ends_with("missing or invalid `color`"));
assert!(err(json!({"color": "#33669980", "notation": "hex"})).ends_with("missing or invalid `color`"));
for opacity in [json!(-1), json!(101), json!("50"), json!(true)] {
assert!(
err(json!({"color": "#336699", "opacity": opacity, "notation": "rgb"})).ends_with("`opacity` must be a number from 0 to 100"),
"{opacity}"
);
}
}
#[test]
fn assign_profile_is_stored_and_undoable() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+37
View File
@@ -119,6 +119,43 @@ fn selecting_one_object_highlights_the_similar_objects_before_global_edit_starts
assert!(highlights(&s).is_empty(), "two objects selected");
}
#[test]
fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
use crate::cmd::globaledit::{FORMS_MADE, OUTLINES_MADE, highlights};
let made = || (FORMS_MADE.with(std::cell::Cell::get), OUTLINES_MADE.with(std::cell::Cell::get));
let since = |b: (usize, usize)| {
let n = made();
(n.0 - b.0, n.1 - b.1)
};
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let copies: Vec<NodeId> = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0)).collect();
sel(&mut s, &[key]);
let before = made();
assert_eq!(highlights(&s).len(), 39);
assert_eq!(since(before), (40, 39), "the first preview measures each object");
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = made();
assert_eq!(highlights(&s).len(), 39);
assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged");
sel(&mut s, &[copies[0]]);
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
sel(&mut s, &[copies[1]]);
s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap();
sel(&mut s, &[copies[2]]);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
sel(&mut s, &[key]);
let before = made();
let shown = highlights(&s);
assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar");
assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match");
let moved = node(&s, copies[1]).stroke_path().unwrap();
assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now");
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out");
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
}
#[test]
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
let mut s = session();
+333
View File
@@ -1066,6 +1066,339 @@ fn clean_up_removes_junk() {
assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none());
}
/// A path drawn by `d`, filled black with no stroke.
fn filled(s: &mut Session, d: &str) -> NodeId {
let id = NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap());
fill_only(s, id);
id
}
fn fill_only(s: &mut Session, id: NodeId) {
s.edit("t", |d, _| {
d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into();
Ok(())
})
.unwrap();
}
/// Hairline Slivers' test art: (the slivers, the shapes with a width).
fn sliver_art(s: &mut Session) -> (Vec<NodeId>, Vec<NodeId>) {
// A triangle whose third anchor lies 0.002 pt from its first: diagonal, so its bounds are wide
// and tall. A long one across the page. A compound path of two slivers.
let triangle = filled(s, "M10 10 L50 40 L10.001 10.0015 Z");
let long = filled(s, "M20 500 L780 20 L20.0005 500.001 Z");
let a = filled(s, "M300 300 L340 330 L300.001 300.0015 Z");
let b = filled(s, "M300 350 L340 380 L300.001 350.0015 Z");
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let two = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
fill_only(s, two);
// Kept: a diagonal strip 0.2 pt across (0.07 mm), a dot 0.3 pt round, a stroked sliver (it
// draws a line), an open path, and a compound path of a sliver and a square.
let strip = filled(s, "M100 100 L180 160 L180.12 159.84 L100.12 99.84 Z");
let dot = NodeId(s.execute("shape.ellipse", &json!({"x": 400, "y": 400, "width": 0.3, "height": 0.3})).unwrap()["id"].as_u64().unwrap());
fill_only(s, dot);
let stroked = filled(s, "M200 10 L240 40 L200.001 10.0015 Z");
s.edit("t", |d, _| {
d.node_mut(stroked).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 1.0).into();
Ok(())
})
.unwrap();
let open = filled(s, "M500 10 L540 40 L500.001 10.0015");
let c = filled(s, "M600 300 L640 330 L600.001 300.0015 Z");
let square = filled(s, "M600 400 L620 400 L620 420 L600 420 Z");
s.execute("select.set", &json!({"ids": [c.0, square.0]})).unwrap();
let mixed = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
fill_only(s, mixed);
s.execute("select.none", &json!({})).unwrap();
(vec![triangle, long, two], vec![strip, dot, stroked, open, mixed])
}
#[test]
fn clean_up_removes_hairline_slivers_and_keeps_shapes_with_a_width() {
let mut s = session();
let (slivers, kept) = sliver_art(&mut s);
// Off by default.
assert_eq!(s.execute("object.path.cleanUp", &json!({})).unwrap()["removed"], 0);
// A sliver with no fill and no stroke is Unpainted Objects' to remove, and one whose fill is
// at 0 % opacity paints nothing either.
let unpainted = filled(&mut s, "M700 10 L740 40 L700.001 10.0015 Z");
let clear = filled(&mut s, "M700 60 L740 90 L700.001 60.0015 Z");
s.edit("t", |d, _| {
d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
let mut a = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0);
if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = a.items.first_mut() {
f.opacity = 0.0;
}
d.node_mut(clear).unwrap().appearance = a.into();
Ok(())
})
.unwrap();
let kept = [kept, vec![unpainted, clear]].concat();
let undo = s.doc().unwrap().history.undo.len();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let r = s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(slivers.iter().all(|id| d.node(*id).is_none()), "slivers left");
for (k, id) in kept.iter().enumerate() {
assert!(d.node(*id).is_some(), "shape {k} with a width went");
}
assert_eq!(r["removed"], slivers.len());
// One undo step brings every sliver back.
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(slivers.iter().all(|id| s.doc().unwrap().doc.node(*id).is_some()));
// A wider width (0.255 pt) takes the 0.2 pt strip too, and still keeps the dot.
let wide = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": "0.09 mm"});
assert_eq!(s.execute("object.path.cleanUp", &wide).unwrap()["removed"], slivers.len() + 1);
assert!(s.doc().unwrap().doc.node(kept[0]).is_none() && s.doc().unwrap().doc.node(kept[1]).is_some());
}
/// Select › Object › Hairline Slivers selects what Clean Up removes, and neither takes hidden or
/// locked slivers.
#[test]
fn select_hairline_slivers_selects_what_clean_up_removes() {
let mut s = session();
let (slivers, _) = sliver_art(&mut s);
let hidden = filled(&mut s, "M10 200 L50 230 L10.001 200.0015 Z");
let locked = filled(&mut s, "M10 250 L50 280 L10.001 250.0015 Z");
s.edit("t", |d, _| {
d.node_mut(hidden).unwrap().visible = false;
d.node_mut(locked).unwrap().locked = true;
Ok(())
})
.unwrap();
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert_eq!(r["count"], slivers.len());
let mut selected: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
selected.sort_unstable();
let mut want = slivers.clone();
want.sort_unstable();
assert_eq!(selected, want);
// Inside an isolated group, only the slivers in it are selected.
let inner = filled(&mut s, "M10 300 L50 330 L10.001 300.0015 Z");
let square = filled(&mut s, "M100 300 L120 300 L120 320 L100 320 Z");
s.execute("select.set", &json!({"ids": [inner.0, square.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
// A sliver in a group is selected as Clean Up finds it.
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], slivers.len() + 1);
assert!(s.doc().unwrap().selection.objects.contains(&inner));
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![inner]);
s.execute("object.exitIsolation", &json!({})).unwrap();
// A template layer that was unlocked afterward.
let template = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let traced = filled(&mut s, "M10 350 L50 380 L10.001 350.0015 Z");
s.edit("t", |d, _| {
let n = d.node_mut(template).unwrap();
if let NodeKind::Layer { template, .. } = &mut n.kind {
*template = true;
}
n.locked = false;
Ok(())
})
.unwrap();
assert!(s.doc().unwrap().doc.node(template).unwrap().is_template());
s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert!(!s.doc().unwrap().selection.objects.contains(&traced));
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(hidden).is_some() && d.node(locked).is_some() && d.node(traced).is_some());
}
/// Hairline Slivers leaves alone a sliver with an effect on its fill, the members of a Live Paint
/// group and of type's glyph outlines, a sliver that its group's stroke draws along, and a layer's
/// clipping path; Clean Up's other options keep the layer's clipping path too.
#[test]
fn hairline_slivers_leave_effects_live_paint_and_clipping_layers_alone() {
let mut s = session();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let rough = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
s.execute("select.set", &json!({"ids": [rough.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 0})).unwrap();
let a = filled(&mut s, "M100 100 L140 130 L100.001 100.0015 Z");
let square = filled(&mut s, "M90 90 L150 90 L150 150 L90 150 Z");
s.execute("select.set", &json!({"ids": [a.0, square.0]})).unwrap();
s.execute("livePaint.make", &json!({})).unwrap();
// A group's own 5 pt stroke draws along its member.
let member = filled(&mut s, "M200 200 L240 230 L200.001 200.0015 Z");
s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(group).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 5.0).into();
Ok(())
})
.unwrap();
// A thin part of type's glyph outlines.
let glyph = filled(&mut s, "M300 200 L340 230 L300.001 200.0015 Z");
s.execute("select.set", &json!({"ids": [glyph.0]})).unwrap();
let outlines = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(outlines).unwrap().extras_mut().type_outlines = true;
Ok(())
})
.unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
// A layer clipped by a thin compound path: neither Hairline Slivers nor Unpainted Objects
// removes the clipping path.
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
filled(&mut s, "M300 300 L400 300 L400 400 L300 400 Z");
let b = filled(&mut s, "M300 300 L340 330 L300.001 300.0015 Z");
let c = filled(&mut s, "M300 350 L340 380 L300.001 350.0015 Z");
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
let clip = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
assert!(s.doc().unwrap().doc.node(clip).is_some(), "the layer's clipping path went");
// A clip group whose clipping path is a sliver.
let art = filled(&mut s, "M300 500 L400 500 L400 600 L300 600 Z");
let mask = filled(&mut s, "M300 500 L340 530 L300.001 500.0015 Z");
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
// A guide drawn as a sliver, and a sliver with an effect on its stroke.
let guide = filled(&mut s, "M400 10 L440 40 L400.001 10.0015 Z");
let stroke_fx = filled(&mut s, "M450 10 L490 40 L450.001 10.0015 Z");
s.edit("t", |d, _| {
if let NodeKind::Path { guide, .. } = &mut d.node_mut(guide).unwrap().kind {
*guide = true;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [stroke_fx.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 1})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(mask).is_some(), "the clip group's clipping path went");
assert!(d.node(guide).is_some() && d.node(stroke_fx).is_some(), "a guide or a sliver with a stroke effect went");
// A layer clipped by a group (as an opened file can have it): its sliver member clips too.
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
filled(&mut s, "M500 500 L600 500 L600 600 L500 600 Z");
let bare = filled(&mut s, "M500 500 L540 530 L500.001 500.0015 Z");
s.execute("select.set", &json!({"ids": [bare.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
if let NodeKind::Layer { clip, children, .. } = &mut d.node_mut(layer).unwrap().kind {
*clip = true;
let i = children.iter().position(|c| c.id == g).unwrap();
let c = children.remove(i);
children.insert(0, c);
}
Ok(())
})
.unwrap();
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
assert!(s.doc().unwrap().doc.node(bare).is_some(), "the clipping group's member went");
}
/// A sliver on a locked artboard is left alone.
#[test]
fn hairline_slivers_leave_art_on_a_locked_artboard_alone() {
let mut s = session();
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
s.edit("t", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
assert!(s.doc().unwrap().doc.node(sliver).is_some());
}
/// A sliver at 0 % opacity, and one in a group at 0 % opacity, paint nothing and are left alone.
#[test]
fn hairline_slivers_leave_art_at_zero_opacity_alone() {
let mut s = session();
let clear = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
let member = filled(&mut s, "M100 10 L140 40 L100.001 10.0015 Z");
s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let seen = filled(&mut s, "M200 10 L240 40 L200.001 10.0015 Z");
s.edit("t", |d, _| {
d.node_mut(clear).unwrap().opacity = 0.0;
d.node_mut(group).unwrap().opacity = 0.0;
d.node_mut(seen).unwrap().opacity = 0.5;
Ok(())
})
.unwrap();
s.execute("select.none", &json!({})).unwrap();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 1);
let d = &s.doc().unwrap().doc;
assert!(d.node(clear).is_some() && d.node(member).is_some(), "a sliver at 0 % opacity went");
assert!(d.node(seen).is_none(), "a sliver at 50 % opacity stayed");
}
/// A shape too complex to measure is kept, and both commands say how many there were.
#[test]
fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() {
let mut s = session();
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
// A closed zigzag of more anchors than one shape is measured with.
let n = vectorcraft_pathops::MAX_THICKNESS_PIECES + 1;
let anchors = (0..n).map(|k| vectorcraft_geom::Anchor::corner(kurbo::Point::new(100.0 + k as f64 * 0.001, 100.0 + (k % 2) as f64))).collect();
let huge = filled(&mut s, "M100 100 L110 100 L110 110 Z");
s.edit("t", |d, _| {
if let NodeKind::Path { path, .. } = &mut d.node_mut(huge).unwrap().kind {
*path = PathData::single(vectorcraft_geom::SubPath::new(anchors, true));
}
Ok(())
})
.unwrap();
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert_eq!(r["count"], 1);
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let r = s.execute("object.path.cleanUp", &only).unwrap();
assert_eq!(r["removed"], 1);
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
let d = &s.doc().unwrap().doc;
assert!(d.node(sliver).is_none() && d.node(huge).is_some());
}
/// The width of Hairline Slivers is refused outside 0.001 to 3 pt, or when it is no number, and the
/// document, the selection and the undo history stay as they were.
#[test]
fn hairline_slivers_refuse_a_width_out_of_range() {
let mut s = session();
sliver_art(&mut s);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.selection.objects.clone(), st.history.undo.len())
};
let before = state(&s);
for w in [json!(0), json!(-1), json!(0.0005), json!(3.5), json!("thin"), json!(true)] {
for (cmd, key) in [("object.path.cleanUp", "sliverWidth"), ("select.object.hairlineSlivers", "width")] {
let mut p = serde_json::Map::new();
p.insert(key.into(), w.clone());
if cmd == "object.path.cleanUp" {
p.insert("hairlineSlivers".into(), json!(true));
}
let r = s.execute(cmd, &Value::Object(p));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(key)), "{cmd} {w}: {r:?}");
assert!(state(&s) == before, "{cmd} {w} changed the document");
}
}
// Both ends of the range are taken.
for w in [json!(0.001), json!(3), json!("3 pt")] {
assert!(s.execute("select.object.hairlineSlivers", &json!({ "width": w })).is_ok(), "{w}");
let p = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": w});
assert!(s.execute("object.path.cleanUp", &p).is_ok(), "{w}");
}
}
/// A page-sized square under a ring (a compound path with a square hole), nothing selected.
fn art_and_ring(s: &mut Session) -> (NodeId, NodeId) {
let art = rect(s, 0.0, 0.0, 100.0, 100.0);
+13
View File
@@ -3195,6 +3195,19 @@ fn a_heavy_filter_installs_once_the_user_agrees() {
assert!(install(&mut s, DESATURATE).get("budget").is_none());
}
/// The refusal of a heavy filter names it as prompts show text: a right-to-left override in its
/// name is escaped, so it can't reorder the message around it.
#[test]
fn a_heavy_filter_refusal_escapes_its_name() {
let mut s = session();
// The override as a JSON escape in the manifest.
let rlo = format!("\\u{:04X}", 0x202E);
let manifest = format!(r#"{{"id":"test.engine.heavy.name","name":"Route{rlo}txt.exe","version":"1","kind":"filter","budget":"heavy"}}"#);
let module = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap();
let e = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap_err().to_string();
assert!(e.contains("“Route\\u{202E}txt.exe” asks for a heavy budget"), "{e}");
}
/// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed
/// without any of its code running: its start function traps and its `vc_manifest` export loops.
#[test]
+31
View File
@@ -356,6 +356,37 @@ fn page_item_properties_join_one_undo_step() {
}
}
/// `app.undo()` and `app.redo()` step through the run's own edits, and the run still ends as one
/// undo step. They change nothing past the run's first edit or its last undone one.
#[test]
fn app_undo_and_redo_step_through_the_runs_edits() {
let (mut s, a, b) = doc();
let steps = undo_steps(&s);
let out = log(
&mut s,
"var d = app.activeDocument; var i = d.pageItems[0]; var unnamed = i.name;\
app.undo(); app.redo();\
i.name = 'first'; i.opacity = 40;\
app.undo(); vc.log([i.name, i.opacity]);\
app.redo(); vc.log(i.opacity);\
app.redo(); vc.log(i.opacity);\
app.undo(); app.undo(); app.undo(); vc.log([i.name === unnamed, i.opacity]);\
vc.log(typeof app.undo());\
d.pageItems[1].name = 'kept';",
);
assert_eq!(out, vec![json!(["first", 100]), json!(40), json!(40), json!([true, 100]), json!("undefined")]);
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
let st = s.active().unwrap();
let names: Vec<_> = [a, b].iter().map(|id| st.doc.node(*id).unwrap().name.clone()).collect();
assert!(names.contains(&Some("kept".to_string())) && !names.contains(&Some("first".to_string())), "{names:?}");
s.execute("edit.undo", &json!({})).unwrap();
let st = s.active().unwrap();
assert!(st.doc.node(a).is_some_and(|n| n.name.is_none()) && st.doc.node(b).is_some_and(|n| n.name.is_none()), "undoing the run");
let mut s = Session::new();
assert!(failure(&mut s, "app.undo();").contains("No active document"));
assert!(failure(&mut s, "app.redo();").contains("No active document"));
}
/// An opacity a graph mark already has still replaces the opacity another mark of its series left on
/// the graph, as `object.setProps` does.
#[test]
+1
View File
@@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
fuel: script::DEFAULT_FUEL,
locale: "en_US".into(),
answers: Vec::new(),
module: false,
actions: Vec::new(),
};
s.script_start(request).unwrap();
+315
View File
@@ -0,0 +1,315 @@
//! `.mjs` scripts: modules, the modules they import from the script's folder, the refusals of
//! specifiers and paths, the run's limits, and errors at the file they are in.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::*;
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-modules-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
base
}
fn write(path: &Path, text: &str) {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).unwrap();
}
std::fs::write(path, text).unwrap();
}
/// Runs `main/<file>` in `base`, with the text `text`.
fn run_file(base: &Path, file: &str, text: &str) -> (Result<Value>, Session) {
let main = base.join("main").join(file);
write(&main, text);
let mut s = Session::new();
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()}));
(r, s)
}
fn run(base: &Path, text: &str) -> Result<Value> {
run_file(base, "main.mjs", text).0
}
/// The report of the run of `main/main.mjs` that failed.
fn failed(base: &Path, text: &str) -> Value {
let (r, s) = run_file(base, "main.mjs", text);
assert!(r.is_err(), "the run failed: {r:?}");
s.script_report().unwrap().clone()
}
fn message(report: &Value) -> &str {
report["message"].as_str().unwrap_or_default()
}
#[test]
fn script_module_imports_from_its_folder_and_below() {
let base = folder("imports");
write(&base.join("main/lib/count.mjs"), "export let n = 0;\nexport function inc() { n++; }\nexport default 'lib';");
write(
&base.join("main/lib/use.mjs"),
"import { inc } from './count.mjs';\nimport name from '../lib/count.mjs';\nexport const used = name;\ninc();",
);
let text = "import { n, inc } from './lib/count.mjs';\nimport { used } from './lib/use.mjs';\ninc();\nvc.log([n, used, this === undefined, /main\\.mjs$/.test($.fileName)]);";
let r = run(&base, text).unwrap();
// count.mjs ran once: use.mjs and the script share its binding.
assert_eq!(r["log"], json!([[2, "lib", true, true]]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_two_modules_import_each_other() {
let base = folder("cycle");
write(&base.join("main/a.mjs"), "import { b } from './b.mjs';\nexport function a() { return 'a' + b(); }");
write(&base.join("main/b.mjs"), "import { a } from './a.mjs';\nexport function b() { return 'b'; }\nexport const viaA = () => a();");
let r = run(&base, "import { a } from './a.mjs';\nimport { viaA } from './b.mjs';\nvc.log([a(), viaA()]);").unwrap();
assert_eq!(r["log"], json!([["ab", "ab"]]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_path_above_the_script_folder_is_refused() {
let base = folder("above");
write(&base.join("outside.mjs"), "export var leaked = 1;");
let report = failed(&base, "vc.log(1);\nimport { leaked } from '../outside.mjs';");
assert!(message(&report).contains("module path leads out of the script's folder: '../outside.mjs'"), "{report}");
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(2), json!([])), "{report}");
// `..` names that stay inside are read by name.
write(&base.join("main/sub/x.mjs"), "export var x = 'x';");
let r = run(&base, "import { x } from './sub/../sub/./x.mjs';\nvc.log(x);").unwrap();
assert_eq!(r["log"], json!(["x"]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_missing_file_is_named() {
let base = folder("missing");
write(&base.join("main/a.mjs"), "import './nope.mjs';");
let report = failed(&base, "import './a.mjs';");
assert!(message(&report).contains("module file not found: ./nope.mjs"), "{report}");
assert!(report["file"].as_str().unwrap().ends_with("a.mjs"), "{report}");
assert_eq!(report["line"], 1);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_specifiers_other_than_relative_paths_are_syntax_errors() {
let base = folder("specifiers");
// The specifier as the script writes it, as the error names it, and why it is refused.
for (written, shown, why) in [
("lib", "lib", "must start with './' or '../'"),
("lib/x.mjs", "lib/x.mjs", "must start with './' or '../'"),
("https://example.com/x.mjs", "https://example.com/x.mjs", "must start with './' or '../'"),
("/abs/x.mjs", "/abs/x.mjs", "must start with './' or '../'"),
("./C:x.mjs", "./C:x.mjs", "must not contain"),
("./a\\u005cb.mjs", "./a\\b.mjs", "must not contain"),
("./x.txt", "./x.txt", "must name a .mjs or .js file"),
("./x", "./x", "must name a .mjs or .js file"),
] {
let report = failed(&base, &format!("import '{written}';"));
let expected = format!("SyntaxError: module specifier '{shown}' {why}");
assert!(message(&report).starts_with(&expected), "{written}: {report}");
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_errors_are_at_the_file_they_are_in() {
let base = folder("errors");
write(&base.join("main/bad.mjs"), "export var a = 1;\nexport var = 2;");
let report = failed(&base, "import { a } from './bad.mjs';");
assert_eq!(report["kind"], "syntax", "{report}");
assert!(report["file"].as_str().unwrap().ends_with("bad.mjs"), "{report}");
assert_eq!(report["line"], 2);
write(&base.join("main/thrower.mjs"), "export var a = 1;\n\nthrow new Error('from thrower');");
let report = failed(&base, "import { a } from './thrower.mjs';\nvc.log(a);");
assert!(report["file"].as_str().unwrap().ends_with("thrower.mjs"), "{report}");
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(3), json!([])), "{report}");
let report = failed(&base, "import { b } from './thrower.mjs';");
assert!(message(&report).contains("the module './thrower.mjs' has no export named 'b'"), "{report}");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_preprocessor_lines_and_scripts_differ_by_extension() {
let base = folder("kinds");
write(&base.join("main/lib.jsxinc"), "var included = 1;");
// A module has no preprocessor lines.
let report = failed(&base, "#include \"lib.jsxinc\"\n");
assert_eq!(report["kind"], "syntax", "{report}");
// A .js or .jsx script does not read import or export.
for file in ["main.js", "main.jsx"] {
let (r, s) = run_file(&base, file, "import { a } from './a.mjs';");
assert!(r.is_err(), "{file}");
assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{file}");
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_files_count_against_the_include_limits() {
let base = folder("limits");
for i in 0..70 {
write(&base.join(format!("main/m{i}.mjs")), &format!("import './m{}.mjs';", i + 1));
}
let report = failed(&base, "import './m0.mjs';");
assert!(message(&report).contains("limit"), "{report}");
assert_eq!(report["log"], json!([]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_paths_of_one_file_give_one_module() {
let base = folder("same");
write(&base.join("main/once.mjs"), "vc.log('ran');\nexport var v = 1;");
let mut text = "import { v } from './once.mjs';\nimport { v as w } from './sub/../once.mjs';\n".to_string();
// Windows file names ignore letter case.
if cfg!(windows) {
text.push_str("import { v as u } from './ONCE.mjs';\n");
}
let r = run(&base, &text).unwrap();
assert_eq!(r["log"], json!(["ran"]));
let _ = std::fs::remove_dir_all(base);
}
/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere.
/// `false` when the system does not allow it here.
fn link_folder(target: &Path, link: &Path) -> bool {
#[cfg(windows)]
{
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success());
made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok()
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, link).is_ok()
}
#[cfg(not(any(unix, windows)))]
{
let _ = (target, link);
false
}
}
#[test]
fn script_module_link_out_of_the_folder_is_refused() {
let base = folder("link");
write(&base.join("outside/x.mjs"), "export var leaked = 1;");
if !link_folder(&base.join("outside"), &base.join("main").join("away")) {
eprintln!("skipped: a folder link can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let report = failed(&base, "import { leaked } from './away/x.mjs';\nvc.log(leaked);");
assert!(message(&report).contains("script file read refused: ./away/x.mjs"), "{report}");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_is_listed_and_taken_by_path() {
assert!(cmd::scripts::runs("tool.MJS"));
let base = folder("text");
let root = base.join("Scripts");
write(&root.join("tool.mjs"), "export var a = 1;");
let mut s = Session::new();
s.attach_scripts_dir(root.clone());
let listed = s.execute("script.listInstalled", &json!({})).unwrap();
assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}]));
// A script given as text is not a module, whatever its name.
let mut s = Session::new();
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"}));
assert!(r.is_err());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_is_chosen_by_the_module_param() {
let mut s = Session::new();
let r = s.execute("script.run", &json!({"source": "export var a = 1;\nvc.log([a, this === undefined]);", "module": true})).unwrap();
assert_eq!(r["log"], json!([[1, true]]));
// A source run as a module imports no files.
let r = s.execute("script.run", &json!({"source": "import { b } from './b.mjs';", "module": true}));
assert!(r.is_err());
assert!(message(s.script_report().unwrap()).contains("./b.mjs"), "{:?}", s.script_report());
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "module": "yes"}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
// `module: false` runs a .mjs file as a script, where `export` is a syntax error.
let base = folder("param");
let main = base.join("main").join("main.mjs");
write(&main, "export var a = 1;");
let r = s.execute("script.run", &json!({"path": main.to_string_lossy(), "module": false}));
assert!(r.is_err());
assert_eq!(s.script_report().unwrap()["kind"], "syntax");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_read_again_through_another_path_is_not_counted_again() {
let base = folder("budget");
// 7 MiB, under the 8 MiB a file may have; five reads of it would pass the 32 MiB of a run.
let big = format!("export var v = 1;\n//{}", "x".repeat(7 * 1024 * 1024));
write(&base.join("main/lib/big.mjs"), &big);
let mut text = String::new();
for i in 0..5 {
if !link_folder(&base.join("main/lib"), &base.join(format!("main/l{i}"))) {
eprintln!("skipped: a folder link can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
text.push_str(&format!("import {{ v as v{i} }} from './l{i}/big.mjs';\n"));
}
text.push_str("vc.log(v0 + v4);");
let r = run(&base, &text);
assert_eq!(r.map(|r| r["log"].clone()).ok(), Some(json!([2])));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_imports_are_read_from_the_folder_the_file_is_in() {
let base = folder("realdir");
write(&base.join("main/real/user.mjs"), "import { d } from './dep.mjs';\nexport const got = d;");
write(&base.join("main/real/dep.mjs"), "export const d = 'real';");
write(&base.join("main/other/dep.mjs"), "export const d = 'other';");
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
#[cfg(not(any(unix, windows)))]
let linked = false;
if !linked {
eprintln!("skipped: a file link can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let r = run(&base, "import { got } from './other/user.mjs';\nvc.log(got);").unwrap();
assert_eq!(r["log"], json!(["real"]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_eval_file_reads_beside_the_module_that_calls_it() {
let base = folder("evalfile");
write(&base.join("main/helper.jsx"), "'top'");
write(&base.join("main/sub/helper.jsx"), "'sub'");
write(&base.join("main/sub/m.mjs"), "export const got = $.evalFile('helper.jsx');");
let r = run(&base, "import { got } from './sub/m.mjs';\nvc.log([got, $.evalFile('helper.jsx')]);").unwrap();
assert_eq!(r["log"], json!([["sub", "top"]]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_module_function_of_the_script_reads_beside_the_script_when_another_file_calls_it() {
let base = folder("evalfile-entry");
write(&base.join("main/helper.jsx"), "'top'");
write(&base.join("main/sub/helper.jsx"), "'sub'");
// The file in `sub` calls the script's function while it is the file being run.
write(&base.join("main/sub/caller.jsx"), "$.global.load()");
let text = "$.global.load = function () { return $.evalFile('helper.jsx'); };\nvc.log($.evalFile('sub/caller.jsx'));";
let r = run(&base, text).unwrap();
assert_eq!(r["log"], json!(["top"]));
let _ = std::fs::remove_dir_all(base);
}
+39
View File
@@ -1248,6 +1248,45 @@ fn color_parse_takes_oklch_only_in_an_srgb_working_space() {
assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again");
}
/// `color.format` writes `oklch()` only while the working RGB space is sRGB, and writes every CSS
/// form of a CMYK color from the RGB numbers the rendering intent gives, so `color.parse` reads each
/// back to the hex color `color.format` gives.
#[test]
fn color_format_writes_every_css_form_through_the_intent() {
let _g = settings();
let old = cms::active_settings();
let mut s = session();
let format = |s: &mut Session, color: &serde_json::Value, notation: &str| {
s.execute("color.format", &json!({"color": color, "notation": notation})).map(|r| r["text"].as_str().unwrap_or_default().to_string())
};
s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap();
let wide = format(&mut s, &json!("#336699"), "oklch").map_err(|e| e.to_string());
// The Generic CMYK profile's file loaded as an ICC profile, which converts through the intent.
let icc = cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some("Format Intent CMYK".into())).unwrap().name;
s.execute("edit.colorSettings", &json!({"rgb": cms::SRGB, "cmyk": icc, "intent": "absolute"})).unwrap();
let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0});
let absolute = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8);
let intents_differ =
absolute != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8);
// Collected as results, so that a failure still restores the process-wide settings first.
let mut read_back = vec![];
for notation in ["hex", "rgb", "hsl", "oklch"] {
let text = format(&mut s, &cyan, notation).map_err(|e| e.to_string());
let hex = text.clone().and_then(|t| s.execute("color.parse", &json!({"text": t})).map(|r| r["hex"].clone()).map_err(|e| e.to_string()));
read_back.push((notation, text, hex));
}
cms::set_active(&old).unwrap();
cms::unregister_icc(&icc);
assert!(wide.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{wide:?}");
assert!(intents_differ, "absolute and relative colorimetric give cyan the same RGB");
let hex = read_back[0].1.clone().unwrap();
let [r, g, b] = absolute;
assert_eq!(hex, format!("#{r:02x}{g:02x}{b:02x}"), "hex is the absolute colorimetric RGB");
for (notation, text, back) in read_back {
assert_eq!(back, Ok(json!(hex)), "{notation}: {text:?}");
}
}
/// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in
/// `Color Settings.json`.
#[test]
@@ -90,8 +90,8 @@ const INSIDE: &[(&str, &str)] = &[
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \
unloadAction unloadAction=",
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= textFonts toString typename \
undo unloadAction unloadAction=",
),
("DocumentPreset.", "prototype"),
(
+1 -1
View File
@@ -118,7 +118,7 @@ fn a_script_refused_before_it_runs_has_not_started() {
let r = result(&mut session(), &json!({"path": "notes.txt", "maxFuel": FUEL, "answers": []}));
assert_eq!(r["started"], false);
assert_eq!(r["ok"], false);
assert!(r["message"].as_str().unwrap().contains(".js or .jsx"), "{r}");
assert!(r["message"].as_str().unwrap().contains(".js, .mjs or .jsx"), "{r}");
}
#[test]
+56
View File
@@ -619,6 +619,62 @@ pub struct Program {
pub(crate) supers: crate::parser::SuperRules,
}
/// The name an import takes from the module it names, or an export from a module it re-exports.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ImportName {
/// The export of this name (`default` for a default import).
Name(String),
/// The module's namespace object (`* as ns`).
Namespace,
}
/// A module a module imports or re-exports from: the specifier as written and where it stands.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ModuleRequest {
/// The specifier as text, with each unpaired surrogate written as U+FFFD.
pub specifier: String,
/// The specifier's string value, code unit for code unit (ECMA-262 2015 section 15.2.1.16,
/// ModuleRequests). It may hold an unpaired surrogate, which no host path can name.
pub units: Vec<u16>,
pub span: Span,
}
/// One name an import declaration binds (ECMA-262 2015 section 15.2.1.16, ImportEntry).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImportEntry {
/// The index of the module in [`ModuleInfo::requests`].
pub request: usize,
pub import: ImportName,
/// The name bound in the importing module.
pub local: Name,
}
/// One name a module exports (ExportEntry).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExportEntry {
/// `export_name` is the module's own binding `local` (`*default*` for a default export of an
/// expression or an anonymous function).
Local { export_name: String, local: String, span: Span },
/// `export_name` is the export `import` of the module `request` (`export { a as b } from`,
/// `export * as ns from`, or an exported import).
Indirect { export_name: String, request: usize, import: ImportName, span: Span },
/// Every export of the module `request` but `default` (`export * from`).
Star { request: usize, span: Span },
}
/// What a module imports and exports, read by [`crate::parse_module`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ModuleInfo {
/// The modules it names, each specifier once, in the order they first appear.
pub requests: Vec<ModuleRequest>,
pub imports: Vec<ImportEntry>,
pub exports: Vec<ExportEntry>,
}
/// The binding name of a default export that has no name of its own (ECMA-262 2015 section
/// 15.2.3.5); no identifier can name it.
pub const DEFAULT_BINDING: &str = "*default*";
impl Program {
/// The line and column (both from 1, the column in UTF-16 code units) of a source offset.
pub fn line_column(&self, offset: u32) -> (u32, u32) {
+2 -2
View File
@@ -591,7 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let k = interp.to_prop_key(&arg(args, 0))?;
let o = interp.to_object(&this)?;
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
}
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
@@ -610,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let k = interp.to_prop_key(&arg(args, 0))?;
let o = interp.to_object(&this)?;
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
}
// ---- Function ----
+3 -3
View File
@@ -139,7 +139,7 @@ fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _:
let o = interp.to_object(&arg(args, 0))?;
interp.rooted(&[Value::Object(o)], |interp| {
let k = interp.to_prop_key(&arg(args, 1))?;
match interp.get_own_pk(o, &k)? {
match interp.own_pk(o, &k)? {
Some(p) => from_prop(interp, &p),
None => Ok(Value::Undefined),
}
@@ -282,7 +282,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult<Value> {
let o = *o;
for k in own_prop_keys(interp, o)? {
interp.use_fuel()?;
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
let Some(prop) = interp.own_pk(o, &k)? else { continue };
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
return Ok(Value::Bool(false));
}
@@ -311,7 +311,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Valu
let mut names = Vec::new();
for k in interp.own_keys(o)? {
interp.use_fuel()?;
if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
if interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
names.push(k);
}
}
+67 -23
View File
@@ -98,6 +98,8 @@ struct FnCompiler<'a> {
recursion: u32,
/// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own.
es2015: bool,
/// The code is a module's ([`compile_module`]), which has no completion value.
module: bool,
scopes: Vec<BlockScope>,
templates: Vec<Template>,
uses_this: bool,
@@ -156,6 +158,7 @@ impl<'a> FnCompiler<'a> {
uses_arguments: false,
recursion,
es2015: false,
module: false,
scopes: Vec::new(),
templates: Vec::new(),
uses_this: false,
@@ -169,6 +172,12 @@ impl<'a> FnCompiler<'a> {
}
}
/// Script and eval code keep the value of the last expression statement as their
/// completion value; function and module code do not.
fn keeps_completion(&self) -> bool {
self.kind != CodeKind::Function && !self.module
}
// ---- emitting ----
fn emit(&mut self, op: Op) {
@@ -270,8 +279,10 @@ impl<'a> FnCompiler<'a> {
let mut seen = HashSet::new();
// The `let` and `const` names and the block functions of each statement list and loop the
// walk enters, with the index of the one around it; the body's are first, and its
// functions are var-scoped.
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, self.lexical_names(body), HashSet::new())];
// functions are var-scoped. Only Annex B's block functions read them, so without
// [`crate::Options::es2015`] none is collected.
let top = if self.es2015 { self.lexical_names(body) } else { HashSet::new() };
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, top, HashSet::new())];
let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect();
let mut add_var = |out: &mut Hoisted, k: Key| {
if seen.insert(k.clone()) {
@@ -306,7 +317,7 @@ impl<'a> FnCompiler<'a> {
}
}
Stmt::Block(list) => {
let s = enter(self.lexical_names(list), self.block_function_names(list));
let s = if inner { enter(self.lexical_names(list), self.block_function_names(list)) } else { scope };
work.extend(list.iter().rev().map(|&st| (st, nested || inner, s)));
}
Stmt::If { consequent, alternate, .. } => {
@@ -314,7 +325,7 @@ impl<'a> FnCompiler<'a> {
// (Annex B.3.4).
for &branch in alternate.iter().chain(std::iter::once(consequent)) {
let alone = matches!(self.ast.stmt(branch), Some(Stmt::FunctionDecl(_)));
let s = if alone { enter(HashSet::new(), HashSet::new()) } else { scope };
let s = if alone && inner { enter(HashSet::new(), HashSet::new()) } else { scope };
work.push((branch, nested || inner, s));
}
}
@@ -347,30 +358,38 @@ impl<'a> FnCompiler<'a> {
work.push((*body, nested || inner, s));
}
Stmt::Switch { cases, .. } => {
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
let s = enter(names, funcs);
let s = if inner {
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
enter(names, funcs)
} else {
scope
};
for case in cases.iter().rev() {
work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s)));
}
}
Stmt::Try { block, handler, finalizer } => {
if let Some(f) = finalizer {
let s = enter(self.lexical_names(f), self.block_function_names(f));
let s = if inner { enter(self.lexical_names(f), self.block_function_names(f)) } else { scope };
work.extend(f.iter().rev().map(|&st| (st, nested || inner, s)));
}
if let Some(h) = handler {
// A `var` cannot redeclare a destructured catch parameter's names
// (ECMA-262 11th edition section B.3.5), so a block function of that name
// in the body is not also made a `var` (section B.3.3).
let mut names = self.lexical_names(&h.body);
if matches!(h.param, Binding::Pattern(_)) {
names.extend(self.bound_keys(&h.param));
}
let s = enter(names, self.block_function_names(&h.body));
let s = if inner {
// A `var` cannot redeclare a destructured catch parameter's names
// (ECMA-262 11th edition section B.3.5), so a block function of that
// name in the body is not also made a `var` (section B.3.3).
let mut names = self.lexical_names(&h.body);
if matches!(h.param, Binding::Pattern(_)) {
names.extend(self.bound_keys(&h.param));
}
enter(names, self.block_function_names(&h.body))
} else {
scope
};
work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s)));
}
let s = enter(self.lexical_names(block), self.block_function_names(block));
let s = if inner { enter(self.lexical_names(block), self.block_function_names(block)) } else { scope };
work.extend(block.iter().rev().map(|&st| (st, nested || inner, s)));
}
Stmt::Expr(_)
@@ -493,7 +512,10 @@ impl<'a> FnCompiler<'a> {
fn lexical_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
for d in decls {
match (d.init, &d.target) {
(Some(init), Binding::Name(name)) => self.named_expr(init, &name.name)?,
(Some(init), Binding::Name(name)) => {
let public_name = if name.name == crate::ast::DEFAULT_BINDING { "default" } else { &name.name };
self.named_expr(init, public_name)?;
}
(Some(init), Binding::Pattern(_)) => self.expr(init)?,
(None, Binding::Name(_)) => self.emit(Op::Undefined),
(None, Binding::Pattern(_)) => return internal("a destructuring declaration without an initializer"),
@@ -552,7 +574,7 @@ impl<'a> FnCompiler<'a> {
Stmt::Empty | Stmt::Debugger => Ok(()),
Stmt::Expr(e) => {
self.expr(*e)?;
self.emit(if self.kind == CodeKind::Function { Op::Pop } else { Op::SetCompletion });
self.emit(if self.keeps_completion() { Op::SetCompletion } else { Op::Pop });
Ok(())
}
Stmt::Block(list) => self.block(list),
@@ -1016,8 +1038,12 @@ impl<'a> FnCompiler<'a> {
let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") };
self.statement_completion_start();
self.expr(*discriminant)?;
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
let scope = self.list_scope(&all, true)?;
let scope = if self.es2015 {
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
self.list_scope(&all, true)?
} else {
None
};
if let Some(scope) = scope {
self.emit(Op::PushBlock(scope));
self.env_depth += 1;
@@ -1247,7 +1273,7 @@ impl<'a> FnCompiler<'a> {
self.bind(fin_entry);
// In script and eval code the finally block keeps the completion value of the try or
// catch block when it ends normally (ECMA-262 5.1 section 12.14).
let keeps_completion = self.kind != CodeKind::Function;
let keeps_completion = self.keeps_completion();
if keeps_completion {
self.emit(Op::GetCompletion);
}
@@ -2519,7 +2545,10 @@ pub(crate) fn compile_function(
class_ctor: f.is_class_constructor(),
derived: f.kind == FunctionKind::DerivedConstructor,
pattern_names,
own_name: es2015.then(|| key_of(f.name.as_ref().map_or("", |n| n.name.as_str()))),
own_name: es2015.then(|| {
let name = f.name.as_ref().map_or("", |n| n.name.as_str());
key_of(if f.kind == FunctionKind::Declaration && name == crate::ast::DEFAULT_BINDING { "default" } else { name })
}),
method: (f.home && !f.is_class_constructor())
|| (es2015 && matches!(f.kind, FunctionKind::Method | FunctionKind::Getter | FunctionKind::Setter)),
};
@@ -2539,6 +2568,21 @@ pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kin
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
}
/// Compiles a module's statements ([`crate::parse_module`]): strict code that runs in an
/// environment of its own, as strict eval code does, and returns `undefined`.
pub(crate) fn compile_module(program: &crate::Program, source: &Rc<Source>) -> CResult<Rc<Code>> {
let mut c = FnCompiler::new(&program.ast, source, CodeKind::Eval, true, 0);
c.es2015 = true;
c.module = true;
let hoisted = c.hoist(&program.body, &[])?;
let top_scope = c.list_scope(&program.body, false)?;
c.stmts(&program.body)?;
c.emit(Op::Undefined);
c.emit(Op::Return);
let end = u32::try_from(source.text.len()).unwrap_or(u32::MAX);
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
}
/// The function of a `Function` constructor's source, `(function anonymous(…) {…})`: the program
/// must be that one parenthesized function expression and nothing else. The name `anonymous` is
/// not bound inside the function (section 15.3.2.1).
+27 -2
View File
@@ -119,8 +119,16 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() {
syntax("'use strict'; { function f() {} function f() {} }");
syntax("for (let x = 1 in {}) {}");
syntax("if (1) let x = 1;");
// No statement starts with `let [`, in a statement list or in the body of an `if` or a loop.
for body in ["if (true) let[0];", "if (false) ; else let[0];", "while (false) let[0];", "for (;false;) let[0];", "lbl: let[0];"] {
syntax(&format!("var let = [1]; {body}"));
}
// Outside strict mode code `let` is still a name where no declaration can start.
truth("var let = 3; let === 3");
truth("var let = [1]; var r; if (true) (let[0]); if (true) r = let[0]; r === 1");
truth("var let = [2]; if (true) let\n; let.length === 1");
// ECMAScript 5.1 reads it as a property read.
assert_eq!(Realm::new().run("var let = [1]; if (true) let[0];"), Ok(JsValue::Number(1.0)));
truth("{ function f() { return 1; } function f() { return 2; } } f() === 2");
// A labeled function in a block declares its name in the block.
syntax("{ let f; label: function f() {} }");
@@ -202,7 +210,7 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() {
assert!(matches!(&var, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{var:?}");
assert_eq!(realm.run("kept"), Ok(JsValue::Number(5.0)));
let restricted = realm.run("let undefined = 1;");
assert!(restricted.is_err(), "{restricted:?}");
assert!(is_thrown(&restricted, "SyntaxError"), "{restricted:?}");
}
#[test]
@@ -388,8 +396,14 @@ fn a_global_var_stops_a_later_let_even_on_a_configurable_property() {
assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0)));
// Deleting the property itself, not through the global environment, keeps the record
// (ECMA-262 2015 sections 12.5.3.2 and 8.1.1.4.7).
// Deleting the global object's property, not the variable, leaves the name declared
// (ECMA-262 2015 section 8.1.1.4.7 runs only for `delete w`).
assert_eq!(realm.run("(0, eval)('var w = 1'); delete this.w"), Ok(JsValue::Bool(true)));
assert!(is_thrown(&realm.run("let w = 4;"), "SyntaxError"));
let after_property = realm.run("let w = 4; w");
assert!(is_thrown(&after_property, "SyntaxError"), "{after_property:?}");
assert_eq!(realm.run("(0, eval)('var v = 1'); with (this) delete v"), Ok(JsValue::Bool(true)));
let after_with = realm.run("let v = 4; v");
assert!(is_thrown(&after_with, "SyntaxError"), "{after_with:?}");
assert_eq!(realm.run("(0, eval)('var u = 1'); with (this) { delete u; }"), Ok(JsValue::Bool(true)));
assert!(is_thrown(&realm.run("let u = 5;"), "SyntaxError"));
// Deleting a name the global object only inherits deletes no variable.
@@ -525,6 +539,17 @@ fn arrow_functions_cannot_be_constructed() {
truth("((a, b) => 0).length === 2");
}
#[test]
fn an_arrow_functions_length_is_configurable_and_read_only() {
truth(
"var d = Object.getOwnPropertyDescriptor((a) => a, 'length'); \
d.configurable && !d.writable && !d.enumerable && d.value === 1",
);
truth("var f = (a, b) => 0; delete f.length && !f.hasOwnProperty('length')");
// In ECMAScript 2015 code the other functions' `length` is configurable too (section 19.2.4.1).
truth("var d = Object.getOwnPropertyDescriptor(function (a) {}, 'length'); d.configurable && !d.writable && !d.enumerable");
}
#[test]
fn bad_arrow_functions_are_syntax_errors() {
syntax("var f = x\n=> x;");
+2
View File
@@ -305,6 +305,8 @@ impl Interp {
completion,
boundary,
generator: Some(generator),
chained: false,
pending_module: false,
});
Ok(())
}
+54 -3
View File
@@ -199,7 +199,7 @@ pub(crate) enum Func {
Pausable { f: crate::interp::PausableFn, name: &'static str },
Host { f: Rc<HostFn>, name: Rc<str> },
Data { f: DataFn, name: Rc<str>, read: crate::host::ArgRead },
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str> },
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str>, site: bool },
Bound { target: ObjId, this: Value, args: Rc<[Value]> },
}
@@ -272,6 +272,9 @@ pub(crate) enum Class {
Xmp(Box<crate::xmp::Meta>),
/// An object the `XMPFile` constructor made ([`crate::xmp_classes`]).
XmpFile(Box<PropMap<Value>>),
/// A module namespace object (ECMA-262 2015 section 9.4.6): its own properties are the
/// module's exports, read live from the bindings they name.
ModuleNamespace(Box<ModuleExports>),
/// An object of a class a host defined ([`crate::host_classes`]).
Host(crate::host_classes::HostObj),
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
@@ -598,6 +601,8 @@ impl Class {
Class::String(_) => "String",
Class::RegExp(_) => "RegExp",
Class::Date(_) => "Date",
// The value of a namespace object's @@toStringTag (ECMA-262 2015 section 26.3.1).
Class::ModuleNamespace(_) => "Module",
Class::UnitValue(_) => "UnitValue",
Class::Map(_) => "Map",
Class::Set(_) => "Set",
@@ -644,17 +649,49 @@ pub(crate) struct Binding {
/// A `let` or `const` binding, or a function declared in a block: a `var` that eval code
/// declares cannot take its name.
pub(crate) lexical: bool,
/// A module's import of another module's binding (ECMA-262 2015 section 8.1.1.5.5,
/// CreateImportBinding): reading it reads the binding of that name in that environment, and
/// writing it is a `TypeError`. `value` is unused.
pub(crate) import: Option<(EnvId, Key)>,
}
impl Binding {
/// An initialized binding.
pub(crate) fn new(value: Value, mutable: bool, deletable: bool) -> Self {
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false }
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false, import: None }
}
/// A `let` (or with `constant`, a `const`) binding not yet initialized.
pub(crate) fn lexical(constant: bool) -> Self {
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true }
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true, import: None }
}
/// An import of the binding `name` of the environment `env`.
pub(crate) fn import(env: EnvId, name: Key) -> Self {
Self {
value: Value::Undefined,
mutable: false,
deletable: false,
uninitialized: false,
constant: true,
lexical: true,
import: Some((env, name)),
}
}
}
/// A module namespace object's exports (ECMA-262 2015 section 9.4.6): each exported name, in
/// code unit order, with the environment and name of the binding it reads, or `None` for an export
/// whose value is fixed (another module's namespace object), kept in the object's own property.
#[derive(Clone, Debug, Default)]
pub(crate) struct ModuleExports {
pub(crate) bindings: Vec<(Key, Option<(EnvId, Key)>)>,
}
impl ModuleExports {
/// The binding the export `name` reads, when it reads one.
pub(crate) fn binding(&self, name: &[u16]) -> Option<&(EnvId, Key)> {
self.bindings.binary_search_by(|(k, _)| (**k).cmp(name)).ok().and_then(|i| self.bindings.get(i)).and_then(|(_, b)| b.as_ref())
}
}
@@ -1103,6 +1140,16 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
work.push(map.env.0);
extra = ARG_NAME_BYTES * map.names.len();
}
Class::ModuleNamespace(exports) => {
for (k, b) in &exports.bindings {
strings.add_key(k);
if let Some((env, name)) = b {
work.push(env.0);
strings.add_key(name);
}
}
extra = PROP_BYTES * exports.bindings.len();
}
Class::String(s) => strings.add(s),
Class::RegExp(re) => {
if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) {
@@ -1233,6 +1280,10 @@ fn trace_env(e: &Env, work: &mut Vec<u32>, strings: &mut StringSizes) -> usize {
for (k, b) in bindings.iter() {
strings.add_key(k);
mark_value(&b.value, work, strings);
if let Some((env, name)) = &b.import {
work.push(env.0);
strings.add_key(name);
}
}
ENV_BYTES + PROP_BYTES * bindings.len()
}
+19 -6
View File
@@ -160,11 +160,14 @@ pub enum HostItem {
/// that is not a string is the call's result. `end` is called when the source has run,
/// normally or not. Each source given has the next tag of [`crate::Realm::error_source`],
/// from 1. `strict_writes`, called after `source`, gives [`crate::Realm::set_strict_writes`]
/// for that source alone; with `None` it takes the calling code's.
/// for that source alone; with `None` it takes the calling code's. With `site`, `source` is
/// given the [`CallSite`] of the code that calls it first, as the three numbers its source
/// tag, line and column, and the arguments after them.
Evaluator {
source: HostFunction,
end: Rc<dyn Fn()>,
strict_writes: Rc<dyn Fn() -> Option<bool>>,
site: bool,
},
/// A read-only property that reads the interpreter's own state.
Script(ScriptItem),
@@ -311,6 +314,8 @@ impl Interp {
out
}
/// The [`crate::host_ref`] of the object of a host class `id`, its key, class name and handle
/// charged to `r` as the plain data they are before they are copied.
fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult<Data> {
let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) };
self.charge_entries(r, len.saturating_add(2))?;
@@ -466,7 +471,8 @@ impl Interp {
/// source it gives as global code, as an indirect `eval` does, giving that code's completion
/// value. A result that is not a string is given to the script as it is. `end` is called once
/// the source has run, normally or not. `strict_writes` gives the source's
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's.
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. With `site`,
/// `f` is given the calling code's [`CallSite`] before the arguments.
pub(crate) fn call_evaluator(
&mut self,
f: &crate::heap::DataFn,
@@ -474,8 +480,13 @@ impl Interp {
strict_writes: &Rc<dyn Fn() -> Option<bool>>,
name: &Rc<str>,
args: &[Value],
site: bool,
) -> JsResult<Value> {
let data = self.read_args(name, None, args, &ArgRead::Data)?;
let caller = site.then(|| self.call_site());
let mut data = self.read_args(name, None, args, &ArgRead::Data)?;
if let Some(caller) = caller {
data.splice(0..0, site_data(caller));
}
let source = match f(data) {
Ok(Data::String(source)) => source,
Ok(d) => return self.write_data(d, 0, false),
@@ -517,7 +528,9 @@ impl Interp {
r
}
/// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first.
/// The arguments of host function `name` as [`Data`], read as `how` says. With `this`, the
/// first is the object `this` stands for, or `undefined` when it is not an object of a host
/// class, charged to the same limits as the arguments.
fn read_args(&mut self, name: &Rc<str>, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
let mut reading = Reading {
limits: match how {
@@ -689,9 +702,9 @@ impl Interp {
HostItem::Converted(list, f) => {
Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE }
}
HostItem::Evaluator { source, end, strict_writes } => {
HostItem::Evaluator { source, end, strict_writes, site } => {
let proto = self.intrinsics.function_proto;
let func = Func::Eval { f: source, end, strict_writes, name: full.into() };
let func = Func::Eval { f: source, end, strict_writes, name: full.into(), site };
let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto)));
Prop::Data { value: Value::Object(f), flags: ENUMERABLE }
}
+2
View File
@@ -270,6 +270,8 @@ impl Interp {
Ok(Some(host_ref(&name, &h.handle)))
}
/// The length of the class name and of the handle of the object of a host class `id`, or `None`
/// when it is not one.
pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult<Option<(usize, usize)>> {
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?;
+65 -6
View File
@@ -433,7 +433,7 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
Ok(Data::Number(f64::from(s.line)))
});
let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into())));
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap();
r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap();
let first = r.script_tag();
@@ -455,6 +455,31 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag()));
}
/// An evaluator made with `site` is given the place of the code that calls it before its
/// arguments; one made without it is given only the arguments.
#[test]
fn an_evaluator_with_site_is_told_where_it_is_called() {
let mut r = realm(10_000_000);
let given: Rc<RefCell<Vec<Vec<Data>>>> = Rc::default();
let evaluator = |site: bool| {
let log = given.clone();
let source: HostFunction = Rc::new(move |a| {
log.borrow_mut().push(a);
Ok(Data::String("1".into()))
});
HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site }
};
r.define_host_object("host", vec![("at".into(), evaluator(true)), ("plain".into(), evaluator(false))]).unwrap();
r.run("\n\n host.at('x');\nhost.plain('y');").unwrap();
let tag = f64::from(r.script_tag());
let given = given.borrow();
assert_eq!(given.len(), 2, "{given:?}");
assert_eq!(given[0].len(), 4, "{given:?}");
assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}");
assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}");
assert_eq!(given[1], vec![Data::String("y".into())]);
}
#[test]
fn a_text_function_takes_each_argument_as_string_gives_it() {
let mut r = realm(1_000_000);
@@ -849,6 +874,40 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() {
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into()));
}
/// A realm with the host class `Thing`: `make(n)` gives the `Thing` whose handle is `n` followed by
/// zeros, `len` numbers in all, and `take()` gives `undefined`; and the global `thing`, the `Thing`
/// with the handle `[0]`.
fn with_long_things(r: &mut Realm, len: usize) {
let make: HostFunction = Rc::new(move |a| {
let mut handle = vec![if let Some(Data::Number(n)) = a.get(1) { *n } else { 0.0 }];
handle.resize(len, 0.0);
Ok(host_ref("Thing", &handle))
});
let take: HostFunction = Rc::new(|_| Ok(Data::Undefined));
let members = vec![("make".to_string(), HostMember::Method(make)), ("take".to_string(), HostMember::Method(take))];
let class = HostClass { name: "Thing".into(), parent: None, members, info: Vec::new(), index: None, construct: None };
r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[0.0]))]).unwrap();
}
#[test]
fn the_handles_of_host_objects_given_to_the_host_count_toward_the_data_limits() {
let mut r = realm(100_000_000);
with_long_things(&mut r, 1024);
// 100 references to an object with a handle of 1,024 numbers are more than 100,000 entries.
r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 100_000 });
let probe = "var t = thing.make(1), list = []; for (var i = 0; i < 100; i++) list.push(t); var m = 'none'; \
try { thing.take(list); } catch (e) { m = e.name + '|' + e.message; } m";
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}");
// The object a member is called on counts too.
r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 1_000 });
let probe = "var m = 'none'; try { thing.make(2).take(); } catch (e) { m = e.name + '|' + e.message; } m";
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}");
// Short handles stay within the limits.
assert_eq!(r.run("thing.take([thing, thing]) === undefined").unwrap(), JsValue::Bool(true));
}
#[test]
fn a_host_class_constructor_called_with_new_cannot_wait() {
let mut r = realm(1_000_000);
@@ -978,7 +1037,7 @@ fn a_converted_function_reads_each_argument_as_its_list_says() {
fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unknown() {
let mut r = realm(10_000_000);
let source: HostFunction = Rc::new(|_| Ok(Data::String("\nthrow new Error('in eval')".into())));
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
r.run("function late() { throw new Error('late'); }").unwrap();
assert!(r.run("host.load()").is_err());
@@ -1000,7 +1059,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
let s = seen.clone();
r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units)));
let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into())));
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap();
assert_eq!(out, JsValue::Number(49.0));
@@ -1015,7 +1074,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() {
let mut r = realm(10_000_000);
let source: HostFunction = Rc::new(|_| Ok(Data::String("function inEval() { throw new Error('in eval'); }".into())));
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "no script yet");
r.run("function late() { throw new Error('late'); }\nhost.load(); host.load();").unwrap();
@@ -1048,7 +1107,7 @@ fn an_evaluators_source_takes_fuel_before_it_is_parsed() {
let ends = Rc::new(Cell::new(0));
let ended = ends.clone();
let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17)))));
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) };
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None), site: false };
let mut r = realm(10_000);
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
let e = r.run("host.evaluate()").unwrap_err();
@@ -1069,7 +1128,7 @@ fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() {
// The source does not parse, so a parse would throw a syntax error instead.
let n = (1 << 17) + 1;
let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1)))));
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
let mut r = realm(1_000_000);
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
r.interp().collect_for_room();
+296 -18
View File
@@ -26,8 +26,8 @@ use crate::ast::BinaryOp;
use crate::bytecode::{Code, CodeKind, NamePrefix, Op, Source};
use crate::compiler::{CompileFail, compile_program};
use crate::heap::{
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId,
Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, ModuleExports, NativeKind, OBJECT_BYTES,
OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
};
use crate::parser::SuperRules;
use crate::string_builtins::flat_charged;
@@ -231,6 +231,11 @@ pub(crate) struct Frame {
pub(crate) boundary: bool,
/// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it.
pub(crate) generator: Option<ObjId>,
/// The frame runs a module that another module of the same run waits under (ECMA-262 2015
/// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception
/// that leaves it ends the run at the boundary frame without stopping in the frames between.
pub(crate) chained: bool,
pub(crate) pending_module: bool,
}
/// Where the exception being thrown was raised: the code and the instruction.
@@ -275,6 +280,7 @@ pub(crate) struct Interp {
pub(crate) heap: Heap,
pub(crate) stack: Vec<Value>,
pub(crate) frames: Vec<Frame>,
pending_module_frames: usize,
/// Values native code holds while it may run JavaScript.
pub(crate) temp_roots: Vec<Value>,
/// Environments native code is still building.
@@ -637,6 +643,7 @@ impl Interp {
heap,
stack: Vec::new(),
frames: Vec::new(),
pending_module_frames: 0,
temp_roots: Vec::new(),
temp_envs: Vec::new(),
temp_codes: Vec::new(),
@@ -1032,7 +1039,11 @@ impl Interp {
self.push(v)?;
return Ok(None);
}
if self.frames.last().is_some_and(|frame| frame.pending_module) {
self.pending_module_frames -= 1;
}
let frame = self.frame_mut()?;
frame.pending_module = false;
let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") };
frame.pc += 1;
match op {
@@ -1101,10 +1112,14 @@ impl Interp {
}
return Ok(());
}
let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) };
let Some(frame) = self.pop_frame() else { return Err(Abrupt::Throw(v)) };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
if frame.boundary {
if frame.chained {
// The modules under it have not started, so no handler of theirs takes it.
self.abort_to_boundary();
}
if frame.boundary || frame.chained {
self.passing = v.clone();
return Err(Abrupt::Throw(v));
}
@@ -1114,11 +1129,24 @@ impl Interp {
/// 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()))
self.frames.iter().filter(|f| !f.pending_module).map(|f| (&f.code, f.pc, f.callee.is_some()))
}
pub(crate) fn clear_frames(&mut self) {
self.frames.clear();
self.pending_module_frames = 0;
}
fn pop_frame(&mut self) -> Option<Frame> {
let frame = self.frames.pop()?;
if frame.pending_module {
self.pending_module_frames -= 1;
}
Some(frame)
}
fn abort_to_boundary(&mut self) {
while let Some(frame) = self.frames.pop() {
while let Some(frame) = self.pop_frame() {
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
if frame.boundary {
@@ -1148,7 +1176,7 @@ impl Interp {
Some(_) => crate::builtins::iterator::iter_result(self, v, true)?,
None => v,
};
let Some(frame) = self.frames.pop() else { return internal("return without a frame") };
let Some(frame) = self.pop_frame() else { return internal("return without a frame") };
self.stack.truncate(frame.base);
self.end_generator(frame.generator);
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
@@ -1160,6 +1188,9 @@ impl Interp {
if frame.boundary {
return Ok(Some(v));
}
if frame.chained {
return Ok(None);
}
self.push(v)?;
Ok(None)
}
@@ -1490,6 +1521,15 @@ impl Interp {
matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized))
}
/// The binding the binding `name` of the declarative environment `env` imports, when it is a
/// module's import.
fn import_of(&self, env: EnvId, name: &[u16]) -> Option<(EnvId, Key)> {
match self.heap.env(env) {
Some(Env::Decl { bindings, .. }) => bindings.get(name).and_then(|b| b.import.clone()),
_ => None,
}
}
fn not_initialized(&mut self, name: &[u16]) -> Abrupt {
let ident = String::from_utf16_lossy(name);
self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized"))
@@ -1502,6 +1542,14 @@ impl Interp {
/// GetValue of a reference whose base was resolved earlier (section 8.7.1).
fn get_resolved(&mut self, r: Resolved, name: &Key) -> JsResult<(Value, Value)> {
if let Resolved::Decl(e) = r
&& let Some((target, target_name)) = self.import_of(e, name)
{
if self.uninitialized(target, &target_name) {
return Err(self.not_initialized(name));
}
return Ok((self.binding_value(target, &target_name)?, Value::Undefined));
}
match r {
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)),
@@ -1521,6 +1569,12 @@ impl Interp {
/// PutValue of a reference whose base was resolved earlier (section 8.7.2).
fn set_resolved(&mut self, r: Resolved, name: &Key, v: Value) -> JsResult<()> {
let strict = self.strict();
if let Resolved::Decl(e) = r
&& self.import_of(e, name).is_some()
{
let ident = String::from_utf16_lossy(name);
return Err(self.type_error(&format!("assignment to the import '{ident}'")));
}
match r {
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
Resolved::Decl(e) if matches!(self.heap.env(e), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.constant)) => {
@@ -1726,18 +1780,59 @@ impl Interp {
return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN }));
}
}
Class::ModuleNamespace(exports) => {
if let Some((env, name)) = exports.binding(k)
&& let Some(Prop::Data { flags, .. }) = o.props.get(k)
{
return Ok(Some(Prop::Data { value: self.binding_value(*env, name)?, flags: *flags }));
}
}
_ => {}
}
Ok(o.props.get(k).cloned())
}
/// [[GetOwnProperty]] as a script reaches it (`hasOwnProperty`, `Object.keys` and the like):
/// [`Self::get_own_property`], except that an export of a module namespace object read before
/// its module initialized it is a `ReferenceError` (ECMA-262 2015 section 9.4.6.5).
pub(crate) fn own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
self.check_namespace_export(id, k)?;
self.get_own_property(id, k)
}
/// [`Self::own_property`] for a name or a Symbol: [`Self::get_own_pk`], with the same
/// `ReferenceError` for a namespace export read before its module initialized it.
pub(crate) fn own_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
if let PropKey::Str(name) = k {
self.check_namespace_export(id, name)?;
}
self.get_own_pk(id, k)
}
/// A `ReferenceError` when `k` is an export of the module namespace object `id` that its module
/// has not initialized yet.
fn check_namespace_export(&mut self, id: ObjId, k: &[u16]) -> JsResult<()> {
if let Some(Class::ModuleNamespace(exports)) = self.heap.object(id).map(|o| &o.class)
&& let Some((env, name)) = exports.binding(k)
&& self.uninitialized(*env, name)
{
return Err(self.not_initialized(k));
}
Ok(())
}
/// [[GetProperty]]: the property found on the object or its prototype chain.
pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
Ok(self.find_property_on(id, k)?.map(|(_, p)| p))
}
/// [`Self::find_property`], with the object on the prototype chain that has the property.
fn find_property_on(&self, id: ObjId, k: &[u16]) -> JsResult<Option<(ObjId, Prop)>> {
let mut cur = Some(id);
let mut steps = 0usize;
while let Some(o) = cur {
if let Some(p) = self.get_own_property(o, k)? {
return Ok(Some(p));
return Ok(Some((o, p)));
}
// A typed array's prototypes are not searched for a numeric name (section 9.4.5.4).
if crate::builtins::binary::typed_key(self, o, k).is_some() {
@@ -1764,7 +1859,14 @@ impl Interp {
{
return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false);
}
match self.find_property(start, k)? {
let found = self.find_property_on(start, k)?;
// A module's export read before the module ran is in its temporal dead zone (ECMA-262
// 2015 section 9.4.6.8), whether the read starts at the namespace object or reaches it
// through a prototype chain.
if let Some((holder, _)) = &found {
self.check_namespace_export(*holder, k)?;
}
match found.map(|(_, p)| p) {
// A name the object and its prototypes lack is the indexer's answer too.
None => match self.host_indexer(start)? {
Some(f) => self.host_index(&f, start, Self::indexer_key(k), false),
@@ -1780,7 +1882,11 @@ impl Interp {
/// class: a name the object and its prototypes lack is `undefined`. For names the engine looks
/// up itself, such as `toJSON`, which a collection's indexer would answer with an error.
pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult<Value> {
match self.find_property(start, k)? {
let found = self.find_property_on(start, k)?;
if let Some((holder, _)) = &found {
self.check_namespace_export(*holder, k)?;
}
match found.map(|(_, p)| p) {
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
Some(Prop::Data { value, .. }) => Ok(value),
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
@@ -1892,10 +1998,26 @@ impl Interp {
}
Ok(true)
}
Class::ModuleNamespace(_) => self.define_namespace_export(id, &k, desc, throw),
_ => self.define_ordinary(id, k, desc, throw),
}
}
/// A module namespace object's [[DefineOwnProperty]] (ECMA-262 2020 section 9.4.6.5): only a
/// descriptor that leaves an export as it is (enumerable, writable, not configurable, its
/// current value) succeeds.
fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult<bool> {
let Some(Prop::Data { value, .. }) = self.own_property(id, k)? else {
return self.reject_bool(throw, k, "a module namespace object is not extensible");
};
let unchanged = desc.configurable != Some(true)
&& desc.enumerable != Some(false)
&& !desc.is_accessor()
&& desc.writable != Some(false)
&& desc.value.as_ref().is_none_or(|v| same_value(v, &value));
if unchanged { Ok(true) } else { self.reject_bool(throw, k, "a module namespace object is read-only") }
}
pub(crate) fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> {
if throw {
let key = String::from_utf16_lossy(k);
@@ -2068,6 +2190,10 @@ impl Interp {
if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) {
return crate::builtins::binary::set_element(self, id, n, &v);
}
// A module namespace object takes no writes (ECMA-262 2015 section 9.4.6.9).
if matches!(self.object(id)?.class, Class::ModuleNamespace(_)) {
return self.reject(throw, &k, "a module namespace object is read-only");
}
match self.get_own_property(id, &k)? {
Some(Prop::Data { flags, .. }) => {
if flags & WRITABLE == 0 {
@@ -2079,8 +2205,25 @@ impl Interp {
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
None => {}
}
let proto = self.object(id)?.proto;
let inherited = proto.map(|p| self.find_property(p, &k)).transpose()?.flatten();
let mut inherited = None;
let mut cur = self.object(id)?.proto;
let mut steps = 0usize;
while let Some(o) = cur {
// A write that reaches a module namespace object on the prototype chain is refused
// there too: its [[Set]] returns false for every key.
if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) {
return self.reject(throw, &k, "a module namespace object is read-only");
}
if let Some(p) = self.get_own_property(o, &k)? {
inherited = Some(p);
break;
}
cur = self.object(o)?.proto;
steps += 1;
if steps > 1_000_000 {
return internal("prototype chain too long");
}
}
match inherited {
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
@@ -2953,6 +3096,8 @@ impl Interp {
// listed or their bytes reserved must not free it.
let saved = self.temp_roots.len();
self.temp_roots.push(Value::Object(o));
// Listing a namespace object's exports does not read them (ECMA-262 2015 section
// 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed.
let keys = self.enumerable_keys(o).and_then(|keys| {
let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
self.reserve_heap(bytes)?;
@@ -3067,8 +3212,8 @@ impl Interp {
// keeps itself reachable.
return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?));
}
Func::Eval { f, end, strict_writes, name } => {
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?));
Func::Eval { f, end, strict_writes, name, site } => {
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args, site)?));
}
Func::Host { f: host, .. } => {
let js_args: Vec<crate::JsValue> = args.iter().map(|v| self.to_js_value(v)).collect();
@@ -3157,9 +3302,7 @@ impl Interp {
/// the stack.
pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
let Entry { callee, code, env, this, args, new_target } = entry;
if self.frames.len() >= self.limits.frames {
return Err(Abrupt::Limit(LimitKind::Frames));
}
self.check_frame_room()?;
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
// An arrow function reads the `arguments` object of the function around it.
let arguments = if code.uses_arguments && !code.arrow { arguments_bytes(args.len()) } else { 0 };
@@ -3220,6 +3363,8 @@ impl Interp {
completion: Value::Undefined,
boundary,
generator: None,
chained: false,
pending_module: false,
});
Ok(())
};
@@ -3563,6 +3708,22 @@ impl Interp {
})
}
/// Parses and compiles a module's source ([`crate::parse_module`]), counting it against the
/// source limit, with [`Self::source_tag`] as its source's tag.
pub(crate) fn compile_module_source(&mut self, units: &[u16]) -> Result<(Rc<Code>, crate::ModuleInfo), CompileError> {
self.source_units = self.source_units.saturating_add(units.len());
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
let options = Options { max_source_units: remaining, ..self.options.clone() };
let (program, info) = crate::parse_module_utf16(units, &options).map_err(CompileError::Syntax)?;
let writes = self.writes_mode();
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
let code = crate::compiler::compile_module(&program, &source).map_err(|e| match e {
CompileFail::Syntax(s) => CompileError::Syntax(s),
CompileFail::Internal(m) => CompileError::Internal(m),
})?;
Ok((code, info))
}
/// Turns a compile failure inside a running script into what it throws.
pub(crate) fn compile_error_to_abrupt(&mut self, e: CompileError) -> Abrupt {
match e {
@@ -3751,7 +3912,7 @@ impl Interp {
/// A [`LimitKind::Frames`] error when no other frame fits under the frame limit.
fn check_frame_room(&self) -> JsResult<()> {
if self.frames.len() >= self.limits.frames {
if self.frames.len() - self.pending_module_frames >= self.limits.frames {
return Err(Abrupt::Limit(LimitKind::Frames));
}
Ok(())
@@ -3777,10 +3938,127 @@ impl Interp {
completion: Value::Undefined,
boundary,
generator: None,
chained: false,
pending_module: false,
});
Ok(())
}
/// Declaration binding instantiation for a module's code (ECMA-262 2015 section 15.2.1.16.4,
/// ModuleDeclarationInstantiation, its imports aside): a new environment inside the global
/// scope holds its variables and functions, and one inside that its `let` and `const` names,
/// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary
/// roots for the caller to remove.
pub(crate) fn instantiate_module(&mut self, code: &Rc<Code>) -> JsResult<(EnvId, EnvId)> {
// The code itself was counted when the module was loaded ([`Self::hold_module_code`]).
self.reserve_heap(declaration_bytes(code).saturating_add(ENV_BYTES))?;
let scope = self.global_lex;
let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
self.temp_envs.push(env);
let lex = self.instantiate_global(code, env, env, true)?;
self.temp_envs.push(lex);
Ok((lex, env))
}
/// Adds `binding` (an import) to the module environment `env`, which must not have `name`.
pub(crate) fn add_import(&mut self, env: EnvId, name: Key, binding: Binding) -> JsResult<()> {
self.use_fuel()?;
// The binding's value (a namespace object) stays reachable while room is made.
self.temp_roots.push(binding.value.clone());
let reserved = self.reserve_heap(binding_bytes(name.len()));
self.temp_roots.pop();
reserved?;
self.env_insert(env, name, binding)
}
/// The environment that holds `name` of a module whose code runs in `lex` inside `env`.
pub(crate) fn module_binding(&self, lex: EnvId, env: EnvId, name: &[u16]) -> Option<EnvId> {
[lex, env].into_iter().find(|e| matches!(self.heap.env(*e), Some(Env::Decl { bindings, .. }) if bindings.contains(name)))
}
/// A module namespace object for the exports `exports`, each `(name, binding)` with the
/// binding it reads or, for `None`, the value `fixed` gives. The names must be in code unit
/// order and distinct.
pub(crate) fn module_namespace(&mut self, exports: Vec<(Key, Option<(EnvId, Key)>)>, fixed: &[(Key, Value)]) -> JsResult<ObjId> {
let names = exports.iter().map(|(name, _)| string_bytes(name.len())).sum::<usize>();
let bindings = PROP_BYTES.saturating_mul(exports.len());
let tag = self.well_known(|symbols| &symbols.to_string_tag);
let tagged = if tag.is_some() { PROP_BYTES.saturating_add(string_bytes(6)) } else { 0 };
let extra = bindings.saturating_add(names).saturating_add(tagged);
self.reserve_heap(OBJECT_BYTES.saturating_add(bindings).saturating_add(extra))?;
let mut object = Object::new(Class::ModuleNamespace(Box::default()), None);
if let Some(tag) = tag {
object.syms.get_or_insert_with(Default::default).insert(tag, Prop::Data { value: Value::str("Module"), flags: 0 });
}
object.extensible = false;
for (name, _) in &exports {
self.use_fuel()?;
let value = fixed.iter().find(|(k, _)| k == name).map_or(Value::Undefined, |(_, v)| v.clone());
object.props.insert(name.clone(), Prop::Data { value, flags: WRITABLE | ENUMERABLE });
}
object.class = Class::ModuleNamespace(Box::new(ModuleExports { bindings: exports }));
let namespace = self.heap.alloc_object(object);
self.heap.bytes = self.heap.bytes.saturating_add(extra);
Ok(namespace)
}
/// Pushes the frames of a run of modules: `modules` in the order they run, each with its code,
/// the environment it runs in and the outer one. The last is the boundary frame, pushed first;
/// each of the others is pushed above the one that runs after it, so the first to run is on
/// top.
pub(crate) fn push_module_frames(&mut self, modules: &[(Rc<Code>, EnvId, EnvId)]) -> JsResult<()> {
for (i, (code, env, var_env)) in modules.iter().enumerate().rev() {
let last = i + 1 == modules.len();
self.push_code_frame(code.clone(), *env, *var_env, Value::Undefined, last)?;
if let Some(frame) = self.frames.last_mut() {
frame.chained = !last;
frame.pending_module = true;
}
self.pending_module_frames += 1;
}
Ok(())
}
/// Ends module linking: drops the temporary roots from `mark` on.
pub(crate) fn drop_temp_envs(&mut self, mark: usize) {
self.temp_envs.truncate(mark);
}
pub(crate) fn temp_envs_mark(&self) -> usize {
self.temp_envs.len()
}
/// Counts a loaded module's code against the heap once, when the module is loaded, and keeps
/// it reachable until [`Self::drop_temp_codes`] drops it, so a collection while later modules
/// load counts it too.
pub(crate) fn hold_module_code(&mut self, code: &Rc<Code>) -> JsResult<()> {
self.charge_code(code, 0)?;
self.temp_codes.push(code.clone());
Ok(())
}
pub(crate) fn temp_codes_mark(&self) -> usize {
self.temp_codes.len()
}
/// Ends module linking: drops the modules' code held from `mark` on.
pub(crate) fn drop_temp_codes(&mut self, mark: usize) {
self.temp_codes.truncate(mark);
}
/// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it.
pub(crate) fn hold(&mut self, v: Value) {
self.temp_roots.push(v);
}
pub(crate) fn temp_roots_mark(&self) -> usize {
self.temp_roots.len()
}
pub(crate) fn drop_temp_roots(&mut self, mark: usize) {
self.temp_roots.truncate(mark);
}
/// Declaration binding instantiation for global and eval code (section 10.5). The caller has
/// reserved [`declaration_bytes`] of `code`; each declaration takes a unit of fuel.
///
+46 -4
View File
@@ -63,7 +63,17 @@
//! closes its iterator. In a realm made without the option and later given it with
//! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects
//! by index and strings by code point, and throw a `TypeError` for other values.
//! Object rest properties (`{ a, ...rest }`) and modules stay syntax errors.
//! Object rest properties (`{ a, ...rest }`) stay syntax errors, and so do `import` and `export`
//! in a script.
//!
//! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import`
//! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a
//! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module
//! once, after the modules it imports, with each import reading the exporting module's binding. In
//! a cycle of imports, a module is marked as visited before the modules it imports are, so it does
//! not wait for a module that is still waiting for its own imports, and reading a binding of that
//! module before it is initialized throws a `ReferenceError`.
//! Dynamic `import()` is a syntax error.
//!
//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition,
//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in
@@ -129,6 +139,7 @@ mod host_classes;
mod interp;
mod iteration;
mod lexer;
mod module;
mod number;
mod number_builtins;
mod parser;
@@ -151,15 +162,16 @@ mod xmp_classes;
mod xpath;
pub use ast::{
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId,
FunctionKind, LexKind, LogicalOp, MethodKind, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece,
UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, DEFAULT_BINDING, ExportEntry, Expr, ExprId, ForInTarget,
ForInit, Function, FunctionId, FunctionKind, ImportEntry, ImportName, LexKind, LogicalOp, MethodKind, ModuleInfo, ModuleRequest, Name, Program,
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
};
pub use builtins::extensions::Localization;
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
pub use lexer::{Goal, Lexer};
pub use module::{LoadError, LoadedModule, ModuleLimits, ModuleLoader};
pub use number::to_string as number_to_string;
pub use realm::{
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
@@ -222,6 +234,34 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxE
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
}
/// Parses `source` as a module (ECMA-262 2015 section 15.2): strict mode code with
/// [`Options::es2015`]'s forms, `import` and `export` declarations at its top, and no preprocessor
/// lines, whatever `options` says about those three. Gives its statements and what it imports and
/// exports.
pub fn parse_module(source: &str, options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
let units = to_utf16(source, options)?;
parse_module_utf16(&units, options)
}
/// Parses `source`, in UTF-16 code units, as a module ([`parse_module`]).
pub fn parse_module_utf16(source: &[u16], options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
check_length(source.len(), options)?;
parser::Parser::new(source, &module_options(options), false)?.parse_module().map(|(program, info, _)| (program, info))
}
/// The tokens of `source` as [`tokenize`] gives them, with `source` read as a module
/// ([`parse_module`]). The source must be a valid module.
pub fn tokenize_module(source: &str, options: &Options) -> Result<Vec<Token>, SyntaxError> {
let units = to_utf16(source, options)?;
check_length(units.len(), options)?;
parser::Parser::new(&units, &module_options(options), true)?.parse_module().map(|(_, _, tokens)| tokens)
}
/// `options` as a module is read with them.
pub(crate) fn module_options(options: &Options) -> Options {
Options { strict: true, es2015: true, preprocessor_lines: false, ..options.clone() }
}
/// [`parse_utf16`] for code a direct `eval` runs, which may use `super` and `new.target` as the
/// code that calls it may (ECMA-262 2015 section 18.2.1.1).
pub(crate) fn parse_utf16_with_supers(source: &[u16], options: &Options, rules: parser::SuperRules) -> Result<Program, SyntaxError> {
@@ -324,6 +364,8 @@ mod host_tests;
#[cfg(test)]
mod interp_tests;
#[cfg(test)]
mod module_tests;
#[cfg(test)]
mod promise_tests;
#[cfg(test)]
mod reflect_tests;
+553
View File
@@ -0,0 +1,553 @@
//! Running modules (ECMA-262 2015 section 15.2.1): loading a module and the modules it imports,
//! linking their imports to the bindings their exports name, and readying them to run, each once,
//! the modules a module imports before it.
//!
//! The host maps each specifier to a module ([`ModuleLoader`], the role of section 15.2.1.17,
//! HostResolveImportedModule): it gives a key that names the module, and its source the first time
//! it gives that key. Every module is parsed and compiled before any runs, and every import is
//! linked before any runs, so a syntax error, a missing or ambiguous export, or a module the host
//! cannot give ends the run before any of its code runs. The run's [`ModuleLimits`] bound how many
//! modules it loads and how deep its imports go; parsing takes fuel for each code unit, and each
//! binding made in linking takes a unit.
//!
//! An import reads the exporting module's binding itself, so it sees each later assignment, and a
//! read before that binding is initialized (a module that imports one that imports it back) is a
//! `ReferenceError`. A module namespace object (`import * as ns`) is not extensible, has no
//! prototype, takes no writes and has the module's export names, in code unit order, as its
//! properties. `export *` passes on every name but `default`; a name two `export *` give from
//! different bindings is left out of a namespace and is a `SyntaxError` to import.
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use crate::ast::{ExportEntry, ImportName, ModuleInfo};
use crate::bytecode::Code;
use crate::heap::{Binding, Env, EnvId, ObjId, Prop, key};
use crate::interp::{Abrupt, CompileError, ErrorType, Interp};
use crate::value::Value;
/// What the host gives for a module a run imports.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoadedModule {
/// What names the module: two specifiers that give one key import one module, which runs once.
pub key: String,
/// The module's source, given the first time the host gives its key in a run. `None` for a key
/// the host gave before in the same run.
pub source: Option<String>,
}
/// Why the host cannot give a module, which ends the run before any module runs: the error the
/// `import` raises, with its message.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LoadError {
/// A specifier the host does not read: a `SyntaxError`.
Syntax(String),
/// A limit of the host's: a `RangeError`.
Range(String),
/// A module that is missing, refused or unreadable: an `Error`.
Other(String),
}
/// The host's map from a specifier to a module: called with the key of the importing module and
/// the specifier as written.
pub type ModuleLoader<'a> = dyn FnMut(&str, &str) -> Result<LoadedModule, LoadError> + 'a;
/// Bounds on the modules of one run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModuleLimits {
/// The most modules a run loads, the first included.
pub modules: usize,
/// The most imports from the first module to any other, along the shortest chain.
pub depth: usize,
}
impl Default for ModuleLimits {
fn default() -> Self {
Self { modules: 64, depth: 16 }
}
}
/// The most modules a run loads, whatever its limits say: [`resolve_export`] and
/// [`exported_names`] recurse once for each module at most.
const MAX_MODULES: usize = 1024;
/// The most `(module, name)` pairs one export's resolution visits.
const MAX_RESOLVE_STEPS: usize = 1024;
#[derive(Default)]
struct ResolveSeen {
pairs: HashSet<ResolveKey>,
count: usize,
}
struct ResolveKey {
module: usize,
name: String,
}
impl PartialEq for ResolveKey {
fn eq(&self, other: &Self) -> bool {
#[cfg(test)]
RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(count.get() + 1));
self.module == other.module && self.name == other.name
}
}
impl Eq for ResolveKey {}
impl std::hash::Hash for ResolveKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::hash::Hash::hash(&(self.module, &self.name), state);
}
}
#[cfg(test)]
thread_local! {
pub(crate) static RESOLVED_STAR_EDGES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static RESOLVE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static RESOLVE_MEMBERSHIP_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// A loaded module.
struct Record {
key: String,
info: ModuleInfo,
code: Rc<Code>,
tag: u32,
/// The module each of `info.requests` names, by index.
requested: Vec<usize>,
/// The environment its code runs in and the outer one, once instantiated.
envs: Option<(EnvId, EnvId)>,
namespace: Option<ObjId>,
/// Each name the module exports itself or re-exports by name, with its entry in
/// `info.exports`.
explicit: HashMap<String, usize>,
/// Each `export *` request, replaced by distinct canonical targets after loading, in order.
stars: Vec<usize>,
}
/// Why a module run could not start.
pub(crate) enum LinkFail {
/// A module does not parse; `tag` is its source's.
Syntax { tag: u32, error: crate::SyntaxError },
/// An exception, raised at `line` and `column` of the module whose source has `tag`.
At { tag: u32, line: u32, column: u32, abrupt: Abrupt },
/// A limit or an internal error, not at any place.
Run(Abrupt),
}
/// Where an export resolves to (ResolvedBinding).
#[derive(Clone, PartialEq, Eq)]
enum Resolution {
/// The binding `name` of module `module`.
Binding { module: usize, name: String },
/// The namespace object of module `module` (`export * as ns from`).
Namespace(usize),
}
/// An export that two `export *` declarations give from different places.
struct Ambiguous;
/// The modules of a run, loaded and linked.
struct Graph<'a, 'l> {
interp: &'a mut Interp,
records: Vec<Record>,
by_key: HashMap<String, usize>,
load: &'a mut ModuleLoader<'l>,
}
/// Loads the module `key` with `source` and every module it imports, instantiates and links them,
/// and gives them in the order they run, each with its code, the environment it runs in and the
/// outer one. The first module's source has tag `entry_tag`; each module loaded after it takes
/// the next tag. The environments stay in the interpreter's temporary roots for the caller to
/// remove once their frames are pushed.
pub(crate) fn link(
interp: &mut Interp,
key_name: &str,
source: &str,
entry_tag: u32,
limits: ModuleLimits,
load: &mut ModuleLoader<'_>,
) -> Result<Vec<(Rc<Code>, EnvId, EnvId)>, LinkFail> {
let mut graph = Graph { interp, records: Vec::new(), by_key: HashMap::new(), load };
if limits.modules == 0 {
return Err(graph.fail_at(0, 0, ErrorType::Range, "module limit (0) reached"));
}
graph.add(key_name.to_string(), source, entry_tag)?;
graph.load_imports(limits)?;
graph.instantiate()?;
graph.link_imports()?;
Ok(graph.evaluation_order())
}
impl Graph<'_, '_> {
/// Parses and compiles a module's source under `tag`.
fn add(&mut self, key_name: String, source: &str, tag: u32) -> Result<usize, LinkFail> {
let interp = &mut *self.interp;
let minimum_units = source.len().div_ceil(3);
if u64::try_from(minimum_units).unwrap_or(u64::MAX) > interp.fuel {
interp.prepare_source(minimum_units).map_err(LinkFail::Run)?;
}
interp.prepare_source(0).map_err(LinkFail::Run)?;
interp.prepare_source(source.encode_utf16().count()).map_err(LinkFail::Run)?;
let saved = std::mem::replace(&mut interp.source_tag, tag);
let compiled = interp.encode_source(source).and_then(|units| interp.compile_module_source(&units));
interp.source_tag = saved;
let (code, info) = match compiled {
Ok(c) => c,
Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }),
Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))),
};
// The record keeps the code from here on, so the heap counts it from here on.
self.interp.hold_module_code(&code).map_err(LinkFail::Run)?;
let mut explicit = HashMap::new();
let mut stars = Vec::new();
for (i, e) in info.exports.iter().enumerate() {
match e {
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
explicit.entry(export_name.clone()).or_insert(i);
}
ExportEntry::Star { request, .. } => stars.push(*request),
}
}
self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None, explicit, stars });
let index = self.records.len() - 1;
self.by_key.insert(key_name, index);
Ok(index)
}
/// An exception of type `t` with `message`, at the source offset `offset` of module `m`.
fn fail_at(&mut self, m: usize, offset: u32, t: ErrorType, message: &str) -> LinkFail {
let (tag, (line, column)) = match self.records.get(m) {
Some(r) => (r.tag, r.code.source.lines.line_column(offset)),
None => (crate::realm::UNKNOWN_SOURCE, (0, 0)),
};
LinkFail::At { tag, line, column, abrupt: self.interp.throw(t, message) }
}
/// Loads the modules each loaded module imports, breadth first, so a module's depth is the
/// length of the shortest chain of imports to it.
fn load_imports(&mut self, limits: ModuleLimits) -> Result<(), LinkFail> {
let max_modules = limits.modules.min(MAX_MODULES);
let mut depths = vec![0usize];
let mut i = 0;
while i < self.records.len() {
let requests: Vec<(String, bool, u32)> = self.records[i]
.info
.requests
.iter()
.map(|r| (r.specifier.clone(), char::decode_utf16(r.units.iter().copied()).all(|c| c.is_ok()), r.span.start))
.collect();
let depth = depths.get(i).copied().unwrap_or(0);
for (specifier, text, offset) in requests {
self.interp.use_fuel().map_err(LinkFail::Run)?;
// The host maps text to modules, and a specifier with an unpaired surrogate is not
// text, so it is refused here, as a host refuses a specifier it does not read.
if !text {
let message = format!("module specifier '{specifier}' is not valid text: it has an unpaired surrogate");
return Err(self.fail_at(i, offset, ErrorType::Syntax, &message));
}
let referrer = self.records[i].key.clone();
let loaded = match (self.load)(&referrer, &specifier) {
Ok(loaded) => loaded,
Err(LoadError::Syntax(why)) => return Err(self.fail_at(i, offset, ErrorType::Syntax, &why)),
Err(LoadError::Range(why)) => return Err(self.fail_at(i, offset, ErrorType::Range, &why)),
Err(LoadError::Other(why)) => return Err(self.fail_at(i, offset, ErrorType::Error, &why)),
};
let target = match (self.by_key.get(&loaded.key), loaded.source) {
(Some(&j), _) => j,
(None, None) => {
let message = format!("the module '{specifier}' was given without its source");
return Err(self.fail_at(i, offset, ErrorType::Error, &message));
}
(None, Some(source)) => {
if depth >= limits.depth {
let message = format!("import depth limit ({}) reached at '{specifier}'", limits.depth);
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
}
if self.records.len() >= max_modules {
let message = format!("module limit ({max_modules}) reached at '{specifier}'");
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
}
let tag = crate::realm::next_tag(self.records.last().map_or(0, |r| r.tag));
self.interp.evaluated = tag;
depths.push(depth + 1);
self.add(loaded.key, &source, tag)?
}
};
self.records[i].requested.push(target);
}
let mut seen_targets = HashSet::new();
let targets: Vec<usize> = self.records[i]
.stars
.iter()
.filter_map(|&request| self.records[i].requested.get(request).copied())
.filter(|target| seen_targets.insert(*target))
.collect();
self.records[i].stars = targets;
i += 1;
}
Ok(())
}
/// Makes each module's environments, with its variables, functions and `let` and `const`
/// names.
fn instantiate(&mut self) -> Result<(), LinkFail> {
for i in 0..self.records.len() {
let code = self.records[i].code.clone();
let envs = self.interp.instantiate_module(&code).map_err(LinkFail::Run)?;
self.records[i].envs = Some(envs);
for import in &self.records[i].info.imports {
if matches!(&import.import, ImportName::Namespace) {
self.interp.add_import(envs.1, key(&import.local.name), Binding::lexical(true)).map_err(LinkFail::Run)?;
}
}
}
Ok(())
}
/// The module the request `request` of module `m` names.
fn target(&self, m: usize, request: usize) -> Option<usize> {
self.records.get(m).and_then(|r| r.requested.get(request)).copied()
}
/// The specifier of request `request` of module `m`, as written.
fn specifier(&self, m: usize, request: usize) -> String {
self.records.get(m).and_then(|r| r.info.requests.get(request)).map(|r| r.specifier.clone()).unwrap_or_default()
}
/// ResolveExport (section 15.2.1.16.3): where the export `name` of module `m` comes from,
/// `None` when the module has no such export (or only through a cycle).
fn resolve_export(&mut self, m: usize, name: &str, seen: &mut ResolveSeen) -> Result<Result<Option<Resolution>, Ambiguous>, LinkFail> {
#[cfg(test)]
RESOLVE_CALLS.with(|count| count.set(count.get() + 1));
let visit = ResolveKey { module: m, name: name.to_string() };
if seen.pairs.contains(&visit) {
return Ok(Ok(None));
}
if seen.count >= MAX_RESOLVE_STEPS {
let message = format!("export resolution limit ({MAX_RESOLVE_STEPS} steps) reached for '{name}'");
return Err(LinkFail::Run(self.interp.throw(ErrorType::Range, &message)));
}
self.interp.use_fuel().map_err(LinkFail::Run)?;
seen.pairs.insert(visit);
seen.count += 1;
let Some(record) = self.records.get(m) else { return Ok(Ok(None)) };
// The module's own export of the name, looked up in its index, comes before any `export *`.
let explicit = record.explicit.get(name).and_then(|&i| record.info.exports.get(i));
match explicit {
Some(ExportEntry::Local { local, .. }) => return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))),
Some(ExportEntry::Indirect { request, import, .. }) => {
let (request, import) = (*request, import.clone());
let Some(t) = self.target(m, request) else { return Ok(Ok(None)) };
return match import {
ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))),
ImportName::Name(n) => self.resolve_export(t, &n, seen),
};
}
_ => {}
}
if name == "default" {
return Ok(Ok(None));
}
let mut star = None;
let stars = record.stars.clone();
for t in stars {
#[cfg(test)]
RESOLVED_STAR_EDGES.with(|count| count.set(count.get() + 1));
self.interp.use_fuel().map_err(LinkFail::Run)?;
match self.resolve_export(t, name, seen)? {
Err(Ambiguous) => return Ok(Err(Ambiguous)),
Ok(None) => {}
Ok(Some(r)) => match &star {
None => star = Some(r),
Some(s) if *s == r => {}
Some(_) => return Ok(Err(Ambiguous)),
},
}
}
Ok(Ok(star))
}
/// GetExportedNames (section 15.2.1.16.2): the names module `m` exports, those of its
/// `export *` modules but `default` included, each once.
fn exported_names(
&mut self,
m: usize,
star: bool,
visited: &mut Vec<usize>,
names: &mut Vec<String>,
seen: &mut HashSet<String>,
) -> Result<(), LinkFail> {
if visited.contains(&m) {
return Ok(());
}
visited.push(m);
let count = self.records.get(m).map_or(0, |r| r.info.exports.len());
for i in 0..count {
self.interp.use_fuel().map_err(LinkFail::Run)?;
let Some(e) = self.records.get(m).and_then(|r| r.info.exports.get(i)) else { break };
match e {
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
if !(star && export_name == "default") && !seen.contains(export_name) {
seen.insert(export_name.clone());
names.push(export_name.clone());
}
}
ExportEntry::Star { request, .. } => {
if let Some(t) = self.target(m, *request) {
self.exported_names(t, true, visited, names, seen)?;
}
}
}
}
Ok(())
}
/// The environment and name of the binding `name` of module `m`.
fn binding_of(&self, m: usize, name: &str) -> Option<(EnvId, crate::heap::Key)> {
let (lex, env) = self.records.get(m)?.envs?;
let k = key(name);
self.interp.module_binding(lex, env, &k).map(|e| (e, k))
}
/// GetModuleNamespace (section 15.2.1.18): module `m`'s namespace object, made the first time.
fn namespace(&mut self, m: usize) -> Result<ObjId, LinkFail> {
if let Some(ns) = self.records.get(m).and_then(|r| r.namespace) {
return Ok(ns);
}
let mut names = Vec::new();
self.exported_names(m, false, &mut Vec::new(), &mut names, &mut HashSet::new())?;
let mut resolved = Vec::new();
for name in names {
if let Ok(Some(r)) = self.resolve_export(m, &name, &mut ResolveSeen::default())? {
resolved.push((key(&name), r));
}
}
resolved.sort_by(|(a, _), (b, _)| a.cmp(b));
let mut exports = Vec::new();
let mut later = Vec::new();
for (k, r) in resolved {
match r {
Resolution::Binding { module, name } => match self.binding_of(module, &name) {
Some(b) => exports.push((k, Some(b))),
None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))),
},
Resolution::Namespace(module) => {
exports.push((k.clone(), None));
later.push((k, module));
}
}
}
let ns = self.interp.module_namespace(exports, &[]).map_err(LinkFail::Run)?;
self.interp.hold(Value::Object(ns));
if let Some(r) = self.records.get_mut(m) {
r.namespace = Some(ns);
}
// A namespace that holds another is made first, so two that hold each other end.
for (k, module) in later {
let inner = self.namespace(module)?;
let flags = crate::heap::WRITABLE | crate::heap::ENUMERABLE;
self.interp.define(ns, k, Prop::Data { value: Value::Object(inner), flags }).map_err(LinkFail::Run)?;
}
Ok(ns)
}
/// Binds each module's imports (section 15.2.1.16.4, steps 9 and 12), after checking that
/// each re-export resolves.
fn link_imports(&mut self) -> Result<(), LinkFail> {
for m in 0..self.records.len() {
let exports = self.records[m].info.exports.clone();
for e in &exports {
let ExportEntry::Indirect { export_name, request, span, .. } = e else { continue };
if self.target(m, *request).is_none() {
continue;
}
match self.resolve_export(m, export_name, &mut ResolveSeen::default())? {
Ok(Some(_)) => {}
Ok(None) => {
let message = format!("the module '{}' has no export to give as '{export_name}'", self.specifier(m, *request));
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
}
Err(Ambiguous) => {
let message = format!("the export '{export_name}' is ambiguous");
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
}
}
}
let imports = self.records[m].info.imports.clone();
let Some((_, env)) = self.records[m].envs else { return Err(LinkFail::Run(Abrupt::Internal("module not instantiated".into()))) };
for imp in imports {
let Some(t) = self.target(m, imp.request) else { continue };
let local = key(&imp.local.name);
let binding = match &imp.import {
ImportName::Namespace => self.namespace_binding(t)?,
ImportName::Name(n) => match self.resolve_export(t, n, &mut ResolveSeen::default())? {
Ok(Some(Resolution::Binding { module, name })) => match self.binding_of(module, &name) {
Some((target_env, target_name)) => Binding::import(target_env, target_name),
None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))),
},
Ok(Some(Resolution::Namespace(module))) => self.namespace_binding(module)?,
Ok(None) => {
let message = format!("the module '{}' has no export named '{n}'", self.specifier(m, imp.request));
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
}
Err(Ambiguous) => {
let message = format!("the export '{n}' of the module '{}' is ambiguous", self.specifier(m, imp.request));
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
}
},
};
if matches!(&imp.import, ImportName::Namespace) {
self.interp.use_fuel().map_err(LinkFail::Run)?;
let Some(Env::Decl { bindings, .. }) = self.interp.heap.env_mut(env) else {
return Err(LinkFail::Run(Abrupt::Internal("namespace import environment not found".into())));
};
let Some(slot) = bindings.get_mut(&local) else {
return Err(LinkFail::Run(Abrupt::Internal("namespace import binding not found".into())));
};
*slot = binding;
} else {
self.interp.add_import(env, local, binding).map_err(LinkFail::Run)?;
}
}
}
Ok(())
}
/// An immutable binding of module `m`'s namespace object.
fn namespace_binding(&mut self, m: usize) -> Result<Binding, LinkFail> {
let ns = self.namespace(m)?;
Ok(Binding { constant: true, lexical: true, ..Binding::new(Value::Object(ns), false, false) })
}
/// The modules in the order they run (section 15.2.1.16.5, ModuleEvaluation): each module
/// after the modules it imports, in the order it imports them, and each once; a module an
/// import cycle reaches again while it waits is not waited for.
fn evaluation_order(&self) -> Vec<(Rc<Code>, EnvId, EnvId)> {
let mut state = vec![0u8; self.records.len()];
let mut order = Vec::new();
let mut stack = vec![(0usize, 0usize)];
if let Some(s) = state.first_mut() {
*s = 1;
}
while let Some(top) = stack.last_mut() {
let m = top.0;
let requested = self.records.get(m).map_or(&[][..], |r| r.requested.as_slice());
if let Some(&t) = requested.get(top.1) {
top.1 += 1;
if let Some(s @ 0) = state.get_mut(t) {
*s = 1;
stack.push((t, 0));
}
continue;
}
stack.pop();
if let Some(r) = self.records.get(m)
&& let Some((lex, env)) = r.envs
{
order.push((r.code.clone(), lex, env));
}
}
order
}
}
+759
View File
@@ -0,0 +1,759 @@
use std::collections::{HashMap, HashSet};
use crate::{
JsValue, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Realm, RunError, RunErrorKind, parse, parse_module,
};
fn es() -> Realm {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
// Modules declare no globals, so they report through this array.
assert!(realm.run("var out = [];").is_ok());
realm
}
#[test]
fn global_var_records_survive_deleting_only_an_inherited_property() {
let mut realm = es();
realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap();
assert_eq!(realm.run("var w; delete this.w; Object.prototype.w = 7; delete w;"), Ok(JsValue::Bool(true)));
let error = realm.run("let w = 2; w;").unwrap_err();
assert!(matches!(error.kind, RunErrorKind::Syntax | RunErrorKind::Thrown), "{error:?}");
let mut realm = es();
realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap();
assert_eq!(realm.run("var w; delete w;"), Ok(JsValue::Bool(true)));
assert_eq!(realm.run("let w = 2; w;"), Ok(JsValue::Number(2.0)));
}
#[test]
fn namespace_allocations_charge_binding_tables_and_symbols() {
use crate::heap::{OBJECT_BYTES, PROP_BYTES, key};
let mut realm = es();
let interp = realm.interp();
let before = interp.heap.bytes;
let exports = (0..128).map(|n| (key(&format!("v{n}")), None)).collect();
let namespace = interp.module_namespace(exports, &[]).unwrap();
let symbols = interp.heap.object(namespace).unwrap().syms.as_ref().map_or(0, |symbols| symbols.len());
let required = OBJECT_BYTES + PROP_BYTES * (128 * 2 + symbols);
assert!(interp.heap.bytes - before >= required, "namespace charged {} bytes, needs at least {required}", interp.heap.bytes - before);
}
#[test]
fn export_resolution_membership_work_is_bounded_per_visit() {
let mut files: Vec<(String, String)> = (0..31).map(|n| (format!("./m{n}.mjs"), format!("export * from './m{}.mjs';", n + 1))).collect();
let source = (0..32).map(|n| format!("export var v{n} = {n};")).collect();
files.push(("./m31.mjs".into(), source));
let references: Vec<_> = files.iter().map(|(name, source)| (name.as_str(), source.as_str())).collect();
let mut load = loader(&references);
let mut realm = es();
crate::module::RESOLVE_CALLS.with(|count| count.set(0));
crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(0));
realm
.run_module("main.mjs", "import * as ns from './m0.mjs'; out.push(ns.v0, ns.v31);", ModuleLimits { modules: 64, depth: 64 }, &mut load)
.unwrap();
let visits = crate::module::RESOLVE_CALLS.with(std::cell::Cell::get);
let checks = crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(std::cell::Cell::get);
assert!(visits > 32);
assert!(checks <= visits * 4, "{checks} membership checks for {visits} export visits");
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("0|31".into())));
}
#[test]
fn star_aliases_resolve_each_canonical_target_once_per_name() {
let exports: String = (0..100).map(|n| format!("export var v{n} = {n};")).collect();
let stars: String = (0..100).map(|n| format!("export * from './alias{n}.mjs';")).collect();
let mut supplied = HashSet::new();
let mut load = |_: &str, specifier: &str| {
let (key, source) = if specifier == "./stars.mjs" { ("stars", &stars) } else { ("canonical", &exports) };
Ok(LoadedModule { key: key.into(), source: supplied.insert(key).then(|| source.clone()) })
};
let mut realm = es();
crate::module::RESOLVED_STAR_EDGES.with(|count| count.set(0));
realm
.run_module("main.mjs", "import * as ns from './stars.mjs'; out.push(ns.v99, Object.keys(ns).length);", ModuleLimits::default(), &mut load)
.unwrap();
let steps = crate::module::RESOLVED_STAR_EDGES.with(|count| count.get());
assert!(steps <= 200, "{steps} star edges inspected");
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("99|100".into()));
}
#[test]
fn ending_a_module_queue_restores_normal_frame_accounting() {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
let mut load = loader(&[("./m.mjs", "for (var i = 0; i < 1000; i++) {}")]);
realm.start_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load).unwrap();
assert!(matches!(realm.advance(1), Ok(Progress::Paused)));
realm.end();
assert_eq!(realm.run("function f() { return 1; } f();"), Ok(JsValue::Number(1.0)));
}
#[test]
fn pending_module_bodies_do_not_consume_active_call_frames() {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "function f() { return 1; } f();")];
let mut load = loader(&files);
let result = realm.run_module("main.mjs", "import './a.mjs';", ModuleLimits::default(), &mut load);
assert_eq!(result, Ok(JsValue::Undefined));
let mut load = loader(&[]);
let result = realm.run_module("main.mjs", "function f() { return f(); } f();", ModuleLimits::default(), &mut load);
assert_eq!(result.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Frames)));
}
#[test]
fn module_stack_excludes_bodies_waiting_to_run() {
let mut realm = es();
realm.define_host_object("$", [("stack".to_string(), crate::HostItem::Script(crate::ScriptItem::Stack))].into_iter().collect()).unwrap();
let (result, out) = run_with(
&mut realm,
"import './m.mjs';",
&[("./m.mjs", "function trace() { var s = $.stack; out.push(s.split('[global]').length - 1, s.indexOf('trace:') >= 0); } trace();")],
ModuleLimits::default(),
);
assert_eq!(result, Ok(JsValue::Undefined));
assert_eq!(out, "1|true");
}
#[test]
fn module_sources_charge_utf16_units_instead_of_utf8_bytes() {
let mut remaining = Vec::new();
for character in ['a', 'é', '界'] {
let source = format!("/*{}*/ export var value = 1;", character.to_string().repeat(1000));
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
let mut load = loader(&[]);
realm.start_module("main.mjs", &source, ModuleLimits::default(), &mut load).unwrap();
remaining.push(realm.fuel_left());
}
assert!(remaining.windows(2).all(|pair| pair[0] == pair[1]), "{remaining:?}");
}
#[test]
fn default_exported_functions_keep_their_public_names() {
for (source, name) in [
("export default function () {}", "default"),
("export default () => {};", "default"),
("export default (function () {});", "default"),
("export default function named() {}", "named"),
] {
let out = run("import value from './m.mjs'; out.push(value.name);", &[("./m.mjs", source)]);
assert_eq!(out, name, "{source}");
}
}
#[test]
fn symbol_writes_through_namespace_prototypes_are_refused() {
let out = run(
"import * as ns from './m.mjs'; var k = Symbol('new'), child = Object.create(ns); \
try { child[k] = 1; } catch (e) { out.push(e.name); } \
out.push(Object.getOwnPropertySymbols(child).length); \
Object.defineProperty(child, k, {value: 3, writable: true}); child[k] = 4; out.push(child[k]);",
&[("./m.mjs", "export var value = 1;")],
);
assert_eq!(out, "TypeError|0|4");
}
#[test]
fn a_namespace_exposes_its_own_immutable_symbol_tag() {
let out = run(
"import * as ns from './m.mjs'; \
var d = Object.getOwnPropertyDescriptor(ns, Symbol.toStringTag); \
out.push(ns[Symbol.toStringTag], Object.getOwnPropertySymbols(ns).length, \
d && d.writable, d && d.enumerable, d && d.configurable);",
&[("./m.mjs", "export var value = 1;")],
);
assert_eq!(out, "Module|1|false|false|false");
}
#[test]
fn modules_reject_await_identifiers_before_running_dependencies() {
for source in ["export const await = 1;", "var aw\\u0061it = 1;", "await;", "function await() {}"] {
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
}
let mut realm = es();
let mut load = loader(&[("./effect.mjs", "out.push('dependency');")]);
let result = realm.run_module("main.mjs", "import './effect.mjs'; export const await = 1;", ModuleLimits::default(), &mut load);
assert!(result.is_err());
assert_eq!(realm.run("out.length").unwrap(), JsValue::Number(0.0));
assert!(realm.run("var await = 1; await").is_ok());
}
#[test]
fn synchronous_and_sliced_modules_drain_promise_jobs() {
let source = "out.push('body'); Promise.resolve().then(function () { out.push('resolved'); }); \
Promise.reject('rejected').catch(function (e) { out.push(e); });";
for sliced in [false, true] {
let mut realm = es();
let mut load = loader(&[]);
if sliced {
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
loop {
match realm.advance(100).unwrap() {
Progress::Paused => {}
Progress::Done(value) => {
assert_eq!(value, JsValue::Undefined);
break;
}
}
}
} else {
assert_eq!(realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap(), JsValue::Undefined);
}
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("body|resolved|rejected".into()), "sliced={sliced}");
}
}
#[test]
fn starting_a_module_discards_a_paused_script() {
for (sliced, invalid) in [(false, false), (true, false), (false, true), (true, true)] {
let mut realm = es();
realm.start("out.push('old');").unwrap();
assert_eq!(realm.advance(1).unwrap(), Progress::Paused);
let mut load = loader(&[]);
let source = if invalid { "var = ;" } else { "out.push('new');" };
if invalid {
let result = if sliced {
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load)
} else {
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).map(drop)
};
assert!(result.is_err());
assert!(!realm.is_running(), "sliced={sliced}");
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String(String::new()));
continue;
}
if sliced {
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
loop {
if let Progress::Done(_) = realm.advance(100).unwrap() {
break;
}
}
} else {
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
}
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("new".into()), "sliced={sliced}");
}
}
/// A loader over `files`: each specifier is its own key, given with its source the first time.
fn loader(files: &[(&str, &str)]) -> impl FnMut(&str, &str) -> Result<LoadedModule, LoadError> + use<> {
let map: HashMap<String, String> = files.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
let mut given = HashSet::new();
move |_, specifier| {
if !specifier.starts_with('.') && specifier != "main" {
return Err(LoadError::Syntax(format!("bare specifier: {specifier}")));
}
let source = map.get(specifier).ok_or_else(|| LoadError::Other(format!("module not found: {specifier}")))?;
let first = given.insert(specifier.to_string());
Ok(LoadedModule { key: specifier.to_string(), source: first.then(|| source.clone()) })
}
}
/// Runs `entry` with the modules `files`. → the result and `out` joined with `|`.
fn run_with(realm: &mut Realm, entry: &str, files: &[(&str, &str)], limits: ModuleLimits) -> (Result<JsValue, RunError>, String) {
let mut load = loader(files);
let result = realm.run_module("main.mjs", entry, limits, &mut load);
let out = match realm.run("out.join('|')") {
Ok(JsValue::String(s)) => s,
other => panic!("{other:?}"),
};
(result, out)
}
fn run(entry: &str, files: &[(&str, &str)]) -> String {
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
(Ok(v), out) => {
assert_eq!(v, JsValue::Undefined);
out
}
(Err(e), _) => panic!("{entry}\n{e:?}"),
}
}
/// The run ends with an error whose message starts with `start`, and `out` holds `ran`.
fn fails(entry: &str, files: &[(&str, &str)], start: &str, ran: &str) -> RunError {
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
(Err(e), out) => {
assert!(e.message.starts_with(start), "{entry}: {e:?}");
assert_eq!(out, ran, "{entry}");
e
}
(Ok(_), out) => panic!("{entry}: completed with {out}"),
}
}
fn syntax(src: &str) {
assert!(parse_module(src, &Options::default()).is_err(), "{src}");
}
#[test]
fn an_import_reads_the_exporting_binding_each_time() {
let counter = "export let count = 0; export function inc() { count++; }";
let out = run("import { count, inc } from './c.mjs'; out.push(count); inc(); inc(); out.push(count);", &[("./c.mjs", counter)]);
assert_eq!(out, "0|2");
}
#[test]
fn imports_can_be_renamed_and_combined() {
let m = "export default 'd'; export var a = 1; export const b = 2;";
let out = run("import d, { a as x, b } from './m.mjs'; out.push(d, x, b);", &[("./m.mjs", m)]);
assert_eq!(out, "d|1|2");
let out = run("import d, * as ns from './m.mjs'; out.push(d, ns.a, ns['default']);", &[("./m.mjs", m)]);
assert_eq!(out, "d|1|d");
}
#[test]
fn a_destructuring_declaration_exports_every_name_it_binds() {
let m = "export const { a, b: [c, ...d] } = { a: 1, b: [2, 3, 4] }; export var [e = 5] = [];";
let out = run("import { a, c, d, e } from './m.mjs'; out.push(a, c, d.join('+'), e);", &[("./m.mjs", m)]);
assert_eq!(out, "1|2|3+4|5");
}
#[test]
fn default_exports_of_expressions_and_functions() {
let out = run("import v from './v.mjs'; out.push(v * 2);", &[("./v.mjs", "export default 20 + 1;")]);
assert_eq!(out, "42");
let out = run("import f from './f.mjs'; out.push(f());", &[("./f.mjs", "export default function () { return 'anon'; }")]);
assert_eq!(out, "anon");
// A named default function is a declaration: hoisted, and its name is bound in the module.
let f = "out.push(typeof g); export default function g() { return 'g'; }";
let out = run("import h from './f.mjs'; out.push(h());", &[("./f.mjs", f)]);
assert_eq!(out, "function|g");
}
#[test]
fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() {
let m = "export var zeta = 1; export let alpha = 2; export function mid() {} export default 3;";
let out = run(
"import * as ns from './m.mjs';
out.push(Object.keys(ns).join(','), Object.prototype.toString.call(ns), Object.isExtensible(ns), Object.getPrototypeOf(ns) === null);
try { ns.alpha = 5; } catch (e) { out.push(e.name); }
try { ns.added = 5; } catch (e) { out.push(e.name); }
try { delete ns.alpha; } catch (e) { out.push(e.name); }
out.push(ns.alpha, Object.getOwnPropertyDescriptor(ns, 'zeta').writable);",
&[("./m.mjs", m)],
);
assert_eq!(out, "alpha,default,mid,zeta|[object Module]|false|true|TypeError|TypeError|TypeError|2|true");
}
#[test]
fn a_write_that_reaches_a_namespace_through_a_prototype_is_refused() {
let m = "export var alpha = 1;";
let out = run(
"import * as ns from './m.mjs';
var o = Object.create(ns);
Object.defineProperty(o, 'own', { value: 1, writable: true });
o.own = 2;
try { o.alpha = 5; } catch (e) { out.push(e.name); }
try { o.fresh = 5; } catch (e) { out.push(e.name); }
try { Object.create(o).alpha = 5; } catch (e) { out.push(e.name); }
out.push(o.own, Object.getOwnPropertyNames(o).join(), ns.alpha, o.alpha);",
&[("./m.mjs", m)],
);
assert_eq!(out, "TypeError|TypeError|TypeError|2|own|1|1");
// A script's sloppy write is ignored.
let mut realm = es();
let out = run_with(&mut realm, "import * as ns from './m.mjs'; out.ns = ns;", &[("./m.mjs", m)], ModuleLimits::default());
assert_eq!(out, (Ok(JsValue::Undefined), String::new()));
// A namespace has no prototype, so `hasOwnProperty` is called from `Object.prototype`.
let sloppy = "var o = Object.create(out.ns), own = Object.prototype.hasOwnProperty; o.alpha = 5; o.fresh = 5; \
[own.call(o, 'alpha'), own.call(o, 'fresh'), o.alpha].join()";
assert_eq!(realm.run(sloppy), Ok(JsValue::String("false,false,1".into())));
}
#[test]
fn a_namespace_takes_only_definitions_that_change_nothing() {
let m = "export var a = 1;";
let out = run(
"import * as ns from './m.mjs';
out.push(Object.seal(ns) === ns, Object.isSealed(ns), Object.isFrozen(ns));
out.push(Object.defineProperty(ns, 'a', { value: 1, writable: true, enumerable: true, configurable: false }) === ns);
var ds = [{ value: 2 }, { writable: false }, { enumerable: false }, { configurable: true }, { get: function () {} }];
for (var i = 0; i < ds.length; i++) {
try { Object.defineProperty(ns, 'a', ds[i]); out.push('defined'); } catch (e) { out.push(e.name); }
}
try { Object.defineProperty(ns, 'b', { value: 1 }); } catch (e) { out.push(e.name); }
try { Object.freeze(ns); } catch (e) { out.push(e.name); }
out.push(ns.a);",
&[("./m.mjs", m)],
);
assert_eq!(out, "true|true|false|true|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|1");
}
#[test]
fn a_namespace_reads_live_values() {
let m = "export var n = 1; export function bump() { n = n + 1; }";
let out = run("import * as ns from './m.mjs'; ns.bump(); out.push(ns.n);", &[("./m.mjs", m)]);
assert_eq!(out, "2");
}
#[test]
fn assigning_to_an_import_is_a_type_error() {
let m = "export var a = 1;";
let out = run("import { a } from './m.mjs'; try { a = 2; } catch (e) { out.push(e.name); } out.push(a);", &[("./m.mjs", m)]);
assert_eq!(out, "TypeError|1");
let out = run("import * as ns from './m.mjs'; try { ns = 2; } catch (e) { out.push(e.name); }", &[("./m.mjs", m)]);
assert_eq!(out, "TypeError");
}
#[test]
fn a_cycle_of_two_modules_runs_each_once_dependency_first() {
// main imports b, b imports main back: b runs first and sees main's hoisted function.
let b = "import { fa } from 'main'; out.push('b ' + fa()); export const b = 'B';";
let mut realm = es();
let mut load = loader(&[("./b.mjs", b), ("main", "")]);
let mut load = |referrer: &str, specifier: &str| {
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { load(referrer, specifier) }
};
let entry = "import { b } from './b.mjs'; export function fa() { return 'fa'; } out.push('a ' + b);";
let r = realm.run_module("main.mjs", entry, ModuleLimits::default(), &mut load);
assert_eq!(r, Ok(JsValue::Undefined));
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b fa|a B".into())));
}
#[test]
fn reading_an_import_before_its_module_ran_is_a_reference_error() {
let b = "import { a } from 'main'; out.push('b'); out.push(a);";
let mut realm = es();
let mut inner = loader(&[("./b.mjs", b)]);
let mut load = |referrer: &str, specifier: &str| {
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
};
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
match r {
Err(e) => assert!(e.message.starts_with("ReferenceError"), "{e:?}"),
other => panic!("{other:?}"),
}
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b".into())));
}
#[test]
fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() {
let b = "import * as ns from 'main';
var tries = [() => ns.a, () => Object.keys(ns), () => Object.prototype.hasOwnProperty.call(ns, 'a'), () => Object.prototype.propertyIsEnumerable.call(ns, 'a'),
() => Object.getOwnPropertyDescriptor(ns, 'a'), () => Object.isSealed(ns), () => Object.isFrozen(ns),
() => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns),
() => Object.create(ns).a, () => Object.create(Object.create(ns)).a];
tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } });
// Listing the export names reads none of them.
var names = [];
for (var k in ns) names.push(k);
out.push(names.join(), 'a' in ns, 'a' in Object.create(ns), Object.getOwnPropertyNames(ns).join());";
let mut realm = es();
let mut inner = loader(&[("./b.mjs", b)]);
let mut load = |referrer: &str, specifier: &str| {
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
};
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
assert_eq!(r, Ok(JsValue::Undefined));
let errors = "ReferenceError|".repeat(13);
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}a|true|true|a"))));
}
#[test]
fn a_module_two_modules_import_runs_once() {
let shared = "out.push('shared'); export var s = 1;";
let a = "import { s } from './shared.mjs'; out.push('a' + s);";
let b = "import { s } from './shared.mjs'; out.push('b' + s);";
let out = run("import './a.mjs'; import './b.mjs'; out.push('main');", &[("./shared.mjs", shared), ("./a.mjs", a), ("./b.mjs", b)]);
assert_eq!(out, "shared|a1|b1|main");
}
#[test]
fn re_exports_pass_names_on() {
let base = "export var x = 1, y = 2; export default 'base';";
let mid = "export { x as renamed } from './base.mjs'; export * from './base.mjs'; export * as all from './base.mjs';";
let out = run(
"import { renamed, x, y, all } from './mid.mjs'; import * as m from './mid.mjs'; out.push(renamed, x, y, all['default'], Object.keys(m).join(','));",
&[("./base.mjs", base), ("./mid.mjs", mid)],
);
// `export *` does not pass `default` on.
assert_eq!(out, "1|1|2|base|all,renamed,x,y");
}
#[test]
fn an_exported_import_is_a_re_export() {
let base = "export var v = 'v';";
let mid = "import { v } from './base.mjs'; import * as ns from './base.mjs'; export { v as w, ns };";
let out = run("import { w, ns } from './mid.mjs'; out.push(w, ns.v);", &[("./base.mjs", base), ("./mid.mjs", mid)]);
assert_eq!(out, "v|v");
}
#[test]
fn a_name_two_stars_give_is_ambiguous() {
let files =
[("./a.mjs", "export var n = 1;"), ("./b.mjs", "export var n = 2;"), ("./both.mjs", "export * from './a.mjs'; export * from './b.mjs';")];
fails("import { n } from './both.mjs'; out.push('ran');", &files, "SyntaxError: the export 'n'", "");
// The namespace leaves the name out.
let out = run("import * as ns from './both.mjs'; out.push(Object.keys(ns).length);", &files);
assert_eq!(out, "0");
}
#[test]
fn a_missing_export_ends_the_run_before_any_module_runs() {
let files = [("./m.mjs", "out.push('m'); export var a = 1;")];
let e = fails("import { nope } from './m.mjs';\nout.push('main');", &files, "SyntaxError: the module './m.mjs' has no export named 'nope'", "");
assert_eq!((e.line, e.column), (1, 10));
let files = [("./m.mjs", "export { nothing as gone } from './n.mjs';"), ("./n.mjs", "")];
fails("import './m.mjs';", &files, "SyntaxError: the module './n.mjs' has no export to give as 'gone'", "");
}
#[test]
fn a_module_the_loader_cannot_give_is_named_in_the_error() {
let e = fails("out.push(1);\nimport { a } from './missing.mjs';", &[], "Error: module not found: ./missing.mjs", "");
assert_eq!(e.line, 2);
fails("import x from 'lib';", &[], "SyntaxError: bare specifier: lib", "");
}
#[test]
fn a_syntax_error_in_an_imported_module_names_its_source() {
let mut realm = es();
let mut load = loader(&[("./a.mjs", "out.push('a');"), ("./bad.mjs", "\nvar = ;")]);
let r = realm.run_module("main.mjs", "import './a.mjs'; import './bad.mjs';", ModuleLimits::default(), &mut load);
let e = r.err().unwrap_or_else(|| panic!("ran"));
assert_eq!((e.kind, e.line), (RunErrorKind::Syntax, 2));
// The entry is source 0, then each module in the order it was loaded.
assert_eq!(realm.error_source(), 2);
assert_eq!(realm.run("out.length"), Ok(JsValue::Number(0.0)));
}
#[test]
fn module_code_is_strict_and_its_this_is_undefined() {
let out = run("out.push(this === undefined, (() => this)() === undefined); try { undeclared = 1; } catch (e) { out.push(e.name); }", &[]);
assert_eq!(out, "true|true|ReferenceError");
// Its declarations stay in the module.
let mut realm = es();
let (r, _) = run_with(&mut realm, "var hidden = 1; function also() {}", &[], ModuleLimits::default());
assert_eq!(r, Ok(JsValue::Undefined));
assert_eq!(realm.run("typeof hidden + typeof also"), Ok(JsValue::String("undefinedundefined".into())));
}
#[test]
fn an_exception_in_a_module_ends_the_run_and_the_modules_after_it_do_not_run() {
let files = [("./a.mjs", "out.push('a'); throw new TypeError('stop');"), ("./b.mjs", "try { out.push('b'); } catch (e) { out.push('caught'); }")];
fails("import './a.mjs'; import './b.mjs'; try { out.push('main'); } catch (e) {}", &files, "TypeError: stop", "a");
}
#[test]
fn the_module_count_and_import_depth_are_limited() {
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "out.push('c');")];
let mut realm = es();
let (r, out) = run_with(&mut realm, "import './a.mjs';", &files, ModuleLimits { modules: 3, depth: 16 });
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (3) reached at './c.mjs'")), "{r:?}");
assert_eq!(out, "");
let (r, _) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: import depth limit (2) reached at './c.mjs'")), "{r:?}");
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 4, depth: 3 });
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "c"));
}
#[test]
fn a_module_at_the_depth_limit_may_import_a_module_already_loaded() {
let files = [("./a.mjs", "import './b.mjs'; out.push('a');"), ("./b.mjs", "import './a.mjs'; out.push('b');")];
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "b|a"));
}
#[test]
fn a_module_limit_of_zero_runs_no_module() {
let (r, out) = run_with(&mut es(), "out.push('main');", &[], ModuleLimits { modules: 0, depth: 16 });
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (0) reached")), "{r:?}");
assert_eq!(out, "");
}
#[test]
fn a_module_run_is_held_to_the_fuel_limit() {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 50, ..Limits::default() });
let mut load = loader(&[("./m.mjs", &"var a = 1;\n".repeat(20))]);
let r = realm.run_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load);
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel)));
}
#[test]
fn a_module_run_advances_in_slices_and_runs_each_module_in_turn() {
let mut realm = es();
let mut load = loader(&[("./a.mjs", "for (var i = 0; i < 200; i++) {} out.push('a');")]);
let entry = "import './a.mjs'; for (var j = 0; j < 200; j++) {} out.push('main');";
assert_eq!(realm.start_module("main.mjs", entry, ModuleLimits::default(), &mut load), Ok(()));
let mut slices = 0;
loop {
match realm.advance(10) {
Ok(Progress::Paused) => slices += 1,
Ok(Progress::Done(v)) => {
assert_eq!(v, JsValue::Undefined);
break;
}
Err(e) => panic!("{e:?}"),
}
}
assert!(slices > 20, "{slices}");
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("a|main".into())));
}
#[test]
fn an_es5_realm_runs_no_module() {
let mut realm = Realm::new();
let mut load = loader(&[]);
let r = realm.run_module("main.mjs", "export var a = 1;", ModuleLimits::default(), &mut load);
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Syntax));
}
#[test]
fn a_script_does_not_read_import_or_export() {
for src in ["import a from './a.mjs';", "export var a = 1;", "import './a.mjs';"] {
assert!(parse(src, &Options { es2015: true, ..Options::default() }).is_err(), "{src}");
assert!(es().run(src).is_err_and(|e| e.kind == RunErrorKind::Syntax), "{src}");
}
}
#[test]
fn module_early_errors() {
for src in [
"export var a; export { a };",
"export { undeclared };",
"export default 1; export default 2;",
"import { a } from './x.mjs'; var a;",
"var a; import a from './x.mjs';",
"import { a, a } from './x.mjs';",
"function f() { import a from './x.mjs'; }",
"{ export var a; }",
"import { default } from './x.mjs';",
"export { default };",
"import a from x;",
"import * from './x.mjs';",
"with (a) {}",
"export default class {}",
"import('./x.mjs');",
"#include 'x.js'\n",
// Top-level functions are lexical declarations in a module.
"function f() {} function f() {}",
"var f; function f() {}",
"function f() {} var f;",
"let f; function f() {}",
] {
syntax(src);
}
for src in [
"import { default as d, if as i } from './x.mjs'; export { d as default, i as if };",
"import {} from './x.mjs'; export {};",
"export function f() {} export { f as g };",
"var as = 1, from = 2; export { as, from };",
"export * as default from './x.mjs';",
"function f() {} { function f() {} } function g() { var g; function h() {} var h; }",
] {
assert!(parse_module(src, &Options::default()).is_ok(), "{src}");
}
}
#[test]
fn a_module_lists_what_it_imports_and_exports() {
let (_, info) =
match parse_module("import a, { b as c } from './x.mjs'; export { c as d }; export * from './y.mjs'; import './x.mjs';", &Options::default())
{
Ok(p) => p,
Err(e) => panic!("{e:?}"),
};
let specifiers: Vec<&str> = info.requests.iter().map(|r| r.specifier.as_str()).collect();
assert_eq!(specifiers, ["./x.mjs", "./y.mjs"]);
assert_eq!(info.imports.len(), 2);
assert!(
matches!(&info.exports[..], [crate::ExportEntry::Star { request: 1, .. }, crate::ExportEntry::Indirect { export_name, request: 0, .. }] if export_name == "d")
);
}
#[test]
fn a_specifier_with_an_unpaired_surrogate_parses_and_no_module_has_it() {
let src = "import './\\uD800.mjs'; import './\\uFFFD.mjs'; import './\\uDC00.mjs'; import './\\uD800.mjs';";
let (_, info) = match parse_module(src, &Options::default()) {
Ok(p) => p,
Err(e) => panic!("{e:?}"),
};
let units: Vec<&[u16]> = info.requests.iter().map(|r| r.units.as_slice()).collect();
let dot = [u16::from(b'.'), u16::from(b'/')];
let ext: Vec<u16> = ".mjs".encode_utf16().collect();
let with = |u: u16| [&dot[..], &[u], &ext[..]].concat();
assert_eq!(units, [with(0xD800).as_slice(), with(0xFFFD).as_slice(), with(0xDC00).as_slice()]);
assert_eq!(info.requests[0].specifier, "./\u{FFFD}.mjs");
// The run stops when the module is to be loaded, before any module runs, and the loader is
// not asked for it.
let e = fails("out.push('ran'); import './\\uD800.mjs';", &[], "SyntaxError: module specifier './\u{FFFD}.mjs' is not valid text", "");
assert_eq!(e.line, 1);
}
#[test]
fn a_namespace_of_many_exports_lists_each_once_in_order() {
let names: Vec<String> = (0..3000).rev().map(|i| format!("e{i}")).collect();
let m: String = names.iter().map(|n| format!("export var {n} = '{n}';")).collect();
let star = "export * from './m.mjs'; export var e5 = 'own';";
let out = run(
"import * as ns from './star.mjs'; var k = Object.keys(ns); out.push(k.length, k[0], k[k.length - 1], ns.e5, ns.e2999);",
&[("./m.mjs", m.as_str()), ("./star.mjs", star)],
);
assert_eq!(out, "3000|e0|e999|own|e2999");
}
#[test]
fn modules_survive_a_collection_while_they_link() {
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 64 << 20, ..Limits::default() });
assert!(realm.run("var out = []; var junk = []; for (var i = 0; i < 2000; i++) junk.push({ i: i }); junk = null;").is_ok());
let m = "export var v = 'kept'; export function f() { return v; }";
let mut load = loader(&[("./m.mjs", m)]);
// A collection runs at every heap reservation while the modules load and link, before any
// of their code runs.
let before = realm.interp().heap.collections;
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
let started = realm.start_module(
"main.mjs",
"import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());",
ModuleLimits::default(),
&mut load,
);
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
assert_eq!(started, Ok(()));
assert!(realm.interp().heap.collections > before);
assert!(matches!(realm.advance(1_000_000), Ok(Progress::Done(JsValue::Undefined))));
realm.collect_garbage();
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into())));
}
#[test]
fn the_heap_counts_each_module_from_when_it_loads() {
// Each module holds about 4 MB of code (its text and its string). The heap holds one of them,
// and not two, so the run stops while the second loads and never asks for the third.
let body = format!("export var v = '{}';", "x".repeat(1_000_000));
let limits = || Limits { heap_bytes: 7 << 20, ..Limits::default() };
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
assert!(realm.run("var out = [];").is_ok());
let one = run_with(&mut realm, "import { v } from './a.mjs'; out.push(v.length);", &[("./a.mjs", body.as_str())], ModuleLimits::default());
assert_eq!(one, (Ok(JsValue::Undefined), "1000000".to_string()));
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
let asked = std::cell::RefCell::new(Vec::new());
let mut inner = loader(&[("./a.mjs", body.as_str()), ("./b.mjs", body.as_str()), ("./c.mjs", "")]);
let mut load = |referrer: &str, specifier: &str| {
asked.borrow_mut().push(specifier.to_string());
inner(referrer, specifier)
};
let r = realm.run_module("main.mjs", "import './a.mjs'; import './b.mjs'; import './c.mjs';", ModuleLimits::default(), &mut load);
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. })), "{r:?}");
assert_eq!(*asked.borrow(), ["./a.mjs", "./b.mjs"]);
}
#[test]
fn a_module_keeps_no_expression_value_alive_after_its_statement() {
// The heap holds one of these arrays and not two, so each must be collectable once the
// expression statement that made it ends.
let big = "function big() { var a = []; for (var i = 0; i < 50000; i++) a[i] = { i: i }; return a; }";
let mut realm = es();
assert!(realm.run(&format!("{big} var held = big();")).is_ok());
let with_one = realm.collect_garbage();
assert!(realm.run("held = null;").is_ok());
let without = realm.collect_garbage();
let one = with_one - without;
realm.set_limits(Limits { heap_bytes: without + one * 3 / 2, ..Limits::default() });
let entry = format!("{big} big(); big(); try {{ big(); }} finally {{ big(); }} out.push('done');");
let (r, out) = run_with(&mut realm, &entry, &[], ModuleLimits::default());
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "done"));
// Script and eval code still complete with the value of their last expression statement.
assert_eq!(realm.run("1; 2;"), Ok(JsValue::Number(2.0)));
assert_eq!(realm.run("eval('3; 4;')"), Ok(JsValue::Number(4.0)));
assert_eq!(realm.run("try { 5; } finally { 6; }"), Ok(JsValue::Number(5.0)));
}
+11
View File
@@ -7,6 +7,7 @@
//! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long
//! runs of them do not nest at all.
mod module;
mod pattern;
mod xml;
@@ -134,6 +135,9 @@ pub(crate) struct Parser<'s> {
scopes: Vec<Scope>,
/// What `super` and `new.target` may do in the function being read.
supers: SuperRules,
/// Read a module ([`Parser::parse_module`]): its top-level function declarations are lexical
/// declarations (ECMA-262 2015 section 15.2.1.11).
module: bool,
/// Where each shorthand property with an initializer (`{a = 1}`) not yet read as part of a
/// destructuring pattern starts; one left when its expression ends is a `SyntaxError`.
cover_inits: Vec<u32>,
@@ -175,6 +179,7 @@ impl<'s> Parser<'s> {
es2015: options.es2015,
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
supers: SuperRules::default(),
module: false,
cover_inits: Vec::new(),
cover_ok: false,
rest_commas: HashSet::new(),
@@ -332,6 +337,9 @@ impl<'s> Parser<'s> {
/// Checks a name used as an identifier: not a reserved word written with escapes, and not a
/// strict-mode reserved word in strict code.
fn check_identifier(&self, token: &Token, name: &str) -> Result<()> {
if self.module && name == "await" {
return Err(self.error_at_token(token, "'await' is a reserved word in modules"));
}
if token.escaped && Keyword::from_word(name).is_some() {
return Err(self.error_at_token(token, format!("keyword '{name}' must not contain escaped characters")));
}
@@ -431,6 +439,9 @@ impl<'s> Parser<'s> {
/// body or the script, lexical in a block.
fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> {
let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) };
if self.module && self.scopes.len() == 1 {
return self.declare_lexical(&name, true);
}
match self.scopes.last_mut() {
Some(scope) if scope.function => {
if scope.lexical.contains_key(&name.name) {
+481
View File
@@ -0,0 +1,481 @@
//! Module code (ECMA-262 2015 section 15.2): the import and export declarations at the top of a
//! module, read into a [`ModuleInfo`], and their early errors (section 15.2.1.1).
//!
//! A module is strict mode code throughout. An import binds its names as lexical declarations at
//! the top of the module, so a `var`, `let`, `const`, function or another import of the same name
//! is a redeclaration. An exported declaration is kept as the declaration; `export default` of an
//! expression or an anonymous function binds [`DEFAULT_BINDING`]. Each exported name may be
//! exported once, and a name an `export { … }` list exports from the module itself must be one it
//! declares or imports.
use std::collections::{HashMap, HashSet};
use super::{Parser, Result, describe};
use crate::ast::{
Binding, DEFAULT_BINDING, ExportEntry, FunctionKind, ImportEntry, ImportName, LexKind, ModuleInfo, ModuleRequest, Name, Program, Stmt, StmtId,
VarDecl,
};
use crate::token::{Keyword, Punct, Span, Token, TokenKind};
/// A name an `export { … }` list without `from` exports: the module's own binding (or import)
/// `local`, exported as `export_name`.
struct ClauseExport {
export_name: String,
local: String,
span: Span,
}
#[derive(Eq)]
struct RequestUnits(Vec<u16>);
impl std::hash::Hash for RequestUnits {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::hash::Hash::hash(&self.0, state);
}
}
impl PartialEq for RequestUnits {
fn eq(&self, other: &Self) -> bool {
#[cfg(test)]
REQUEST_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
self.0 == other.0
}
}
#[derive(Eq)]
struct ImportLocal<'a>(&'a str);
impl std::hash::Hash for ImportLocal<'_> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::hash::Hash::hash(self.0, state);
}
}
impl PartialEq for ImportLocal<'_> {
fn eq(&self, other: &Self) -> bool {
#[cfg(test)]
EXPORT_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
self.0 == other.0
}
}
#[cfg(test)]
thread_local! {
static REQUEST_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static EXPORT_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
impl Parser<'_> {
/// Reads the source as a module: its statements, without its import and export declarations
/// but with the declarations they export, and what it imports and exports.
pub(crate) fn parse_module(mut self) -> Result<(Program, ModuleInfo, Vec<Token>)> {
self.module = true;
#[cfg(test)]
REQUEST_SEARCH_STEPS.with(|steps| steps.set(0));
let mut info = ModuleInfo::default();
let mut requests = HashMap::new();
let mut clause = Vec::new();
let mut body = Vec::new();
while self.tok.kind != TokenKind::Eof {
if self.at_keyword(Keyword::Import) {
self.import_declaration(&mut info, &mut requests)?;
} else if self.at_keyword(Keyword::Export) {
if let Some(stmt) = self.export_declaration(&mut info, &mut clause, &mut requests)? {
body.push(stmt);
}
} else {
body.push(self.parse_statement_item()?);
}
}
self.finish_exports(&mut info, clause)?;
if let Some(tokens) = &mut self.tokens {
tokens.push(self.tok.clone());
}
let program =
Program { ast: self.ast, body, strict: true, directives: self.directives, lines: self.lines, es2015: self.es2015, supers: self.supers };
Ok((program, info, self.tokens.unwrap_or_default()))
}
/// The current token is the contextual keyword `word` (`as` or `from`), written without escapes.
fn at_contextual(&self, word: &str) -> bool {
self.tok.ident() == Some(word) && !self.tok.escaped
}
fn expect_contextual(&mut self, word: &str) -> Result<()> {
if self.at_contextual(word) {
self.bump()?;
return Ok(());
}
Err(self.error_at_token(&self.tok, format!("expected '{word}' but found {}", describe(&self.tok))))
}
/// A module specifier: a string literal, added to the module's requests once. → its index.
/// Any string value is a specifier here; the host decides which it can load.
fn module_specifier(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<usize> {
let TokenKind::String(units) = &self.tok.kind else {
return Err(self.error_at_token(&self.tok, format!("expected a module specifier string but found {}", describe(&self.tok))));
};
if self.tok.legacy_octal {
return Err(self.error_at_token(&self.tok, "octal escape sequences are not allowed in strict mode"));
}
let units = RequestUnits(units.to_vec());
let span = self.bump()?.span;
if let Some(index) = requests.get(&units) {
return Ok(*index);
}
let specifier = String::from_utf16_lossy(&units.0);
let index = info.requests.len();
info.requests.push(ModuleRequest { specifier, units: units.0.clone(), span });
requests.insert(units, index);
Ok(info.requests.len() - 1)
}
/// A name as an import or export list gives it: any identifier name, keywords included. → the
/// name and whether it was an identifier (not a keyword).
fn list_name(&mut self) -> Result<(Name, bool)> {
let Some(name) = self.tok.identifier_name().map(str::to_string) else {
return Err(self.error_at_token(&self.tok, format!("expected a name but found {}", describe(&self.tok))));
};
let ident = matches!(self.tok.kind, TokenKind::Ident(_));
let token = self.bump()?;
Ok((Name { name, span: token.span }, ident))
}
/// `import …;` (section 15.2.2). Each name it binds is declared in the module's scope.
fn import_declaration(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<()> {
let import = self.bump()?;
if self.at(Punct::LParen) {
return Err(self.error_at_token(&import, "import() is not supported"));
}
if matches!(self.tok.kind, TokenKind::String(_)) {
self.module_specifier(info, requests)?;
return self.semicolon();
}
let mut bound: Vec<(ImportName, Name)> = Vec::new();
let mut list = true;
if matches!(self.tok.kind, TokenKind::Ident(_)) {
let local = self.binding_identifier()?;
bound.push((ImportName::Name("default".into()), local));
list = self.eat(Punct::Comma)?;
}
if list {
if self.eat(Punct::Star)? {
self.expect_contextual("as")?;
let local = self.binding_identifier()?;
bound.push((ImportName::Namespace, local));
} else {
self.expect(Punct::LBrace)?;
while !self.at(Punct::RBrace) {
if matches!(self.tok.kind, TokenKind::Ident(_)) && !self.next_is_as() {
// A name without `as` binds itself, so it must be one a declaration may bind.
let local = self.binding_identifier()?;
bound.push((ImportName::Name(local.name.clone()), local));
} else {
let (imported, _) = self.list_name()?;
self.expect_contextual("as")?;
let local = self.binding_identifier()?;
bound.push((ImportName::Name(imported.name), local));
}
if !self.eat(Punct::Comma)? {
break;
}
}
self.expect(Punct::RBrace)?;
}
}
self.expect_contextual("from")?;
let request = self.module_specifier(info, requests)?;
self.semicolon()?;
for (import, local) in bound {
self.declare_lexical(&local, false)?;
info.imports.push(ImportEntry { request, import, local });
}
Ok(())
}
/// The token after the current one is the contextual keyword `as`.
fn next_is_as(&self) -> bool {
self.peek().is_some_and(|t| !t.escaped && t.ident() == Some("as"))
}
/// `export …` (section 15.2.3). → the declaration it exports, which runs in place.
fn export_declaration(
&mut self,
info: &mut ModuleInfo,
clause: &mut Vec<ClauseExport>,
requests: &mut HashMap<RequestUnits, usize>,
) -> Result<Option<StmtId>> {
let export = self.bump()?;
let span = export.span;
if self.eat(Punct::Star)? {
if self.at_contextual("as") {
self.bump()?;
let (name, _) = self.list_name()?;
self.expect_contextual("from")?;
let request = self.module_specifier(info, requests)?;
self.semicolon()?;
info.exports.push(ExportEntry::Indirect { export_name: name.name, request, import: ImportName::Namespace, span: name.span });
return Ok(None);
}
self.expect_contextual("from")?;
let request = self.module_specifier(info, requests)?;
self.semicolon()?;
info.exports.push(ExportEntry::Star { request, span });
return Ok(None);
}
if self.at(Punct::LBrace) {
self.bump()?;
// Each name: the name it refers to (and whether that was an identifier) and the name it
// is exported as.
let mut names: Vec<(Name, bool, Name)> = Vec::new();
while !self.at(Punct::RBrace) {
let (local, ident) = self.list_name()?;
let exported = if self.at_contextual("as") {
self.bump()?;
self.list_name()?.0
} else {
local.clone()
};
names.push((local, ident, exported));
if !self.eat(Punct::Comma)? {
break;
}
}
self.expect(Punct::RBrace)?;
if self.at_contextual("from") {
self.bump()?;
let request = self.module_specifier(info, requests)?;
self.semicolon()?;
for (local, _, exported) in names {
let import = ImportName::Name(local.name);
info.exports.push(ExportEntry::Indirect { export_name: exported.name, request, import, span: exported.span });
}
return Ok(None);
}
self.semicolon()?;
for (local, ident, exported) in names {
// Without `from`, each name refers to a binding of the module (section 15.2.3.1).
if !ident || crate::token::strict_reserved(&local.name) {
return Err(self.error_at_offset(local.span.start, format!("'{}' cannot be exported as a binding", local.name)));
}
clause.push(ClauseExport { export_name: exported.name, local: local.name, span: local.span });
}
return Ok(None);
}
if self.at_keyword(Keyword::Default) {
self.bump()?;
return self.export_default(info, span).map(Some);
}
let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some();
if !exportable {
return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok))));
}
let stmt = self.parse_statement_item()?;
let names: Vec<Name> = match self.ast.stmt(stmt) {
Some(Stmt::Var(decls) | Stmt::Lexical(_, decls)) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).collect(),
Some(Stmt::FunctionDecl(fid)) => self.ast.function(*fid).and_then(|f| f.name.clone()).into_iter().collect(),
_ => return Err(self.error_at_offset(span.start, "expected a declaration after 'export'")),
};
for name in names {
info.exports.push(ExportEntry::Local { export_name: name.name.clone(), local: name.name, span: name.span });
}
Ok(Some(stmt))
}
/// `export default …` after `default`: a function declaration (named or not) or an expression.
fn export_default(&mut self, info: &mut ModuleInfo, span: Span) -> Result<StmtId> {
if self.at_keyword(Keyword::Class) {
return Err(self.error_at_token(&self.tok, "classes are not supported"));
}
if self.at_keyword(Keyword::Function) {
self.enter()?;
let result = self.default_function();
self.leave();
let (stmt, fid, local) = result?;
self.declare_function(fid)?;
info.exports.push(ExportEntry::Local { export_name: "default".into(), local, span });
return Ok(stmt);
}
let start = self.tok.span;
let value = self.parse_assignment(false)?;
self.semicolon()?;
let target = Binding::Name(Name { name: DEFAULT_BINDING.into(), span: start });
let stmt = self.ast.push_stmt(Stmt::Lexical(LexKind::Const, vec![VarDecl { target, init: Some(value) }]), self.span_from(start));
info.exports.push(ExportEntry::Local { export_name: "default".into(), local: DEFAULT_BINDING.into(), span });
Ok(stmt)
}
/// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of
/// `name`, or of [`DEFAULT_BINDING`] for a function without one.
fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> {
let keyword = self.expect_keyword(Keyword::Function)?;
let start = keyword.span;
let generator = self.es2015 && self.eat(Punct::Star)?;
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) {
self.function_name()?
} else {
(Name { name: DEFAULT_BINDING.into(), span: start }, keyword)
};
let local = name.0.name.clone();
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start));
Ok((stmt, fid, local))
}
/// The early errors of the exports as a whole (section 15.2.1.1): no name exported twice, and
/// each name an `export { … }` list takes from the module itself declared or imported there. An
/// exported named import becomes a re-export of its imported binding (section 15.2.1.16.1).
/// A namespace import keeps its local binding.
fn finish_exports(&self, info: &mut ModuleInfo, clause: Vec<ClauseExport>) -> Result<()> {
#[cfg(test)]
EXPORT_SEARCH_STEPS.with(|steps| steps.set(0));
let mut imports = HashMap::with_capacity(info.imports.len());
for import in &info.imports {
imports.entry(ImportLocal(&import.local.name)).or_insert(import);
}
let top = self.scopes.first();
for c in clause {
let declared = top.is_some_and(|s| s.lexical.contains_key(&c.local) || s.vars.contains(&c.local));
if !declared {
return Err(self.error_at_offset(c.span.start, format!("'{}' is exported but not declared in the module", c.local)));
}
let imported = imports.get(&ImportLocal(&c.local));
let entry = match imported {
Some(i) if matches!(&i.import, ImportName::Name(_)) => {
ExportEntry::Indirect { export_name: c.export_name, request: i.request, import: i.import.clone(), span: c.span }
}
_ => ExportEntry::Local { export_name: c.export_name, local: c.local, span: c.span },
};
info.exports.push(entry);
}
let mut seen = HashSet::new();
for e in &info.exports {
let (name, span) = match e {
ExportEntry::Local { export_name, span, .. } | ExportEntry::Indirect { export_name, span, .. } => (export_name, span),
ExportEntry::Star { .. } => continue,
};
if !seen.insert(name.as_str()) {
return Err(self.error_at_offset(span.start, format!("'{name}' is exported more than once")));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{EXPORT_SEARCH_STEPS, REQUEST_SEARCH_STEPS};
use crate::{Options, parse_module};
fn run_namespace_modules(main: &str, files: &[(&str, &str)]) -> (Result<crate::JsValue, crate::RunError>, crate::Realm) {
let mut realm = crate::Realm::with_options(Options { es2015: true, ..Options::default() }, crate::Limits::default());
realm.run("var out = [];").unwrap();
let mut load = |_: &str, specifier: &str| {
files.iter().find(|(name, _)| *name == specifier).map_or_else(
|| Err(crate::LoadError::Other(format!("missing module {specifier}"))),
|(_, source)| Ok(crate::LoadedModule { key: specifier.into(), source: Some((*source).into()) }),
)
};
let result = realm.run_module("main.mjs", main, crate::ModuleLimits::default(), &mut load);
(result, realm)
}
#[test]
fn namespace_reexport_bindings_keep_their_origin() {
let files = [
("./a.mjs", "import * as ns from './shared.mjs'; export {ns};"),
("./b.mjs", "import * as ns from './shared.mjs'; export {ns};"),
("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"),
("./shared.mjs", "export var value = 7;"),
];
let (result, _) = run_namespace_modules("import {ns} from './barrel.mjs'; out.push(ns.value);", &files);
assert!(result.as_ref().is_err_and(|error| error.message.contains("ambiguous")), "{result:?}");
let files = [
("./a.mjs", "import {value} from './shared.mjs'; export {value};"),
("./b.mjs", "import {value} from './shared.mjs'; export {value};"),
("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"),
("./shared.mjs", "export var value = 7; export function change() { value = 9; }"),
];
let (result, mut realm) =
run_namespace_modules("import {value} from './barrel.mjs'; import {change} from './shared.mjs'; change(); out.push(value);", &files);
assert!(result.is_ok(), "{result:?}");
assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("9".into())));
}
#[test]
fn namespace_reexports_link_through_cycles() {
let files = [("./a.mjs", "import * as ns from './b.mjs'; export {ns};"), ("./b.mjs", "import * as ns from './a.mjs'; export {ns};")];
let (result, mut realm) = run_namespace_modules("import * as a from './a.mjs'; out.push(a.ns.ns === a);", &files);
assert!(result.is_ok(), "{result:?}");
assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into())));
}
#[test]
fn module_specifiers_reject_legacy_octal_escapes() {
for source in
[r"import './\141.mjs';", r"import value from './\141.mjs';", r"export * from './\141.mjs';", r"export { value } from './\141.mjs';"]
{
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
}
for source in [r"import './\u0061.mjs';", r"export * from './\x61.mjs';", r"import './\uD800.mjs';"] {
assert!(parse_module(source, &Options::default()).is_ok(), "{source}");
}
}
#[test]
fn module_request_search_work_is_bounded_by_request_count() {
let count = 1_000;
let mut source = String::new();
for index in 0..count {
source.push_str(&format!("import './{index}.mjs';"));
}
source.push_str(r"import './\u0030.mjs'; import './\uD800.mjs'; import './\uFFFD.mjs'; import './\uDC00.mjs'; import './\uD800.mjs';");
let (_, info) = match parse_module(&source, &Options::default()) {
Ok(parsed) => parsed,
Err(error) => panic!("{error:?}"),
};
assert_eq!(info.requests.len(), count + 3);
for (index, request) in info.requests.iter().take(count).enumerate() {
assert_eq!(request.specifier, format!("./{index}.mjs"));
}
assert_eq!(info.requests[count].units[2], 0xD800);
assert_eq!(info.requests[count + 1].units[2], 0xFFFD);
assert_eq!(info.requests[count + 2].units[2], 0xDC00);
let steps = REQUEST_SEARCH_STEPS.with(std::cell::Cell::get);
assert!(steps > 0, "the repeated requests compare their exact UTF-16 keys");
assert!(steps <= 2 * (count + 5), "{steps} request-search steps for {} requests", count + 5);
}
#[test]
fn imported_export_resolution_work_is_bounded_by_binding_count() {
let count = 1_000;
let bindings = (0..count).map(|index| format!("value as local{index}")).collect::<Vec<_>>().join(",");
let exports = (0..count).map(|index| format!("local{index} as exported{index}")).collect::<Vec<_>>().join(",");
let source = format!(
"import {{{bindings}}} from './values.mjs'; import * as ns from './namespace.mjs'; export {{{exports},ns as namespace,local0 as again}};"
);
let (_, info) = match parse_module(&source, &Options::default()) {
Ok(parsed) => parsed,
Err(error) => panic!("{error:?}"),
};
assert_eq!(info.imports.len(), count + 1);
assert_eq!(info.exports.len(), count + 2);
for (index, export) in info.exports.iter().take(count).enumerate() {
assert!(matches!(export, crate::ExportEntry::Indirect { export_name, request: 0, import: crate::ast::ImportName::Name(name), .. }
if export_name == &format!("exported{index}") && name == "value"));
}
assert!(matches!(&info.exports[count], crate::ExportEntry::Local { export_name, local, .. } if export_name == "namespace" && local == "ns"));
assert!(
matches!(&info.exports[count + 1], crate::ExportEntry::Indirect { request: 0, import: crate::ast::ImportName::Name(name), .. } if name == "value")
);
let steps = EXPORT_SEARCH_STEPS.with(std::cell::Cell::get);
assert!(steps > 0);
assert!(steps <= 3 * (count + 2), "{steps} import-local comparisons for {} exports", count + 2);
for source in [
"import {value as x} from './values.mjs'; export {x,x};",
"import {value as x} from './values.mjs'; import * as x from './namespace.mjs';",
] {
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
}
}
}
+89 -24
View File
@@ -7,9 +7,14 @@ use std::sync::atomic::{AtomicBool, Ordering};
use crate::bytecode::CodeKind;
use crate::heap::{Func, HIDDEN, Object, Prop, key};
use crate::interp::{Abrupt, CompileError, Interp};
use crate::module::{LinkFail, ModuleLimits, ModuleLoader};
use crate::value::Value;
use crate::{Options, SyntaxError};
fn internal_error(message: &str) -> RunError {
RunError { kind: RunErrorKind::Internal, message: message.to_string(), line: 0, column: 0, authored: false }
}
/// The limits a run is held to. Reaching one ends the run with [`RunErrorKind::Limit`]; scripts
/// cannot catch it, and their `finally` blocks do not run.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -287,6 +292,78 @@ impl Realm {
/// Compiles `source` and readies the realm for a run.
fn compile(&mut self, source: &str) -> Result<std::rc::Rc<crate::bytecode::Code>, RunError> {
self.end();
self.reset_run()?;
let interp = &mut self.interp;
let strict = interp.options.strict;
interp.evaluated = next_tag(interp.evaluated);
self.script_tag = interp.evaluated;
interp.source_tag = self.script_tag;
let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global));
interp.source_tag = UNKNOWN_SOURCE;
match code {
Ok(code) => Ok(code),
Err(CompileError::Syntax(e)) => {
interp.error_tag = self.script_tag;
Err(e.into())
}
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }),
}
}
/// Begins a run of the module `key` with `source` (ECMA-262 2015 section 15.2), which
/// [`Realm::advance`] carries on as it does a script [`Realm::start`] began. `load` gives each
/// module a module imports ([`ModuleLoader`]). Every module is loaded, parsed and linked before
/// any runs, so a syntax error, an import of a missing or ambiguous export, a module `load`
/// cannot give or a module past `limits` ends the run here, with no code run. The first module
/// has [`Realm::script_tag`] as its source's tag, and each module loaded after it the next tag,
/// in the order `load` first gave their sources, as the sources an evaluator gives during a run
/// take theirs. A realm without [`Options::es2015`] runs no module: that is a syntax error.
/// A paused or waiting run ends before loading; its globals remain available.
pub fn start_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<(), RunError> {
self.end();
self.reset_run()?;
if !self.interp.options.es2015 {
let message = "modules need ECMAScript 2015; this script runs ECMAScript 5".to_string();
return Err(RunError { kind: RunErrorKind::Syntax, message, line: 0, column: 0, authored: false });
}
let interp = &mut self.interp;
interp.evaluated = next_tag(interp.evaluated);
self.script_tag = interp.evaluated;
let marks = (interp.temp_envs_mark(), interp.temp_roots_mark(), interp.temp_codes_mark());
let linked = crate::module::link(interp, key, source, self.script_tag, limits, load);
let pushed = match linked {
Ok(modules) => interp.push_module_frames(&modules).map_err(LinkFail::Run),
Err(fail) => Err(fail),
};
let interp = &mut self.interp;
interp.drop_temp_envs(marks.0);
interp.drop_temp_roots(marks.1);
interp.drop_temp_codes(marks.2);
match pushed {
Ok(()) => Ok(()),
Err(LinkFail::Syntax { tag, error }) => {
self.interp.error_tag = tag;
Err(error.into())
}
Err(LinkFail::At { tag, line, column, abrupt }) => {
let e = self.outcome(Err(abrupt)).err();
self.interp.error_tag = tag;
Err(e.map_or_else(|| internal_error("a module failed without an error"), |e| RunError { line, column, ..e }))
}
Err(LinkFail::Run(abrupt)) => self.outcome(Err(abrupt)).map(drop),
}
}
/// Runs the module `key` with `source` to its end ([`Realm::start_module`]), drains its queued
/// Promise jobs, and returns `undefined`.
pub fn run_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<JsValue, RunError> {
self.start_module(key, source, limits, load)?;
let result = self.interp.execute().and_then(|value| self.interp.drain_jobs(value));
self.outcome(result)
}
/// Readies the realm for a run: its state from the last run cleared and its fuel filled.
fn reset_run(&mut self) -> Result<(), RunError> {
self.script_tag = UNKNOWN_SOURCE;
self.rejections = (Vec::new(), 0);
let interp = &mut self.interp;
@@ -328,21 +405,7 @@ impl Realm {
}),
};
}
let interp = &mut self.interp;
let strict = interp.options.strict;
interp.evaluated = next_tag(interp.evaluated);
self.script_tag = interp.evaluated;
interp.source_tag = self.script_tag;
let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global));
interp.source_tag = UNKNOWN_SOURCE;
match code {
Ok(code) => Ok(code),
Err(CompileError::Syntax(e)) => {
interp.error_tag = self.script_tag;
Err(e.into())
}
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }),
}
Ok(())
}
/// The end of a run: its completion value or error, with the interpreter's stacks emptied.
@@ -358,7 +421,7 @@ impl Realm {
// A generator whose body was running when the run ended cannot go on.
let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect();
running.into_iter().for_each(|g| interp.end_generator(Some(g)));
interp.frames.clear();
interp.clear_frames();
interp.temp_roots.clear();
interp.join_stack.clear();
interp.waiting = false;
@@ -549,16 +612,17 @@ impl Realm {
self.interp.script_name = name;
}
/// Which source the last error's `line` and `column` are in: 0 for the script last given to
/// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a
/// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which
/// includes code from an earlier script and from the sources given during its run.
/// Which source the last error's `line` and `column` are in: 0 for the most recent script or
/// module entry source. Later sources are numbered from 1 as tags are assigned: modules in
/// load order, then sources a [`crate::HostItem::Evaluator`] gives. Module execution order
/// can differ from load order. A script run without modules numbers only evaluator sources.
/// [`UNKNOWN_SOURCE`] includes code from earlier runs and their module or evaluator sources.
pub fn error_source(&self) -> u32 {
self.source_of(self.interp.error_tag)
}
/// The source tag of the code the last error's `line` and `column` are in, which stays the same
/// from run to run: each script given to [`Realm::run`] or [`Realm::start`] and each source a
/// from run to run: each script or module entry, each dependency loaded, and each source a
/// [`crate::HostItem::Evaluator`] gives gets the next tag, so a function an earlier script
/// defined has its script's tag. [`UNKNOWN_SOURCE`] for code that `eval` or `Function`
/// compiled, an error with no place, and sources given once the tags are used up.
@@ -566,9 +630,10 @@ impl Realm {
self.interp.error_tag
}
/// The source tag ([`Realm::error_tag`]) of the script the last [`Realm::run`] or
/// [`Realm::start`] compiled; the `n`th source an evaluator gave during that run has this tag
/// plus `n`. [`UNKNOWN_SOURCE`] when that call compiled nothing.
/// The source tag ([`Realm::error_tag`]) of the most recent script or module entry source.
/// Dependency modules receive subsequent tags in load order, followed by evaluator sources
/// as they are given. A script run without modules assigns subsequent tags only to evaluator
/// sources. [`UNKNOWN_SOURCE`] when no entry tag has been assigned or the tags are used up.
pub fn script_tag(&self) -> u32 {
self.script_tag
}
+21 -2
View File
@@ -408,8 +408,27 @@ impl Interp {
Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"),
None => {}
}
let proto = self.object(id)?.proto;
match proto.map(|p| self.find_sym(p, &k)).transpose()?.flatten() {
let mut cur = self.object(id)?.proto;
let mut inherited = None;
let mut steps = 0usize;
while let Some(object) = cur {
if matches!(self.object(object)?.class, crate::heap::Class::ModuleNamespace(_)) {
return self.reject_sym(throw, &k, "a module namespace object is read-only");
}
if let Some(property) = self.get_own_sym(object, &k)? {
inherited = Some(property);
break;
}
cur = self.object(object)?.proto;
if cur.is_some() {
self.use_fuel()?;
}
steps += 1;
if steps > 1_000_000 {
return Err(crate::interp::Abrupt::Internal("prototype chain too long".into()));
}
}
match inherited {
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"),
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject_sym(throw, &k, "it is read-only"),
+199 -2
View File
@@ -31,7 +31,10 @@
//! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`,
//! arrow functions, templates, default and rest parameters, classes, `super` and `new.target`,
//! and from ECMAScript 2020 optional chains and `??`) without and with that option, and
//! prints both counts; its failures with the option go to `es2015-failures.txt`.
//! prints both counts; its failures with the option go to `es2015-failures.txt`. A sixth test runs
//! the module tests under `test/language/module-code`, `import` and `export` as modules, reading
//! the fixture files they import from the suite, and as scripts for comparison; its failures as
//! modules go to `module-failures.txt`.
//!
//! A sixth test runs the tests under the folders [`ES2015_COLLECTION_BUILT_INS`] names (`Map`, `Set`,
//! `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, `TypedArray` and `TypedArrayConstructors`) in
@@ -73,7 +76,11 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize};
use vectorcraft_js::{
JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize,
tokenize_module,
};
/// A test file's metadata, from its `/*--- … ---*/` block.
#[derive(Default)]
struct Meta {
@@ -453,6 +460,12 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options:
Err(_) => return true,
}
}
uses_missing_builtin(&lists, missing)
}
/// The tokens `lists` (of a test and the harness files it includes) use a missing built-in, as
/// [`needs_missing_builtin`] counts them.
fn uses_missing_builtin(lists: &[Vec<Token>], missing: &HashSet<&str>) -> bool {
let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens));
lists.iter().flatten().any(|t| match &t.kind {
TokenKind::Ident(name) => missing.contains(name.as_str()),
@@ -967,6 +980,190 @@ fn run_es2015(dir: &Path) {
assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display());
}
/// The folders under `test/language/` whose module tests [`modules_run`] reads.
const MODULE_FOLDERS: &[&str] = &["module-code", "import", "export"];
/// The feature tags a module test may carry: those of [`ES2015_FEATURES`] and `export * as ns from`.
const MODULE_FEATURES: &[&str] =
&["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters", "export-star-as-namespace-from-module"];
#[test]
fn modules_run() {
let Some(dir) = suite_dir() else {
println!("test262 modules: SKIPPED (no suite; run cargo xtask test262)");
return;
};
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_modules(&dir)).unwrap();
handle.join().unwrap();
}
/// The `/`-separated path, from the suite's folder, of the module `specifier` names for the module
/// at `referrer` (a path from the suite's folder too): only a `./` or `../` path that stays inside
/// `test/`.
fn module_path(referrer: &str, specifier: &str) -> Result<String, LoadError> {
if !(specifier.starts_with("./") || specifier.starts_with("../")) {
return Err(LoadError::Syntax(format!("the runner reads only relative specifiers: '{specifier}'")));
}
let mut names: Vec<&str> = referrer.split('/').collect();
names.pop();
for name in specifier.split('/') {
match name {
"" | "." => {}
".." if names.len() > 1 => {
names.pop();
}
".." => return Err(LoadError::Other(format!("'{specifier}' leads out of the suite's tests"))),
name => names.push(name),
}
}
Ok(names.join("/"))
}
/// Runs a module test's `source` (at `rel`, a path from the suite's folder) in a new realm with
/// `options`, after `prelude` (the harness) as a script; the modules it imports are read from the
/// suite. `Err` describes a failure. `negative` is the phase (`resolution` or `runtime`) and the
/// error the test expects. A `resolution` test's module must parse, and the run must end with the
/// error while the modules load and link, before any runs; an imported module that does not parse
/// counts for a `SyntaxError`. A `runtime` test's modules must load and link, and the error must be thrown
/// while they run.
fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative: Option<(&str, &str)>, options: &Options) -> Result<(), String> {
let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
realm.run(prelude).map_err(|e| format!("the harness failed: {}", e.message))?;
let mut given = HashSet::new();
let mut load = |referrer: &str, specifier: &str| {
let key = module_path(referrer, specifier)?;
let path = inside(dir, &key).map_err(LoadError::Other)?;
let source = if given.insert(key.clone()) { Some(read_source(&path).map_err(LoadError::Other)?) } else { None };
Ok(LoadedModule { key, source })
};
let resolution = negative.is_some_and(|(phase, _)| phase == "resolution");
if resolution && let Err(e) = vectorcraft_js::parse_module(source, options) {
return Err(format!("did not parse; a resolution error was expected: {} (line {})", e.message, e.line));
}
let started = realm.start_module(rel, source, ModuleLimits::default(), &mut load);
let result = match started {
Ok(()) if resolution => return Err("linked; an error while linking was expected".to_string()),
Err(e) if !resolution && negative.is_some() => {
return Err(format!("did not start; an error while running was expected: {:?}: {} (line {})", e.kind, e.message, e.line));
}
Err(e) => Err(e),
Ok(()) => loop {
match realm.advance(u64::MAX) {
Ok(Progress::Paused) => {}
Ok(Progress::Done(v)) => break Ok(v),
Err(e) => break Err(e),
}
},
};
match (result, negative.map(|(_, t)| t)) {
(Ok(_), None) => Ok(()),
(Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")),
(Err(e), Some("SyntaxError")) if resolution && e.kind == RunErrorKind::Syntax => Ok(()),
(Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => {
realm.bind_last_thrown("__thrown");
match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) {
Ok(JsValue::Bool(true)) => Ok(()),
_ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)),
}
}
(Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)),
}
}
/// Runs the module tests (`flags: [module]`) under [`MODULE_FOLDERS`] whose feature tags are all in
/// [`MODULE_FEATURES`], leaving out asynchronous tests and those that use a missing built-in: each
/// once as a strict script with [`Options::es2015`], as they could run before modules, and once as
/// a module, and prints both counts. A `negative: phase: parse` test must not parse as a module,
/// and a `phase: resolution` one must end before it runs with the error its `type:` names.
/// Failures as a module go to `module-failures.txt`.
fn run_modules(dir: &Path) {
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
let missing = missing_builtins(&[TEXT_BUILTINS]);
let options = Options { es2015: true, ..Options::default() };
let (mut selected, mut skipped) = (0usize, 0usize);
let (mut before, mut after) = ((0usize, 0usize), (0usize, 0usize));
let mut failures = String::new();
let mut panics = 0usize;
for folder in MODULE_FOLDERS {
let root = or_fail(inside(dir, &format!("test/language/{folder}")));
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
for path in or_fail(test_files(&root)) {
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
let source = or_fail(read_source(&path));
let meta = meta(&source);
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
if !has("module") || !meta.features.iter().all(|f| MODULE_FEATURES.contains(&f.as_str())) {
continue;
}
let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
let phase = meta.negative_phase.as_deref();
// A module that must not parse has no tokens to look at, and one that does not parse
// runs, to fail.
let missing_builtin = phase != Some("parse")
&& match (tokenize_module(&source, &options), tokenize(&includes, &options)) {
(Ok(test), Ok(harness)) => uses_missing_builtin(&[test, harness], &missing),
(Err(_), Ok(_)) => false,
(_, Err(_)) => true,
};
if has("async") || missing_builtin {
skipped += 1;
continue;
}
selected += 1;
let negative_type = meta.negative_type.clone().filter(|_| matches!(phase, Some("runtime" | "resolution")));
let negative = phase.zip(negative_type.as_deref());
let as_script = if matches!(phase, Some("parse" | "resolution")) {
parse(&source, &Options { strict: true, ..options.clone() }).is_err()
} else {
run_one(&format!("\"use strict\";\n{prelude}{includes}{source}"), negative_type.as_deref(), &options).is_ok()
};
if as_script {
before.0 += 1;
} else {
before.1 += 1;
}
let outcome = if phase == Some("parse") {
match vectorcraft_js::parse_module(&source, &options) {
Err(_) => Ok(()),
Ok(_) => Err("parsed; a SyntaxError was expected".to_string()),
}
} else {
let prelude = format!("{prelude}{includes}");
match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative, &options)) {
Ok(r) => r,
Err(_) => {
panics += 1;
Err("PANIC".to_string())
}
}
};
match outcome {
Ok(()) => after.0 += 1,
Err(why) => {
after.1 += 1;
failures.push_str(&format!("{rel}: {why}\n"));
}
}
}
}
assert!(selected > 0, "no module tests under {}", dir.display());
let report = dir.join("module-failures.txt");
if let Err(e) = std::fs::write(&report, &failures) {
println!("could not write {}: {e}", report.display());
}
println!(
"test262 modules: {selected} tests. As scripts: {} passed, {} failed. As modules: {} passed, {} failed. Skipped {skipped} \
asynchronous or missing-built-in tests. Failures: {}",
before.0,
before.1,
after.0,
after.1,
report.display()
);
assert_eq!(panics, 0, "the interpreter panicked; see {}", report.display());
}
#[test]
fn annex_b_runs() {
let Some(dir) = suite_dir() else {
+3 -3
View File
@@ -2028,7 +2028,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.installPlugin",
"Install Plug-in…",
"",
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above) | {pending: true} on the web while a Web Worker checks module bytes no worker has checked yet, after which the install goes on as above in the app",
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, showing its id and file SHA-256, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above) | {pending: true} on the web while a Web Worker checks module bytes no worker has checked yet, after which the install goes on as above in the app",
),
(
"ui.failedPlugins",
@@ -2070,13 +2070,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.runScript",
"Other Script…",
"Cmd+F12",
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
"{path? | source?, name?} run a .js, .mjs or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
),
(
"ui.runInstalledScript",
"Run Script",
"",
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js, .mjs or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
),
(
"ui.checkScript",
+1 -1
View File
@@ -21,7 +21,7 @@ thread_local! {
/// The contour passes made over an arrangement on this thread, each of which walks all of it.
pub(crate) static CONTOUR_PASSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The sweeps [`normalize_bez`] made on this thread.
static NORMALIZE_SWEEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static NORMALIZE_SWEEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The input curves [`exact_merge`] tested on this thread.
static EXACT_MERGE_CURVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
+2
View File
@@ -15,6 +15,7 @@ mod offset;
mod pathfinder;
mod planar;
mod sweep_axis;
mod thickness;
mod trap;
pub use boolean::{
@@ -35,6 +36,7 @@ pub use planar::{
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out,
encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
};
pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within};
pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band};
/// Errors from fallible operations.
+573
View File
@@ -0,0 +1,573 @@
//! The thickness of a filled shape: whether a circle of a given width fits anywhere inside its
//! fill (Clean Up's and Select › Object's Hairline Slivers).
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as _};
use vectorcraft_geom::{FillRule, PathData};
use crate::boolean::{eps_for, fill_bezpath, normalize_bez};
/// Most line pieces the outline of one shape is measured with.
pub const MAX_THICKNESS_PIECES: usize = 100_000;
/// Most cells one search for a wide enough spot looks at.
const MAX_CELLS: usize = 500_000;
/// Most distances from a point to a piece of outline one search measures.
const MAX_WORK: usize = 50_000_000;
/// Most distances from a point to a piece of outline the shapes of one document are measured
/// with, all together ([`ThicknessBudget::document`]).
pub const MAX_DOCUMENT_THICKNESS_WORK: usize = 1_000_000_000;
/// The resolved outline is measured as line pieces within `width / FINE_PARTS` of its curves.
const FINE_PARTS: f64 = 32.0;
/// The first, rough look measures the path as drawn with pieces within `width / ROUGH_PARTS`.
const ROUGH_PARTS: f64 = 8.0;
/// Is the fill of `path` (every subpath closed, as a fill paints it) under `rule` thinner than
/// `width` everywhere: does no circle of diameter `width` fit inside it? A path with no fill is.
/// A shape within a small fraction of `width` of the limit is taken as thick enough.
///
/// `None` when it can't be told: `width` isn't a finite positive number, a coordinate isn't
/// finite, the fill can't be resolved into outlines (or only so coarsely, for a shape that large,
/// that edges closer than `width` would merge), or measuring it would take more than
/// [`MAX_THICKNESS_PIECES`] pieces of outline or a search too long.
pub fn thinner_than(path: &PathData, rule: FillRule, width: f64) -> Option<bool> {
thinner_than_within(path, rule, width, &mut ThicknessBudget::new(MAX_WORK))
}
/// The work left for measuring shapes with [`thinner_than_within`]: a count of distances from a
/// point to a piece of outline.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ThicknessBudget(usize);
impl ThicknessBudget {
pub fn new(work: usize) -> Self {
Self(work)
}
/// The work all the shapes of one document may take: [`MAX_DOCUMENT_THICKNESS_WORK`].
pub fn document() -> Self {
Self(MAX_DOCUMENT_THICKNESS_WORK)
}
/// The work left.
pub fn left(&self) -> usize {
self.0
}
}
/// [`thinner_than`], taking the search's work from `budget`: `None` as well when the search needs
/// more than is left. The quick checks take nothing from it, so they still settle shapes once it
/// runs out.
pub fn thinner_than_within(path: &PathData, rule: FillRule, width: f64, budget: &mut ThicknessBudget) -> Option<bool> {
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
if !(width.is_finite() && width > 0.0)
|| !path.subpaths.iter().flat_map(|sp| &sp.anchors).all(|a| finite(a.p) && finite(a.h_in) && finite(a.h_out))
{
return None;
}
// Every segment is at least one piece of outline, so a path of more anchors is too long to
// measure before its outline is built.
if path.subpaths.iter().map(|sp| sp.anchors.len()).sum::<usize>() > MAX_THICKNESS_PIECES {
return None;
}
let mut bp = fill_bezpath(path);
if bp.elements().is_empty() {
return Some(true);
}
// Measured from the corner of its bounds, so that a shape far from the origin measures as it
// does near it.
let corner = bp.bounding_box().origin();
bp.apply_affine(Affine::translate(-corner.to_vec2()));
let b = bp.bounding_box();
let (r, fine) = (width / 2.0, width / FINE_PARTS);
// A circle inside the fill is inside its bounds. Bounds within the fine measure's error of the
// width go on to that measure, which keeps them.
if b.width().min(b.height()) < width - 2.0 * fine {
return Some(true);
}
// Every point of a fill lies within the widest circle's radius r of its outline, and the points
// within r of a closed outline of length L cover at most 2rL + πr². A fill larger than that holds
// a circle of diameter `width`. Only one subpath filled nonzero that winds at most once around
// any point is measured so: the areas of several subpaths add up to more than their fill where
// they overlap, a path that runs around a spot twice counts its area there twice, and an
// even-odd fill of a path that runs around twice is empty.
if path.subpaths.len() == 1
&& rule == FillRule::NonZero
&& winds_at_most_once(&bp)
&& bp.area().abs() > 2.0 * r * bp.perimeter(1e-3) * 1.01 + std::f64::consts::PI * r * r
{
return Some(false);
}
// The circle lies between any two parallel lines that hold the path's points and handles too,
// which settles a long sliver lying on a slant.
if hull_width(&bp) < width - 2.0 * fine {
return Some(true);
}
// A rough look at the path as drawn: an edge running inside the fill is nearer than the fill's
// outline, so a spot this far from every edge (and from the rough pieces' error) is far enough.
let rough = width / ROUGH_PARTS;
let mut edges = vec![];
if !flatten_into(&bp, rough, &mut edges) {
return None;
}
match search(&edges, b, rule, r + rough, rough, budget) {
Search::Found => return Some(false),
// Resolving the outlines takes time of its own, so it isn't started when what is left of
// the budget cut the rough look short. The rough look can run out where the resolved
// outline is much shorter, so one that ran out of its own share goes on.
Search::TooLong if budget.0 < MAX_WORK => return None,
_ => {}
}
// The fill's own outlines: where subpaths overlap or a path crosses itself, the edges inside the
// fill are no outline of it. A spot within the fine pieces' error of the radius counts as one.
// The sweep snaps points within its tolerance together, which grows with the shape's size: one
// as coarse as the fine pieces could close up a fill that holds the circle, so it isn't measured.
if eps_for([&bp]).ok()? >= fine {
return None;
}
let contours = normalize_bez(&bp, rule).ok()?;
edges.clear();
for c in contours.contours() {
if !flatten_into(&c.path, fine, &mut edges) {
return None;
}
}
if edges.is_empty() {
return Some(true);
}
match search(&edges, b, FillRule::EvenOdd, r - fine, fine, budget) {
Search::Found | Search::Unsure => Some(false),
Search::Absent => Some(true),
Search::TooLong => None,
}
}
/// The points and handles of `bp`, in order.
fn control_points(bp: &BezPath) -> Vec<Point> {
bp.elements()
.iter()
.flat_map(|el| match *el {
PathEl::MoveTo(p) | PathEl::LineTo(p) => vec![p],
PathEl::QuadTo(a, p) => vec![a, p],
PathEl::CurveTo(a, b, p) => vec![a, b, p],
PathEl::ClosePath => vec![],
})
.collect()
}
/// Does `bp`, one closed subpath, wind at most once around every point? Every line through a point
/// that a curve winds around twice crosses it at least four times, so such a curve turns through
/// at least 4π in all. A Bézier curve turns no more than its control polygon, so a control polygon
/// that turns through less than 4π winds at most once.
fn winds_at_most_once(bp: &BezPath) -> bool {
let mut pts = control_points(bp);
pts.dedup();
while pts.len() > 1 && pts.first() == pts.last() {
pts.pop();
}
if pts.len() < 3 {
return true;
}
let turned: f64 = pts
.iter()
.zip(pts.iter().cycle().skip(1))
.zip(pts.iter().cycle().skip(2))
.map(|((&a, &b), &c)| {
let (u, v) = (b - a, c - b);
u.cross(v).atan2(u.dot(v)).abs()
})
.sum();
turned < 4.0 * std::f64::consts::PI * (1.0 - 1e-9)
}
/// Most corners of a convex hull [`hull_width`] measures; a larger hull measures as unbounded.
const MAX_HULL: usize = 512;
/// The least distance between two parallel lines that hold every point and handle of `bp` (the
/// width of their convex hull, which holds the curves too).
fn hull_width(bp: &BezPath) -> f64 {
let mut pts = control_points(bp);
pts.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
pts.dedup();
if pts.len() < 3 {
return 0.0;
}
// Andrew's monotone chain: the lower hull, then the upper.
let turn = |o: Point, a: Point, b: Point| (a - o).cross(b - o);
let mut hull: Vec<Point> = Vec::with_capacity(pts.len() + 1);
for pass in [false, true] {
let floor = hull.len();
let ordered: Box<dyn Iterator<Item = &Point>> = if pass { Box::new(pts.iter().rev()) } else { Box::new(pts.iter()) };
for &p in ordered {
while hull.len() >= floor + 2 && hull.get(hull.len() - 2).zip(hull.last()).is_some_and(|(&o, &a)| turn(o, a, p) <= 0.0) {
hull.pop();
}
hull.push(p);
}
hull.pop();
}
if hull.len() < 3 {
return 0.0;
}
if hull.len() > MAX_HULL {
return f64::INFINITY;
}
// For each side, the farthest corner from its line; the least of those is the width.
let mut least = f64::INFINITY;
for (&a, &b) in hull.iter().zip(hull.iter().cycle().skip(1)) {
let side = b - a;
let len = side.hypot();
if len > 0.0 {
let far = hull.iter().map(|&p| side.cross(p - a).abs() / len).fold(0.0, f64::max);
least = least.min(far);
}
}
least
}
/// Add `bp`'s outline to `edges` as line pieces within `tolerance` of it: false when that takes
/// more than [`MAX_THICKNESS_PIECES`], or when a curve is too long for [`vectorcraft_geom::flatten`]
/// to keep within `tolerance`.
fn flatten_into(bp: &BezPath, tolerance: f64, edges: &mut Vec<(Point, Point)>) -> bool {
let push = |from: Point, to: Point, edges: &mut Vec<(Point, Point)>| {
if from != to {
edges.push((from, to));
}
};
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
let most = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE;
for el in bp.iter() {
if edges.len() > MAX_THICKNESS_PIECES {
return false;
}
match el {
// An outline that doesn't end where it starts is closed with a line, as a fill paints it.
PathEl::MoveTo(p) => {
push(last, start, edges);
(start, last) = (p, p);
}
PathEl::ClosePath => {
push(last, start, edges);
last = start;
}
PathEl::LineTo(p) => {
push(last, p, edges);
last = p;
}
PathEl::QuadTo(a, p) | PathEl::CurveTo(a, _, p) => {
let length = match el {
PathEl::CurveTo(_, b, _) => last.distance(a) + a.distance(b) + b.distance(p),
_ => last.distance(a) + a.distance(p),
};
if length / most > tolerance {
return false;
}
let mut from = last;
vectorcraft_geom::flatten([PathEl::MoveTo(last), el], tolerance, |piece| {
if let PathEl::LineTo(to) = piece {
push(from, to, edges);
from = to;
}
});
last = p;
}
}
}
push(last, start, edges);
edges.len() <= MAX_THICKNESS_PIECES
}
/// The distance from `p` to the nearest of `edges`, negative outside the region they bound under
/// `rule`.
fn signed_distance(edges: &[(Point, Point)], rule: FillRule, p: Point) -> f64 {
let mut winding = 0i32;
let mut nearest = f64::INFINITY;
for &(a, b) in edges {
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) {
winding += if b.y > a.y { 1 } else { -1 };
}
let ab = b - a;
let len2 = ab.hypot2();
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
nearest = nearest.min((p - (a + ab * t)).hypot2());
}
let inside = match rule {
FillRule::NonZero => winding != 0,
FillRule::EvenOdd => winding % 2 != 0,
};
let d = nearest.sqrt();
if inside { d } else { -d }
}
/// A square cell of the search: its center, half its side, the signed distance from its center to
/// the outline, and the most that distance can be anywhere in it.
struct Cell {
c: Point,
h: f64,
d: f64,
most: f64,
}
impl PartialEq for Cell {
fn eq(&self, other: &Self) -> bool {
self.most.total_cmp(&other.most) == Ordering::Equal
}
}
impl Eq for Cell {}
impl PartialOrd for Cell {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Cell {
fn cmp(&self, other: &Self) -> Ordering {
self.most.total_cmp(&other.most)
}
}
/// What [`search`] found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Search {
/// A point at least the distance asked for from the outline.
Found,
/// No such point.
Absent,
/// None found, but cells smaller than the finest size could still hold one.
Unsure,
/// The search needed more cells or distances than it may take.
TooLong,
}
/// Look for a point inside the region `edges` bound under `rule` (within `bounds`) at least `goal`
/// from its outline. The bounds are cut into square cells, and the cell that could hold the farthest
/// point is split first, until a cell's center is `goal` away or no cell could be. The distance
/// changes no faster than the point moves, so a cell holds no point farther than its center's
/// distance plus half its diagonal. Cells smaller than `finest` are not split further. The
/// distances it measures, no more than [`MAX_WORK`], are taken from `budget`.
fn search(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, goal: f64, finest: f64, budget: &mut ThicknessBudget) -> Search {
let mut work = 0usize;
let found = search_up_to(edges, bounds, rule, (goal, finest), budget.0.min(MAX_WORK), &mut work);
budget.0 = budget.0.saturating_sub(work);
found
}
/// [`search`], measuring no more than `limit` distances and counting them in `work`.
fn search_up_to(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, (goal, finest): (f64, f64), limit: usize, work: &mut usize) -> Search {
let side = bounds.width().min(bounds.height());
if side.is_nan() || side <= 0.0 {
return Search::Absent;
}
let (cols, rows) = ((bounds.width() / side).ceil(), (bounds.height() / side).ceil());
if cols * rows > MAX_CELLS as f64 || cols * rows * edges.len() as f64 > limit as f64 {
return Search::TooLong;
}
let cell = |c: Point, h: f64, work: &mut usize| {
*work += edges.len();
let d = signed_distance(edges, rule, c);
Cell { c, h, d, most: d + h * std::f64::consts::SQRT_2 }
};
let mut heap = BinaryHeap::new();
let h = side / 2.0;
for i in 0..cols as usize {
for j in 0..rows as usize {
heap.push(cell(Point::new(bounds.x0 + (i as f64 + 0.5) * side, bounds.y0 + (j as f64 + 0.5) * side), h, work));
}
}
let (mut made, mut unsure) = (heap.len(), false);
while let Some(next) = heap.pop() {
if next.d >= goal {
return Search::Found;
}
if next.most < goal {
break;
}
if next.h < finest / 2.0 {
unsure = true;
continue;
}
if made + 4 > MAX_CELLS || work.saturating_add(4 * edges.len()) > limit {
return Search::TooLong;
}
let h = next.h / 2.0;
for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] {
let part = cell(Point::new(next.c.x + dx, next.c.y + dy), h, work);
// A cell that can't hold a point `goal` away is left out.
if part.most >= goal {
heap.push(part);
}
}
made += 4;
}
if unsure { Search::Unsure } else { Search::Absent }
}
#[cfg(test)]
mod tests {
use vectorcraft_geom::{Anchor, SubPath};
use super::*;
fn polygon(points: &[(f64, f64)]) -> SubPath {
SubPath::new(points.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)
}
fn one(points: &[(f64, f64)]) -> PathData {
PathData::single(polygon(points))
}
fn thin(p: &PathData, rule: FillRule, width: f64) -> bool {
thinner_than(p, rule, width) == Some(true)
}
fn thick(p: &PathData, rule: FillRule, width: f64) -> bool {
thinner_than(p, rule, width) == Some(false)
}
#[test]
fn a_triangle_whose_third_anchor_almost_meets_its_first_is_thinner_than_a_hairline() {
let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]);
assert!(thin(&sliver, FillRule::NonZero, 0.085));
// Long and on a slant at the narrowest width, and far from the origin.
assert!(thin(&one(&[(0.0, 0.0), (600.0, 600.0), (0.0, 0.0001)]), FillRule::NonZero, 0.001));
let (x, y) = (1_000_000.0, 1_000_000.0);
assert!(thin(&one(&[(x, y), (x + 0.01, y + 0.0075), (x + 0.0001, y + 0.0002)]), FillRule::NonZero, 0.001));
}
#[test]
fn a_bent_sliver_is_found_by_measuring_inside_it() {
// Out along two sides of a triangle and back 0.002 pt inside them: its hull and bounds are
// wide, and only the measure inside finds it thin.
let v = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]);
assert!(thin(&v, FillRule::NonZero, 0.085));
}
#[test]
fn a_narrow_strip_wider_than_the_width_is_kept_and_one_narrower_is_not() {
// A diagonal strip 100 pt long.
let strip = |w: f64| {
let (dx, dy) = (0.6 * w, -0.8 * w);
one(&[(0.0, 0.0), (80.0, 60.0), (80.0 + dx, 60.0 + dy), (dx, dy)])
};
assert!(thick(&strip(0.2), FillRule::NonZero, 0.085));
assert!(thick(&strip(0.2), FillRule::NonZero, 0.18));
assert!(thin(&strip(0.05), FillRule::NonZero, 0.085));
assert!(thin(&strip(0.2), FillRule::NonZero, 0.24));
}
#[test]
fn a_triangle_holding_the_circle_off_every_cell_center_is_kept() {
// Its inscribed circle is 2 across, centered at (1, 1).
let t = one(&[(0.0, 0.0), (4.0, 0.0), (0.0, 3.0)]);
assert!(thick(&t, FillRule::NonZero, 1.95));
assert!(thin(&t, FillRule::NonZero, 2.3));
}
#[test]
fn a_tiny_round_dot_is_kept() {
let dot = vectorcraft_geom::shapes::ellipse(kurbo::Rect::new(10.0, 10.0, 10.3, 10.3));
assert!(thick(&dot, FillRule::NonZero, 0.085));
assert!(thick(&dot, FillRule::NonZero, 0.29));
assert!(thin(&dot, FillRule::NonZero, 0.4));
}
#[test]
fn a_thin_ring_is_thin_whichever_way_its_subpaths_run() {
let square = |x0: f64, x1: f64| polygon(&[(x0, x0), (x1, x0), (x1, x1), (x0, x1)]);
let mut hole = square(1.01, 98.99);
hole.reverse();
assert!(thin(&PathData::new(vec![square(1.0, 99.0), hole]), FillRule::NonZero, 0.085));
// Even-odd: an inner square running the same way still cuts a hole.
assert!(thin(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::EvenOdd, 0.085));
// Nonzero: it doesn't, and the edges inside the fill are no outline of it.
assert!(thick(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::NonZero, 0.085));
}
#[test]
fn overlapping_strips_are_measured_by_their_union() {
// Two strips 0.2 pt tall overlapping by half: their fill is 0.3 pt tall, while the edges of
// each that run inside the other are no more than 0.1 pt apart.
let strip = |y: f64| polygon(&[(0.0, y), (100.0, y), (100.0, y + 0.2), (0.0, y + 0.2)]);
let strips = PathData::new(vec![strip(0.0), strip(0.1)]);
assert!(thick(&strips, FillRule::NonZero, 0.15));
assert!(thin(&strips, FillRule::NonZero, 0.35));
}
#[test]
fn an_outline_out_and_back_along_itself_has_no_fill_and_is_thin() {
assert!(thin(&one(&[(0.0, 0.0), (30.0, 40.0), (0.0, 0.0), (30.0, 40.0)]), FillRule::NonZero, 0.085));
assert!(thin(&PathData::default(), FillRule::NonZero, 0.085));
}
/// Shapes thicker than the width by their area, and slivers lying flat along an axis, are settled
/// without resolving their outlines, so a document of thousands of them is measured quickly.
#[test]
fn plain_shapes_and_flat_slivers_are_settled_without_resolving_their_outlines() {
let before = crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get());
for k in 0..2000 {
let x = f64::from(k) * 12.0;
assert!(thick(&one(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0), (x, 10.0)]), FillRule::NonZero, 0.085));
assert!(thin(&one(&[(x, 20.0), (x + 10.0, 20.0), (x + 10.0, 20.01), (x, 20.01)]), FillRule::NonZero, 0.085));
// Long slivers on a slant are settled by the width of their hull.
assert!(thin(&one(&[(x, 40.0), (x + 9.0, 52.0), (x + 0.001, 40.0015)]), FillRule::NonZero, 0.085));
}
assert_eq!(crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get()), before);
}
/// The area measure is used only for an outline that runs around once: one that runs around
/// twice counts its area twice.
#[test]
fn an_outline_that_runs_around_twice_is_not_measured_by_its_area() {
let square = |n: usize| {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
for _ in 0..n {
for p in [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] {
bp.line_to(p);
}
}
bp.close_path();
bp
};
assert!(winds_at_most_once(&square(1)));
assert!(!winds_at_most_once(&square(2)));
// Measured inside instead, a square run around twice is still as thick as one.
let twice = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
assert!(thick(&twice, FillRule::NonZero, 0.085));
}
/// Shapes that need the search share one budget: once it is spent they can't be measured, and
/// the quick checks still settle the rest.
#[test]
fn a_spent_budget_leaves_the_shapes_that_need_a_search_unmeasured() {
let bent = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]);
let square = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
let mut budget = ThicknessBudget::document();
assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut budget), Some(true));
assert!(budget.left() < MAX_DOCUMENT_THICKNESS_WORK);
let mut spent = ThicknessBudget::new(0);
assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut spent), None);
assert_eq!(thinner_than_within(&square, FillRule::NonZero, 0.085, &mut spent), Some(false));
}
/// A shape so long that resolving its outline snaps edges closer than the width together is not
/// measured, while the same height at an ordinary length is.
#[test]
fn a_shape_too_long_to_resolve_at_the_width_cannot_be_measured() {
let rect = |w: f64| one(&[(0.0, 0.0), (w, 0.0), (w, 0.0011), (0.0, 0.0011)]);
assert_eq!(thinner_than(&rect(1e12), FillRule::NonZero, 0.001), None);
assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.001), Some(false));
assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.0012), Some(true));
}
#[test]
fn a_width_or_a_coordinate_that_is_no_finite_number_cannot_be_measured() {
let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]);
for w in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert_eq!(thinner_than(&sliver, FillRule::NonZero, w), None, "{w}");
}
let flat = one(&[(0.0, 0.0), (f64::NAN, 0.0), (40.0, 0.0)]);
assert_eq!(thinner_than(&flat, FillRule::NonZero, 0.085), None);
}
}
+3 -1
View File
@@ -33,7 +33,8 @@
//! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is
//! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A
//! filter or a live effect may also add menu commands of its own ([`Command`]), which the host
//! runs through `vc_run` with the command's id in `_context`. The web build checks modules and
//! runs through `vc_run` with the command's id in `_context`. Its name, command labels and
//! parameter text may come in other languages too ([`translations`]). The web build checks modules and
//! runs filters in a worker of its own ([`worker`]).
//!
//! An object filter may also be written in JavaScript ([`js`]): its manifest gives
@@ -60,6 +61,7 @@ pub mod safe_mode;
#[cfg(any(test, feature = "test-steady"))]
pub mod steady;
pub mod storage;
pub mod translations;
pub mod wat;
pub mod worker;
+10 -2
View File
@@ -6,6 +6,7 @@ use serde_json::{Map, Value, json};
use crate::dialog::ParamUi;
use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, OUTPUT_KINDS_API, PROGRESS_API, Permission, WRITES_API};
use crate::translations::Translations;
use crate::{Error, Result};
/// Longest manifest the host reads.
@@ -725,6 +726,10 @@ pub struct Manifest {
/// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter.
#[serde(default, skip_serializing_if = "Runtime::is_wasm")]
pub runtime: Runtime,
/// Its name, command labels and parameter text in other languages, shown in place of the
/// manifest's own when the UI is in one of them ([`crate::translations`]).
#[serde(default, skip_serializing_if = "Translations::is_empty")]
pub translations: Translations,
}
impl Manifest {
@@ -779,13 +784,15 @@ impl Manifest {
commands: Vec::new(),
command_allowlist: Vec::new(),
runtime: Runtime::Wasm,
translations: Translations::default(),
}
}
/// The manifest command `c` runs with: this one with `c`'s label as its name and `c`'s
/// parameters as its own, so dialogs show them and [`Manifest::resolve_params`] checks them.
/// parameters as its own, so dialogs show them and [`Manifest::resolve_params`] checks them,
/// and with `c`'s text in each language as its translations.
pub fn for_command(&self, c: &Command) -> Manifest {
Manifest { name: c.label.clone(), params: c.params.clone(), commands: Vec::new(), ..self.clone() }
Manifest { name: c.label.clone(), params: c.params.clone(), commands: Vec::new(), translations: self.command_translations(c), ..self.clone() }
}
/// The command with id `id`.
@@ -890,6 +897,7 @@ impl Manifest {
self.validate_params()?;
self.validate_commands()?;
self.validate_allowlist()?;
self.validate_translations()?;
self.validate_runtime()
}
+1 -1
View File
@@ -235,7 +235,7 @@ pub fn names(permissions: &[Permission]) -> Vec<&'static str> {
/// Is `c` a character that changes the direction text is laid out in, or a line or paragraph
/// separator, which a prompt must not let a manifest string use to disguise itself?
fn is_bidi_or_separator(c: char) -> bool {
pub(crate) fn is_bidi_or_separator(c: char) -> bool {
matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{2028}' | '\u{2029}')
}
+589
View File
@@ -0,0 +1,589 @@
//! Text a plug-in gives in other languages: its manifest's `translations` (docs/plugins.md ›
//! Translations).
//!
//! `translations` maps language codes (`de`, `pt-br`, `zh-hant`, compared without regard to case)
//! to the text shown in that language: the plug-in's `name`, its commands' labels, its parameters'
//! labels, help and choice labels, and its group headings. Every entry is optional; text a language
//! leaves out comes from the language without its last part (`pt-br`, then `pt`) and then from the
//! manifest's own text. The text is shown only: command ids, parameter names, the values a choice
//! passes, `plugin.list` and the install approval keep the manifest's own text.
use std::collections::HashSet;
use serde::{Deserialize, Serialize};
use crate::dialog::{MAX_HELP, MAX_LABEL};
use crate::manifest::{Command, Manifest, ParamSpec};
use crate::permissions::{self, MAX_SHOWN_FIELD, MAX_SHOWN_NAME};
use crate::{Error, Result};
/// Most languages a manifest's `translations` gives text in.
pub const MAX_LANGUAGES: usize = 16;
/// Longest language code, in bytes.
pub const MAX_LANGUAGE_CODE: usize = 35;
/// Longest translated plug-in name, command label or choice label, in characters.
pub const MAX_NAME: usize = 64;
/// Named entries in the order the manifest gives them; each name at most once.
#[derive(Clone, Debug, PartialEq)]
pub struct Entries<T>(pub Vec<(String, T)>);
impl<T> Default for Entries<T> {
fn default() -> Self {
Entries(Vec::new())
}
}
impl<T> Entries<T> {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// The entry named `name`.
pub fn get(&self, name: &str) -> Option<&T> {
self.0.iter().find(|(k, _)| k == name).map(|(_, v)| v)
}
}
impl<T: Serialize> Serialize for Entries<T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
let mut m = s.serialize_map(Some(self.0.len()))?;
for (k, v) in &self.0 {
m.serialize_entry(k, v)?;
}
m.end()
}
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Entries<T> {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
struct V<T>(std::marker::PhantomData<T>);
impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for V<T> {
type Value = Entries<T>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("an object")
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> std::result::Result<Self::Value, A::Error> {
let mut seen = HashSet::new();
let mut out = Vec::new();
while let Some(k) = map.next_key::<String>()? {
if !seen.insert(k.clone()) {
let shown = permissions::display_text(&k, MAX_SHOWN_FIELD);
return Err(serde::de::Error::custom(format!("`{shown}` is given twice")));
}
out.push((k, map.next_value()?));
}
Ok(Entries(out))
}
}
d.deserialize_any(V(std::marker::PhantomData))
}
}
/// A parameter's text in one language.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ParamText {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub help: Option<String>,
/// A choice's labels, by the value each option passes.
#[serde(default, skip_serializing_if = "Entries::is_empty")]
pub options: Entries<String>,
}
/// A command's text in one language.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CommandText {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Entries::is_empty")]
pub params: Entries<ParamText>,
}
/// A plug-in's text in one language.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Catalog {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// By parameter name.
#[serde(default, skip_serializing_if = "Entries::is_empty")]
pub params: Entries<ParamText>,
/// Group headings, by the `group` the parameters give.
#[serde(default, skip_serializing_if = "Entries::is_empty")]
pub groups: Entries<String>,
/// By command id.
#[serde(default, skip_serializing_if = "Entries::is_empty")]
pub commands: Entries<CommandText>,
}
/// A manifest's `translations`, by language code.
pub type Translations = Entries<Catalog>;
/// Is `tag` a language code: a language of 2 or 3 letters, then parts of 2 to 8 letters and
/// digits, each after a `-`, at most [`MAX_LANGUAGE_CODE`] bytes in all (`de`, `pt-BR`,
/// `zh-Hant-TW`)?
pub fn valid_language_code(tag: &str) -> bool {
let mut parts = tag.split('-');
tag.len() <= MAX_LANGUAGE_CODE
&& parts.next().is_some_and(|l| (2..=3).contains(&l.len()) && l.bytes().all(|b| b.is_ascii_alphabetic()))
&& parts.all(|p| (2..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric()))
}
/// The codes text for language `lang` is looked up under, most specific first: `lang`, then
/// `lang` without its last part, down to the language alone (`zh-hant-tw`, `zh-hant`, `zh`).
fn lookup_codes(lang: &str) -> impl Iterator<Item = &str> {
std::iter::successors(Some(lang), |l| l.rfind('-').map(|i| &l[..i]))
}
impl Translations {
/// The first text `f` finds for language `lang` ([`lookup_codes`]).
fn find<'a, T>(&'a self, lang: &str, f: impl Fn(&'a Catalog) -> Option<T>) -> Option<T> {
lookup_codes(lang).find_map(|code| self.0.iter().filter(|(k, _)| k.eq_ignore_ascii_case(code)).find_map(|(_, c)| f(c)))
}
/// The plug-in's name these translations give for language `lang` (`None`: they give none).
pub fn name_in(&self, lang: &str) -> Option<&str> {
self.find(lang, |c| c.name.as_deref())
}
}
/// Is `s` text a translation may give: 1 to `max` characters, not all spaces, without control
/// characters (`\n` too, unless `lines`) or characters that change the direction text is laid out
/// in or separate lines?
fn fits(s: &str, max: usize, lines: bool) -> bool {
!s.trim().is_empty()
&& s.chars().count() <= max
&& s.chars().all(|c| (!c.is_control() || (lines && c == '\n')) && !permissions::is_bidi_or_separator(c))
}
/// `translations.<path>` as an error names it, each part escaped as prompts show text.
fn key(path: &[&str]) -> String {
let parts: Vec<String> = path.iter().map(|p| permissions::display_text(p, MAX_SHOWN_FIELD)).collect();
format!("`translations.{}`", parts.join("."))
}
/// Text `s` as a dialog shows it: each line with its control and bidirectional characters escaped
/// and cut at [`MAX_HELP`] characters.
fn shown_text(s: &str) -> String {
let lines: Vec<String> = s.split('\n').map(|l| permissions::display_text(l, MAX_HELP)).collect();
lines.join("\n")
}
/// Checks text `s` at `path` against `max` characters (`lines`: `\n` allowed).
fn check_text(s: &str, max: usize, lines: bool, path: &[&str]) -> Result<()> {
if fits(s, max, lines) {
return Ok(());
}
let at = key(path);
Err(Error::Manifest(format!("{at} must be 1-{max} printable characters, without direction or line-separator characters")))
}
/// The error for the key at `path`, which names a parameter, choice value, group or command the
/// manifest doesn't declare, or translates a field the manifest doesn't give (`options` of a
/// parameter that isn't a choice, `help` of a parameter without one).
fn undeclared(path: &[&str]) -> Error {
let at = key(path);
Error::Manifest(format!("{at} names or translates something the manifest doesn't declare"))
}
/// Checks the text of parameters `texts` against the parameters `params` they name, at `path`.
fn check_params(texts: &Entries<ParamText>, params: &[(String, crate::Param)], path: &[&str]) -> Result<()> {
for (k, t) in &texts.0 {
let here = [path, &[k.as_str()]].concat();
let Some((_, p)) = params.iter().find(|(name, _)| name == k) else {
return Err(undeclared(&here));
};
if let Some(label) = &t.label {
check_text(label, MAX_LABEL, false, &[here.as_slice(), &["label"]].concat())?;
}
if let Some(help) = &t.help {
let at = [here.as_slice(), &["help"]].concat();
if p.ui.help.is_none() {
return Err(undeclared(&at));
}
check_text(help, MAX_HELP, true, &at)?;
}
if t.options.is_empty() {
continue;
}
let ParamSpec::Choice { options, .. } = &p.spec else {
return Err(undeclared(&[here.as_slice(), &["options"]].concat()));
};
for (value, label) in &t.options.0 {
let at = [here.as_slice(), &["options", value.as_str()]].concat();
if !options.contains(value) {
return Err(undeclared(&at));
}
check_text(label, MAX_NAME, false, &at)?;
}
}
Ok(())
}
impl Manifest {
/// `translations` gives at most [`MAX_LANGUAGES`] languages, each by a distinct language code
/// ([`valid_language_code`]; case doesn't tell codes apart), and names only what the manifest
/// declares: its parameters, their choices' values, its groups and its commands. Each text
/// follows the rules of the text it translates, without direction or line-separator
/// characters, and `help` translates a `help` the parameter gives. The error names the key.
pub(crate) fn validate_translations(&self) -> Result<()> {
let langs = &self.translations.0;
if langs.len() > MAX_LANGUAGES {
return Err(Error::Manifest(format!("`translations` gives at most {MAX_LANGUAGES} languages")));
}
let groups: HashSet<&str> =
self.params.iter().chain(self.commands.iter().flat_map(|c| c.params.iter())).filter_map(|(_, p)| p.ui.group.as_deref()).collect();
for (i, (lang, c)) in langs.iter().enumerate() {
let lang = lang.as_str();
if !valid_language_code(lang) || langs.get(..i).is_some_and(|before| before.iter().any(|(b, _)| b.eq_ignore_ascii_case(lang))) {
let at = key(&[lang]);
return Err(Error::Manifest(format!("{at} is not a language code such as `de` or `pt-BR`, or repeats one given before it")));
}
if let Some(name) = &c.name {
check_text(name, MAX_NAME, false, &[lang, "name"])?;
}
check_params(&c.params, &self.params, &[lang, "params"])?;
for (g, heading) in &c.groups.0 {
let g = g.as_str();
if !groups.contains(g) {
return Err(undeclared(&[lang, "groups", g]));
}
check_text(heading, MAX_LABEL, false, &[lang, "groups", g])?;
}
for (id, t) in &c.commands.0 {
let id = id.as_str();
let Some(command) = self.command(id) else {
return Err(undeclared(&[lang, "commands", id]));
};
if let Some(label) = &t.label {
check_text(label, MAX_NAME, false, &[lang, "commands", id, "label"])?;
}
check_params(&t.params, &command.params, &[lang, "commands", id, "params"])?;
}
}
// A dropdown tells its options apart by their labels: in each language, with the labels a
// language leaves out taken from the language without its region, no two may be the same.
for (lang, _) in langs {
self.check_option_labels(lang, &[lang, "params"])?;
}
for c in self.commands.iter().filter(|c| c.params.iter().any(|(_, p)| matches!(p.spec, ParamSpec::Choice { .. }))) {
let own = self.for_command(c);
for (lang, _) in langs {
own.check_option_labels(lang, &[lang, "commands", c.id.as_str(), "params"])?;
}
}
Ok(())
}
/// Checks that no two options of a choice show the same label in language `lang`, naming the
/// choice's `options` under `path`. Labels are compared as dialogs show them, with control and
/// bidirectional characters escaped, so an option value holding U+202E and a translation
/// giving the text `\u{202E}` count as the same label.
fn check_option_labels(&self, lang: &str, path: &[&str]) -> Result<()> {
for (k, p) in &self.params {
let ParamSpec::Choice { options, .. } = &p.spec else { continue };
let shown: Vec<String> = options.iter().map(|o| shown_text(self.option_label_in(k, o, lang))).collect();
if shown.iter().enumerate().any(|(i, s)| shown.get(..i).is_some_and(|before| before.contains(s))) {
let at = key(&[path, &[k.as_str(), "options"]].concat());
return Err(Error::Manifest(format!("{at} gives two options the same label")));
}
}
Ok(())
}
/// The translations command `c`'s manifest ([`Manifest::for_command`]) shows: in each language,
/// `c`'s label as its name, `c`'s parameters' text and the group headings.
pub(crate) fn command_translations(&self, c: &Command) -> Translations {
let langs = self.translations.0.iter().map(|(lang, cat)| {
let own = cat.commands.get(&c.id);
let catalog = Catalog {
name: own.and_then(|t| t.label.clone()),
params: own.map(|t| t.params.clone()).unwrap_or_default(),
groups: cat.groups.clone(),
commands: Entries::default(),
};
(lang.clone(), catalog)
});
Entries(langs.collect())
}
/// The plug-in's name in language `lang` (an app language code such as `de` or `pt-br`): its
/// translation, else the manifest's `name`.
pub fn name_in(&self, lang: &str) -> &str {
self.translations.name_in(lang).unwrap_or(&self.name)
}
/// [`Manifest::name_in`] as menus show it: trimmed, control and bidirectional characters
/// escaped, at most [`MAX_SHOWN_NAME`] characters.
pub fn shown_name(&self, lang: &str) -> String {
permissions::display_text(self.name_in(lang).trim(), MAX_SHOWN_NAME)
}
/// Command `c`'s label in language `lang`, as menus show it ([`Command::shown_label`]).
pub fn shown_command_label(&self, c: &Command, lang: &str) -> String {
let label = self.translations.find(lang, |t| t.commands.get(&c.id).and_then(|t| t.label.as_deref())).unwrap_or(&c.label);
permissions::display_text(label.trim(), MAX_SHOWN_NAME)
}
/// The label command `c`'s menu item shows in language `lang` ([`Command::menu_label`]):
/// [`Manifest::shown_command_label`], and for a command placed in another menu, followed by
/// [`Manifest::shown_name`] in parentheses.
pub fn shown_command_menu_label(&self, c: &Command, lang: &str) -> String {
let label = self.shown_command_label(c, lang);
match c.place {
None => label,
Some(_) => format!("{label} ({})", self.shown_name(lang)),
}
}
/// Parameter `k`'s label in language `lang`: its translation, else its `label` (`None`: it
/// has neither).
pub fn param_label_in(&self, k: &str, lang: &str) -> Option<&str> {
let own = self.param(k).and_then(|p| p.ui.label.as_deref());
self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.label.as_deref())).or(own)
}
/// Parameter `k`'s help in language `lang`: its translation, else its `help`.
pub fn param_help_in(&self, k: &str, lang: &str) -> Option<&str> {
let own = self.param(k).and_then(|p| p.ui.help.as_deref());
self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.help.as_deref())).or(own)
}
/// The label of value `option` of choice `k` in language `lang`: its translation, else the
/// value itself.
pub fn option_label_in<'a>(&'a self, k: &str, option: &'a str, lang: &str) -> &'a str {
self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.options.get(option)).map(String::as_str)).unwrap_or(option)
}
/// The heading of group `group` in language `lang`: its translation, else `group`.
pub fn group_in<'a>(&'a self, group: &'a str, lang: &str) -> &'a str {
self.translations.find(lang, |c| c.groups.get(group).map(String::as_str)).unwrap_or(group)
}
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use super::*;
const TRANSLATED: &str = r#"{"id":"org.example.tidy","name":"Tidy","kind":"filter",
"params":{"mode":{"type":"choice","options":["soft","hard"],"label":"Mode","group":"Shape","help":"How hard."},
"steps":{"type":"int","min":1,"max":9,"group":"Shape"}},
"commands":[{"id":"grow","label":"Grow","params":{"by":{"type":"number","min":0,"max":10,"default":2,"label":"By","group":"Shape"}}},
{"id":"shrink","label":"Shrink"}],
"translations":{
"de":{"name":"Aufräumen","params":{"mode":{"label":"Modus","help":"Wie stark.","options":{"soft":"Weich"}},"steps":{"label":"Schritte"}},
"groups":{"Shape":"Form"},
"commands":{"grow":{"label":"Wachsen","params":{"by":{"label":"Um"}}}}},
"pt":{"name":"Arrumar","commands":{"shrink":{"label":"Encolher"}}},
"pt-BR":{"name":"Organizar"}}}"#;
fn translated() -> Manifest {
Manifest::parse(TRANSLATED.as_bytes()).unwrap()
}
/// A German UI shows the German text; any language without a catalog shows the manifest's own.
#[test]
fn a_language_shows_its_text_and_others_the_manifests_own() {
let m = translated();
assert_eq!(m.name_in("de"), "Aufräumen");
assert_eq!(m.shown_name("de"), "Aufräumen");
assert_eq!(m.name_in("de-at"), "Aufräumen", "a region falls back to its language");
for other in ["en", "fr", "ja", "zh-hant"] {
assert_eq!(m.name_in(other), "Tidy", "{other}");
assert_eq!(m.param_label_in("mode", other), Some("Mode"), "{other}");
assert_eq!(m.param_label_in("steps", other), None, "{other}");
assert_eq!(m.option_label_in("mode", "soft", other), "soft", "{other}");
assert_eq!(m.group_in("Shape", other), "Shape", "{other}");
}
assert_eq!(m.param_label_in("mode", "de"), Some("Modus"));
assert_eq!(m.param_label_in("steps", "de"), Some("Schritte"), "a label for a parameter that gives none");
assert_eq!(m.param_help_in("mode", "de"), Some("Wie stark."));
assert_eq!((m.option_label_in("mode", "soft", "de"), m.option_label_in("mode", "hard", "de")), ("Weich", "hard"));
assert_eq!(m.group_in("Shape", "de"), "Form");
let grow = m.command("grow").unwrap();
assert_eq!((m.shown_command_label(grow, "de"), m.shown_command_label(grow, "en")), ("Wachsen".into(), "Grow".into()));
// A command's dialog shows its own text in that language.
let run = m.for_command(grow);
assert_eq!((run.name_in("de"), run.param_label_in("by", "de"), run.group_in("Shape", "de")), ("Wachsen", Some("Um"), "Form"));
assert_eq!((run.name_in("en"), run.param_label_in("by", "en")), ("Grow", Some("By")));
// The text is shown only: what runs and what plugin.list reads keep the manifest's own.
assert_eq!((m.name.as_str(), grow.label.as_str(), grow.id.as_str()), ("Tidy", "Grow", "grow"));
assert_eq!(Value::Object(m.resolve_params(&json!({"mode": "soft"})).unwrap())["mode"], json!("soft"));
}
/// `pt-br` text comes from `pt-br`, then `pt`, then the manifest, each piece on its own.
#[test]
fn a_region_falls_back_to_its_language_and_then_the_manifest() {
let m = translated();
assert_eq!(m.name_in("pt-br"), "Organizar", "codes match without regard to case");
assert_eq!(m.name_in("pt"), "Arrumar");
assert_eq!(m.name_in("pt-pt"), "Arrumar");
let shrink = m.command("shrink").unwrap();
assert_eq!(m.shown_command_label(shrink, "pt-br"), "Encolher", "from pt");
let grow = m.command("grow").unwrap();
assert_eq!(m.shown_command_label(grow, "pt-br"), "Grow", "from the manifest");
}
/// A command placed in another menu names its plug-in after its label, both in the language
/// shown; one in its plug-in's submenu shows its label alone.
#[test]
fn a_placed_command_names_its_plugin_in_the_language_shown() {
let m = Manifest::parse(
r#"{"id":"org.example.ridge","name":"Ridge","api":2,"kind":"filter",
"commands":[{"id":"low","label":"Low Area","menu":{"path":["Select"]}},{"id":"stay","label":"Stay"}],
"translations":{"de":{"name":"Grat","commands":{"low":{"label":"Tiefe Fläche"},"stay":{"label":"Bleiben"}}}}}"#
.as_bytes(),
)
.unwrap();
let (low, stay) = (m.command("low").unwrap(), m.command("stay").unwrap());
assert_eq!(m.shown_command_menu_label(low, "de"), "Tiefe Fläche (Grat)");
assert_eq!(m.shown_command_menu_label(low, "fr"), "Low Area (Ridge)");
assert_eq!(m.shown_command_menu_label(low, "en"), low.menu_label(&m.name), "the manifest's own text as before");
assert_eq!((m.shown_command_menu_label(stay, "de"), m.shown_command_menu_label(stay, "en")), ("Bleiben".into(), "Stay".into()));
}
#[test]
fn translations_round_trip_and_are_left_out_when_absent() {
let m = translated();
let written = serde_json::to_value(&m).unwrap();
assert_eq!(written["translations"]["pt-BR"], json!({"name": "Organizar"}));
assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m);
let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap();
assert!(serde_json::to_value(&plain).unwrap().get("translations").is_none());
assert_eq!(plain.name_in("de"), "x");
}
/// A bad code, text a source field couldn't hold, text that changes direction, and a key the
/// manifest doesn't declare are refused with an error naming the key.
#[test]
fn bad_translations_are_refused_naming_the_key() {
let with = |translations: &str| {
format!(
r#"{{"id":"a","name":"x","kind":"filter","params":{{"mode":{{"type":"choice","options":["a","b"],"group":"G"}},
"n":{{"type":"number","min":0,"max":1,"default":0}}}},"commands":[{{"id":"c","label":"C"}}],"translations":{translations}}}"#
)
};
let long = "x".repeat(MAX_NAME + 1);
let long_label = format!(r#"{{"de":{{"params":{{"n":{{"label":"{}"}}}}}}}}"#, "x".repeat(MAX_LABEL + 1));
let long_name = format!(r#"{{"de":{{"name":"{long}"}}}}"#);
for (translations, says) in [
(r#"{"german":{"name":"X"}}"#, "`translations.german` is not a language code"),
(r#"{"d":{"name":"X"}}"#, "`translations.d` is not a language code"),
(r#"{"de-":{"name":"X"}}"#, "`translations.de-` is not a language code"),
(r#"{"de_DE":{"name":"X"}}"#, "`translations.de_DE` is not a language code"),
(r#"{"x-klingon":{"name":"X"}}"#, "`translations.x-klingon` is not a language code"),
(r#"{"":{"name":"X"}}"#, "`translations.` is not a language code"),
(r#"{"de":{"name":"X"},"DE":{"name":"Y"}}"#, "`translations.DE` is not a language code such as `de` or `pt-BR`, or repeats one"),
(r#"{"de":{"name":""}}"#, "`translations.de.name` must be 1-64"),
(r#"{"de":{"name":" "}}"#, "`translations.de.name` must be 1-64"),
(long_name.as_str(), "`translations.de.name` must be 1-64"),
(r#"{"de":{"name":"a\u0007b"}}"#, "`translations.de.name`"),
(r#"{"de":{"commands":{"c":{"label":"a\nb"}}}}"#, "`translations.de.commands.c.label` must be"),
(
r#"{"de":{"commands":{"nope":{"label":"N"}}}}"#,
"`translations.de.commands.nope` names or translates something the manifest doesn't declare",
),
(r#"{"de":{"params":{"nope":{"label":"N"}}}}"#, "`translations.de.params.nope` names or translates"),
(long_label.as_str(), "`translations.de.params.n.label` must be 1-64"),
(r#"{"de":{"params":{"n":{"help":"H"}}}}"#, "`translations.de.params.n.help` names or translates"),
(r#"{"de":{"params":{"n":{"options":{"a":"A"}}}}}"#, "`translations.de.params.n.options` names or translates"),
(r#"{"de":{"params":{"mode":{"options":{"c":"C"}}}}}"#, "`translations.de.params.mode.options.c` names or translates"),
(r#"{"de":{"params":{"mode":{"options":{"a":""}}}}}"#, "`translations.de.params.mode.options.a` must be"),
(r#"{"de":{"params":{"mode":{"options":{"a":"b"}}}}}"#, "`translations.de.params.mode.options` gives two options the same label"),
(r#"{"de":{"params":{"mode":{"options":{"a":"X","b":"X"}}}}}"#, "gives two options the same label"),
(
r#"{"pt":{"params":{"mode":{"options":{"a":"Leve"}}}},"pt-BR":{"params":{"mode":{"options":{"b":"Leve"}}}}}"#,
"`translations.pt-BR.params.mode.options` gives two options the same label",
),
(r#"{"de":{"groups":{"H":"Ha"}}}"#, "`translations.de.groups.H` names or translates"),
] {
let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string();
assert!(e.contains(says), "{translations}: {e}");
}
// Characters that change the direction of the text or separate lines, written as JSON
// escapes: right-to-left and left-to-right overrides, isolates, and a line separator.
let esc = |c: u32| format!("\\u{c:04X}");
for (translations, says) in [
(format!(r#"{{"de":{{"name":"Flip{}txt"}}}}"#, esc(0x202E)), "`translations.de.name` must be"),
(format!(r#"{{"de":{{"name":"Flip{}txt"}}}}"#, esc(0x2067)), "`translations.de.name` must be"),
(format!(r#"{{"de":{{"name":"a{}b"}}}}"#, esc(0x2028)), "`translations.de.name` must be"),
(format!(r#"{{"de":{{"commands":{{"c":{{"label":"{}C"}}}}}}}}"#, esc(0x202E)), "`translations.de.commands.c.label` must be"),
(format!(r#"{{"de":{{"params":{{"n":{{"label":"{}N"}}}}}}}}"#, esc(0x202D)), "`translations.de.params.n.label` must be"),
(format!(r#"{{"de":{{"params":{{"mode":{{"options":{{"a":"{}A"}}}}}}}}}}"#, esc(0x202B)), "`translations.de.params.mode.options.a`"),
(format!(r#"{{"de":{{"groups":{{"G":"{}Ge"}}}}}}"#, esc(0x2066)), "`translations.de.groups.G` must be"),
(format!(r#"{{"de{}":{{"name":"X"}}}}"#, esc(0x202E)), "`translations.de\\u{202E}` is not a language code"),
] {
let e = Manifest::parse(with(&translations).as_bytes()).unwrap_err().to_string();
assert!(e.contains(says), "{translations}: {e}");
}
// An option value holding U+202E shows as the text `\u{202E}`, so a translation giving
// that text for another option shows the same label.
let escaped = format!(
r#"{{"id":"a","name":"x","kind":"filter","params":{{"mode":{{"type":"choice","options":["soft","{}"]}}}},
"translations":{{"de":{{"params":{{"mode":{{"options":{{"soft":"\\u{{202E}}"}}}}}}}}}}}}"#,
esc(0x202E)
);
let e = Manifest::parse(escaped.as_bytes()).unwrap_err().to_string();
assert!(e.contains("`translations.de.params.mode.options` gives two options the same label"), "{e}");
// Keys and types serde reads: an unknown key, a repeated one, and a value of the wrong type.
for (translations, says) in [
(r#"{"de":{"title":"X"}}"#, "unknown field `title`"),
(r#"{"de":{"params":{"n":{"unit":"mm"}}}}"#, "unknown field `unit`"),
(r#"{"de":{"name":"X","name":"Y"}}"#, "duplicate field `name`"),
(r#"{"de":{"params":{"n":{"label":"A"},"n":{"label":"B"}}}}"#, "`n` is given twice"),
(r#"{"de":{"name":"X"},"de":{"name":"Y"}}"#, "`de` is given twice"),
(r#"{"de":{"name":7}}"#, "manifest"),
(r#"["de"]"#, "manifest"),
(r#""de""#, "manifest"),
("null", "expected an object"),
(r#"{"de":null}"#, "manifest"),
(r#"{"de":{"params":null}}"#, "expected an object"),
(r#"{"de":{"groups":null}}"#, "expected an object"),
(r#"{"de":{"commands":null}}"#, "expected an object"),
(r#"{"de":{"params":{"mode":{"options":null}}}}"#, "expected an object"),
] {
let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string();
assert!(e.contains(says), "{translations}: {e}");
}
// Right-to-left text without direction characters is text like any other.
let arabic = Manifest::parse(with(r#"{"ar":{"name":"ترتيب","commands":{"c":{"label":"تكبير"}}}}"#).as_bytes()).unwrap();
assert_eq!(arabic.name_in("ar"), "ترتيب");
}
/// At most 16 languages, and the whole manifest, translations included, stays within the
/// manifest's byte limit.
#[test]
fn languages_and_manifest_size_are_capped() {
const CODES: [&str; 17] = ["de", "fr", "es", "it", "pt", "nl", "sv", "da", "fi", "pl", "cs", "hu", "ro", "tr", "ru", "uk", "ja"];
let manifest = |n: usize| {
let langs: Vec<String> = CODES.iter().take(n).map(|c| format!(r#""{c}":{{"name":"X"}}"#)).collect();
format!(r#"{{"id":"a","name":"x","kind":"filter","translations":{{{}}}}}"#, langs.join(","))
};
assert_eq!(Manifest::parse(manifest(MAX_LANGUAGES).as_bytes()).unwrap().translations.0.len(), MAX_LANGUAGES);
let e = Manifest::parse(manifest(MAX_LANGUAGES + 1).as_bytes()).unwrap_err().to_string();
assert!(e.contains("`translations` gives at most 16 languages"), "{e}");
let help = "h".repeat(crate::manifest::MAX_MANIFEST_BYTES);
let big = format!(
r#"{{"id":"a","name":"x","kind":"filter","params":{{"n":{{"type":"bool","help":"H"}}}},"translations":{{"de":{{"params":{{"n":{{"help":"{help}"}}}}}}}}}}"#
);
assert!(Manifest::parse(big.as_bytes()).unwrap_err().to_string().contains("limit"), "the manifest's byte limit applies");
}
#[test]
fn language_codes() {
for good in ["de", "DE", "pt-br", "pt-BR", "zh-Hant", "zh-Hant-TW", "es-419", "fil", "sr-Latn-RS"] {
assert!(valid_language_code(good), "{good}");
}
let long = format!("de-{}", ["abcdefgh"; 4].join("-"));
for bad in ["", "d", "deutsch", "de-", "-de", "de--at", "de_AT", "de-a", "x-test", "i-klingon", "de-abcdefghi", "1d", long.as_str()] {
assert!(!valid_language_code(bad), "{bad}");
}
}
}
+5
View File
@@ -65,6 +65,11 @@ impl Known {
self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure)
}
/// No variable holds a member chain or a File or Folder object. [`Known::unsure`] may be set.
pub fn no_names(&self) -> bool {
self.bound.is_empty() && self.files.is_empty()
}
/// What `other` adds, up to [`crate::Limits::entries`] names of each kind: a name already
/// bound keeps its chain. A name that holds a File or Folder object on both sides holds a Folder
/// object only when both sides say so; otherwise it may hold a File object.
+4 -4
View File
@@ -231,9 +231,9 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits:
/// that includes nothing, so a variable a function uses before the global code assigns it holds
/// what it is assigned. `first` holds the scan made with nothing known, which found `known`, and
/// `pre` what came before it. A scan made with what the scans before it found, and that finds
/// nothing more, is the report scan; no other scan is repeated. When `known` holds no names, the
/// first scan is the report: its [`analyze::Known::unsure`] comes from the script's own
/// declarations, which that scan already read.
/// nothing more, is the report scan; no other scan is repeated. When `known` holds no name, `first`
/// is the report: [`analyze::Known::unsure`] alone comes from `declared`, which the first scan
/// already read.
fn settle<'l>(
first: report::Acc<'l>,
pre: report::Acc<'l>,
@@ -242,7 +242,7 @@ fn settle<'l>(
braced: &[analyze::Braced],
mut known: analyze::Known,
) -> report::Acc<'l> {
if known.bound.is_empty() && known.files.is_empty() {
if known.no_names() {
return first;
}
let entries = pre.limits.entries;
+31 -2
View File
@@ -1935,12 +1935,41 @@ fn the_costliest_inputs_stay_within_five_steps_a_byte() {
format!("\\u0061;function f({}) {{ var {}; }}", names.join(","), names.join(",")),
format!("\\u0061;function f({}) {{}}", vec!["a"; 900].join(",")),
format!("\\u0061;{}", "x=(".repeat(600)),
format!("\\u0061;o[k];{}", "{".repeat(2_000)),
] {
let r = report(&src);
assert!(r.steps <= 5 * src.len() + 16, "{} steps for {} bytes", r.steps, src.len());
}
}
/// The most steps a check of `bytes` without a loader may take. The text is read once for the
/// escapes and once for the names declared, and a scan takes at most three steps a byte. A script
/// whose variables hold nothing the check follows is scanned once: five steps a byte. Any other
/// script is scanned up to five times (the first scan, three more while what its variables hold
/// grows, and the report's): seventeen steps a byte.
fn step_bound(bytes: &[u8]) -> usize {
let limits = Limits::default();
let mut acc = report::Acc::new(&limits);
let (text, _) = decode(bytes);
let (text, braced) = analyze::unescaped(text, &mut acc);
let declared = analyze::declarations(&text, &mut acc);
let known = analyze::scan(&text, &declared, &braced, None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc).known;
let scans = if known.no_names() { 1 } else { 5 };
(2 + 3 * scans) * bytes.len() + 16
}
/// A name in brackets that is not one literal (`0[ \| … ]`) gives no variable a value, so the
/// script is scanned once. The bytes are the ones a run of the property below found.
#[test]
fn a_script_that_binds_no_name_is_scanned_once() {
let bytes: &[u8] = b"\x01\x01 \x010 !0!\x01!\x01#\x01#{#{ 0( #0\x01( \x01( {#{ # \x01#0:((0[\t \\| \x1b!!0:|!| 0) ) )] ! \x1b \x1b \x1b \\u\t\x01";
assert_eq!(bytes.len(), 104);
let r = check("a.jsx", bytes, None, &Limits::default());
assert_eq!(r.kind, Kind::Script);
assert_eq!(step_bound(bytes), 5 * bytes.len() + 16);
assert!(r.steps <= 5 * bytes.len() + 16, "{} steps for {} bytes", r.steps, bytes.len());
}
#[test]
fn lists_stop_at_their_limits_and_echoes_are_cut() {
let mut s = String::new();
@@ -2339,13 +2368,13 @@ proptest! {
#[test]
fn any_bytes_are_checked_in_linear_work(bytes in prop::collection::vec(any::<u8>(), 0..2_000), jsxbin in any::<bool>()) {
let r = check(if jsxbin { "a.jsxbin" } else { "a.jsx" }, &bytes, None, &Limits::default());
prop_assert!(r.steps <= 5 * bytes.len() + 16, "{} steps for {} bytes", r.steps, bytes.len());
prop_assert!(r.steps <= step_bound(&bytes), "{} steps for {} bytes", r.steps, bytes.len());
}
#[test]
fn script_like_text_is_checked_in_linear_work(text in script_text()) {
let r = report(&text);
prop_assert!(r.steps <= 5 * text.len() + 16, "{} steps for {} bytes", r.steps, text.len());
prop_assert!(r.steps <= step_bound(text.as_bytes()), "{} steps for {} bytes", r.steps, text.len());
let limits = Limits::default();
for list in [r.targets.len(), r.directives.len(), r.includes.len(), r.members.len(), r.types.len(), r.menu_strings.len(), r.problems.len()] {
prop_assert!(list <= limits.entries);
+22 -9
View File
@@ -120,9 +120,11 @@ pub(crate) struct CanvasDrops<'a> {
kind: BodyKind,
/// The uid of the document the canvas shows.
document: u64,
/// The revert count of the document the canvas shows: an appearance dragged from contents File › Revert replaced is
/// refused.
/// The revert count of the document the canvas shows: an appearance, graphic style or brush dragged from contents
/// File › Revert replaced is refused.
reverts: u64,
/// `(uid, reverts)` of every open document: a symbol dragged from contents File › Revert replaced is refused.
contents: Vec<(u64, u64)>,
/// `(uid, revision)` of every open document: carried art whose source is not listed unchanged is refused.
sources: Vec<(u64, u64)>,
/// Whether the art being carried is taken though its source's revision moved: its move was given up and the source
@@ -176,12 +178,17 @@ impl Component for CanvasDrops<'_> {
let panel = Target::new(rect, view, covered, |p: &PanelDrag| match p {
PanelDrag::Art { .. } => None,
PanelDrag::Appearance { .. } if p.appearance_for(self.document, self.reverts).is_none() => None,
_ if p.stale_rows(Some((self.document, self.reverts))) => None,
_ => Some(Payload::Panel(p.clone())),
});
let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone())));
let symbol = Target::new(rect, view, covered, |d: &ListDrag<SymbolKey>| Some(Payload::Symbol(d.grabbed.clone())));
let here = (self.document, self.reverts);
let style = Target::new(rect, view, covered, |d: &StyleDrag| ((d.document, d.reverts) == here).then(|| Payload::Style(d.clone())));
// A symbol of any open document's current contents.
let symbol = Target::new(rect, view, covered, |d: &ListDrag<SymbolKey>| {
self.contents.contains(&(d.grabbed.doc, d.grabbed.reverts)).then(|| Payload::Symbol(d.grabbed.clone()))
});
let brush = Target::new(rect, view, covered, |d: &ListDrag<BrushKey>| {
(d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone()))
((d.grabbed.doc, d.grabbed.reverts) == here).then(|| Payload::Brush(d.grabbed.clone()))
});
let library = Target::new(rect, view, covered, |d: &ListDrag<LibraryKey>| Some(Payload::Library(d.grabbed.clone())));
let panel = cx.drop_target::<PanelDrag, _>(&panel);
@@ -222,6 +229,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kind: BodyKi
BodyKind::Pane => pane_view(app, win, rect),
};
let (Some(view), Some((document, reverts))) = (view, app.session.documents().get(win.0).map(|d| (d.uid, d.reverts))) else { return };
let contents = app.session.documents().iter().map(|d| (d.uid, d.reverts)).collect();
let sources = app.session.documents().iter().map(|d| (d.uid, d.revision)).chain(app.canvas.panes.released_from).collect();
// A tab rest leaves the art to the document it showed while that is the current one: any canvas or pane takes it
// then, and nothing once that document was closed or left by other means.
@@ -234,7 +242,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kind: BodyKi
let ctx = ui.ctx().clone();
let covered = |at: Pos2| crate::panel_docking::os_window_at(app, &ctx, at);
let files = (CanvasFiles::new(app, rect, &view), &files_out);
let drops = CanvasDrops { common: Common::new(), view, kind, document, reverts, sources, given_up, covered: &covered, out: &out, files };
let drops =
CanvasDrops { common: Common::new(), view, kind, document, reverts, contents, sources, given_up, covered: &covered, out: &out, files };
drops.id_salt(("canvas-drops", win)).show_at(ui, rect);
if let Some(files) = files_out.take() {
crate::place::canvas_drop(app, ui.ctx(), files);
@@ -330,6 +339,8 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
)
}
}
// A symbol of contents File › Revert replaced places nothing.
Payload::Symbol(key) if !app.session.documents().iter().any(|d| (d.uid, d.reverts) == (key.doc, key.reverts)) => Ok(()),
Payload::Symbol(key) => run(app, "symbol.placeFromDocument", json!({"sourceDocument": key.doc, "name": key.name, "x": at.x, "y": at.y})),
Payload::Library(key) if key.folder => Ok(()),
Payload::Library(key) => match library_panel::parse(&key.panel) {
@@ -346,7 +357,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => {
run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]}))
}
Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() {
Payload::Brush(key) if app.session.active().is_some_and(|st| (st.uid, st.reverts) == (key.doc, key.reverts)) => match hit() {
None if brush_has_art(app, key) && no_art_at(app, at, zoom) => {
run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y}))
}
@@ -357,12 +368,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
}
},
Payload::Brush(_) => Ok(()),
Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => {
Payload::Style(style) if app.session.active().is_some_and(|st| (st.uid, st.reverts) == (style.document, style.reverts)) => {
let Some(hit) = hit() else { return Ok(()) };
let top = top_object(app, &hit)?;
run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy}))
}
Payload::Style(_) => Ok(()),
// Swatch rows of contents File › Revert replaced apply and place nothing.
Payload::Panel(drag @ PanelDrag::Paint { .. }) if drag.stale_rows(app.session.active().map(|st| (st.uid, st.reverts))) => Ok(()),
// A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile art with its tile.
Payload::Panel(PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. })
if hit().is_none() && no_art_at(app, at, zoom) =>
@@ -385,7 +398,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
{
return Err(tl!("A linked color swatch can only be applied in its own document.").into());
}
let Some(mut params) = drag.paint_drop_params(destination) else { return Ok(()) };
let Some(mut params) = drag.paint_drop_params(app.session.active().map(|st| (st.uid, st.reverts))) else { return Ok(()) };
params["ids"] = json!([owner(app, &hit)?]);
params["focus"] = json!(false);
let cmd = crate::panels::proxy_cmd(app, false);
+94 -8
View File
@@ -68,7 +68,7 @@ fn a_foreign_graphic_style_drop_does_not_apply_a_style_with_the_same_name() {
let before = fill(&app);
let history = undo_len(&app);
let at = Point::new(250.0, 70.0);
let payload = Payload::Style(StyleDrag { document, name: "Shared name".into() });
let payload = Payload::Style(StyleDrag { document, reverts: 0, name: "Shared name".into() });
for operation in [DropOperation::Move, DropOperation::Copy] {
drop_at(&mut app, payload.clone(), at, operation).unwrap();
assert_eq!(fill(&app), before);
@@ -135,7 +135,7 @@ fn a_drop_runs_the_effect_of_its_payload() {
assert_eq!(app.session.active().unwrap().selection.objects, [a], "the selection stays");
let st = app.session.active().unwrap();
let name = st.doc.graphic_styles[2].name.clone();
let style = Payload::Style(StyleDrag { document: st.uid, name: name.clone() });
let style = Payload::Style(StyleDrag { document: st.uid, reverts: st.reverts, name: name.clone() });
drop_at(&mut app, style.clone(), on_b, Move).unwrap();
let st = app.session.active().unwrap();
assert_eq!(st.doc.node(b).unwrap().extras().graphic_style, st.doc.graphic_style(&name).map(|g| g.id));
@@ -165,7 +165,7 @@ fn a_drop_runs_the_effect_of_its_payload() {
let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap());
let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone());
let uid = app.session.active().unwrap().uid;
let brush = |name: &str| Payload::Brush(BrushKey { doc: uid, name: name.into(), group: false });
let brush = |name: &str| Payload::Brush(BrushKey { doc: uid, reverts: 0, name: name.into(), group: false });
let library = |kind: &str, id: &str, name: &str| {
Payload::Library(LibraryKey { panel: library_panel::panel_id(kind, id), name: name.into(), folder: false })
};
@@ -200,7 +200,7 @@ fn a_drop_runs_the_effect_of_its_payload() {
drop_at(&mut app, library(SymbolLibraries::KIND, "basic-shapes", "Star"), on_b, Move).unwrap();
assert_eq!(undo_len(&app), n + 1, "a library symbol is added and placed in one step");
symbol_at(&app, on_b);
drop_at(&mut app, Payload::Symbol(SymbolKey { doc: uid, name: "Star".into() }), empty, Move).unwrap();
drop_at(&mut app, Payload::Symbol(SymbolKey { doc: uid, reverts: 0, name: "Star".into() }), empty, Move).unwrap();
symbol_at(&app, empty);
}
@@ -215,8 +215,13 @@ fn a_brush_with_art_dropped_inside_a_fill_with_path_only_places_nothing() {
app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap();
let uid = app.session.active().unwrap().uid;
let n = undo_len(&app);
drop_at(&mut app, Payload::Brush(BrushKey { doc: uid, name: "Arrow".into(), group: false }), Point::new(300.0, 240.0), DropOperation::Move)
.unwrap();
drop_at(
&mut app,
Payload::Brush(BrushKey { doc: uid, reverts: 0, name: "Arrow".into(), group: false }),
Point::new(300.0, 240.0),
DropOperation::Move,
)
.unwrap();
assert_eq!(undo_len(&app), n, "{}", app.ui.status);
}
@@ -235,6 +240,7 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() {
let swatch = |name: &str, paint: Paint| {
let rows = SwatchRows {
document,
reverts: 0,
grabbed: name.into(),
names: vec![name.into()],
groups: false,
@@ -288,7 +294,7 @@ fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() {
let before = brush_of(&app);
assert!(before.is_none());
let history = undo_len(&app);
let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false });
let payload = Payload::Brush(BrushKey { doc: document, reverts: 0, name: "Shared Brush".into(), group: false });
drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap();
assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone");
drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap();
@@ -308,7 +314,7 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let ctx = crate::testing::ui_context();
frame(&mut app, &ctx, vec![]);
let key = |doc| Payload::Symbol(SymbolKey { doc, name: "Leaf".into() });
let key = |doc| Payload::Symbol(SymbolKey { doc, reverts: 0, name: "Leaf".into() });
let at = Point::new(250.0, 180.0);
let n = undo_len(&app);
drop_at(&mut app, key(source), at, DropOperation::Move).unwrap();
@@ -338,6 +344,7 @@ fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() {
let paint = source.doc.swatch(name).unwrap().paint.clone();
let rows = SwatchRows {
document: source.uid,
reverts: source.reverts,
grabbed: name.into(),
names: vec![name.into()],
groups: false,
@@ -734,3 +741,82 @@ fn an_appearance_drop_after_file_revert_leaves_the_restored_object_unchanged() {
panel.release();
assert_eq!(fill(&panel.app()), red, "a drag started after the revert copies the appearance");
}
/// A graphic style, brush or symbol held across File › Revert, released on art on the canvas, makes no edit to the
/// restored contents, both where the canvas takes the drop and where the drop is applied. The same drag started after
/// the revert still applies or places it.
#[test]
fn a_style_brush_or_symbol_held_across_file_revert_is_not_dropped_on_the_canvas() {
use crate::tests::panel_harness::Panel;
use craft::ui::runtime::drag;
fn beside_canvas(app: &mut VectorcraftApp, ui: &mut egui::Ui, panel: fn(&mut VectorcraftApp, &mut egui::Ui)) {
app.sync_views();
egui::Panel::top("source panel").exact_size(220.0).show(ui, |ui| panel(app, ui));
canvas::show(app, ui);
}
fn styles(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
beside_canvas(app, ui, crate::panels::graphic_styles::show);
}
fn brushes(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
beside_canvas(app, ui, crate::panels::brushes::show);
}
fn symbols(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
beside_canvas(app, ui, crate::panels::symbols::show);
}
type Show = fn(&mut VectorcraftApp, &mut egui::Ui);
let panels: [(&str, Show); 3] = [("style", styles), ("brush", brushes), ("symbol", symbols)];
for (kind, show) in panels {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 30})).unwrap();
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
match kind {
"style" => app.run("graphicStyle.new", json!({"name": "Held"})).map(drop),
"brush" => app
.run("brush.new", json!({"name": "Held", "type": "art"}))
.and_then(|_| app.run("brush.setCurrent", json!({"name": null})).map(drop)),
_ => app.run("symbol.new", json!({"name": "Held"})).map(drop),
}
.unwrap();
app.run("path.create", json!({"anchors": [{"x": 200, "y": 150}, {"x": 380, "y": 150}]})).unwrap();
app.run("select.none", json!({})).unwrap();
let folder = vectorcraft_testkit::TempDir::new("canvas-panel-item-drop-revert");
let path = folder.join("drawing.vectorcraft");
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
app.run("shape.ellipse", json!({"x": 20, "y": 250, "width": 20, "height": 20})).unwrap();
app.run("select.none", json!({})).unwrap();
let mut panel = Panel::new(app, show);
let hold = |panel: &mut Panel| {
let from = panel.rect("Held").center();
let to = panel.app().canvas_view().unwrap().to_screen(Point::new(290.0, 150.0));
panel.drag_hold_between(from, to);
};
hold(&mut panel);
assert!(drag::mark(panel.ctx()).is_some(), "{kind}: the canvas takes it from the current contents");
let opening = panel.app().session.active().map(|st| (st.uid, st.reverts)).unwrap();
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
panel.frame();
assert_eq!(panel.app().session.active().map(|st| (st.uid, st.reverts)), Some((opening.0, opening.1 + 1)));
let history = undo_len(&panel.app());
assert!(drag::mark(panel.ctx()).is_none(), "{kind}: the canvas refuses it once the contents it came from are gone");
panel.release();
assert_eq!(undo_len(&panel.app()), history, "{kind}: the stale drop makes no edit");
let stale = match kind {
"style" => Payload::Style(StyleDrag { document: opening.0, reverts: opening.1, name: "Held".into() }),
"brush" => Payload::Brush(BrushKey { doc: opening.0, reverts: opening.1, name: "Held".into(), group: false }),
_ => Payload::Symbol(SymbolKey { doc: opening.0, reverts: opening.1, name: "Held".into() }),
};
drop_at(&mut panel.app(), stale, Point::new(290.0, 150.0), DropOperation::Move).unwrap();
assert_eq!(undo_len(&panel.app()), history, "{kind}: a stale payload that reaches the drop is not applied");
hold(&mut panel);
panel.release();
assert_eq!(undo_len(&panel.app()), history + 1, "{kind}: a drag started after the revert is still dropped");
}
}
+1 -1
View File
@@ -62,7 +62,7 @@ pub(crate) fn units() -> &'static [UnitKind] {
}
/// Lengths stored in points and shown in `unit`, a bare number read as Numbers Without Units Are Points says.
fn lengths(app: &VectorcraftApp, unit: Unit) -> LengthUnits {
pub(crate) fn lengths(app: &VectorcraftApp, unit: Unit) -> LengthUnits {
crate::fields::bare_points(
LengthUnits::new(UnitKind::Points, unit_kind(unit), PIXELS_PER_INCH),
app.session.prefs.numbers_without_units_are_points,
+36 -1
View File
@@ -59,6 +59,9 @@ struct Open {
struct Setting {
cmyk: bool,
units: LengthUnits,
/// Hairline Slivers' widths: the stroke unit (Preferences › Units › Stroke), or points when
/// that unit's field rounds the narrowest width to 0.
sliver_units: LengthUnits,
}
impl Setting {
@@ -67,8 +70,23 @@ impl Setting {
cmyk: app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk),
// PLAN: assumed `canvas::rulers::general_lengths(&VectorcraftApp) -> LengthUnits` (cv.B5)
units: crate::canvas::rulers::general_lengths(app),
sliver_units: crate::canvas::rulers::lengths(app, sliver_unit(app.session.stroke_unit())),
}
}
/// The length units of `command`'s distance rows.
fn units_for(self, command: &str) -> LengthUnits {
match command {
"object.path.cleanUp" | "select.object.hairlineSlivers" => self.sliver_units,
_ => self.units,
}
}
}
/// The unit Hairline Slivers' widths show in for the stroke unit `stroke`: `stroke`, or points
/// when `stroke` rounds the narrowest width to 0.
fn sliver_unit(stroke: vectorcraft_doc::Unit) -> vectorcraft_doc::Unit {
if stroke.number(*vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE.start()) == "0" { vectorcraft_doc::Unit::Points } else { stroke }
}
/// Opens the parameter dialog of `command`, headed `label`, on `params` (a menu item's own values, `__params` for the
@@ -283,7 +301,7 @@ fn row(command: &str, key: &str, value: &Value, setting: Setting) -> Option<Para
param = param.bounds(Some(*range.start()), Some(*range.end()));
}
if lengths(command).contains(&key) {
param = param.length(setting.units);
param = param.length(setting.units_for(command));
if let Some(range) = length_range(command, key) {
param = param.bounds(Some(*range.start()), Some(*range.end()));
}
@@ -399,6 +417,8 @@ fn lengths(command: &str) -> &'static [&'static str] {
crate::addons::cutting::BRIDGES => &["width"],
"object.textWrap.options" => &["offset"],
crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset"],
"object.path.cleanUp" => &["sliverWidth"],
"select.object.hairlineSlivers" => &["width"],
_ => &[],
}
}
@@ -413,6 +433,7 @@ pub(crate) fn length_range(command: &str, key: &str) -> Option<std::ops::RangeIn
(crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE, "offset") => {
Some(0.0..=vectorcraft_engine::MAX_COORD)
}
("object.path.cleanUp", "sliverWidth") | ("select.object.hairlineSlivers", "width") => Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE),
_ => None,
}
}
@@ -446,6 +467,7 @@ fn order(command: &str) -> &'static [&'static str] {
crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"],
crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"],
crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"],
"object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"],
_ => &[],
}
}
@@ -1157,4 +1179,17 @@ mod tests {
answer_ok(&mut app);
assert_eq!(fold_angle(&mut app, a), Some(-180.0));
}
/// Hairline Slivers' widths show in the stroke unit, or in points when that unit rounds the
/// narrowest width (0.001 pt) to 0.
#[test]
fn sliver_widths_show_in_the_stroke_unit_unless_it_rounds_them_to_zero() {
use vectorcraft_doc::Unit;
assert_eq!(sliver_unit(Unit::Points), Unit::Points);
assert_eq!(sliver_unit(Unit::Millimeters), Unit::Millimeters);
assert_eq!(sliver_unit(Unit::Inches), Unit::Points);
assert!(lengths("object.path.cleanUp").contains(&"sliverWidth"));
assert!(lengths("select.object.hairlineSlivers").contains(&"width"));
assert_eq!(length_range("object.path.cleanUp", "sliverWidth"), Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE));
}
}
+3 -2
View File
@@ -185,11 +185,12 @@ pub(crate) fn heading(cx: &EffectCx) -> String {
}
/// The effect's name in the UI language as the Effect menu shows it ([`crate::i18n::effect_name`]).
/// A plug-in effect's name is shown as it is.
/// A plug-in effect's name is the plug-in's in the UI language
/// ([`super::plugin::effect_name`]).
pub(crate) fn label(id: &str) -> String {
let name = vectorcraft_effects::effect_info(id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string());
if vectorcraft_plugins::effect::plugin_id(id).is_some() {
return name;
return super::plugin::effect_name(id).unwrap_or(name);
}
crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or(name)
}
+44 -12
View File
@@ -14,6 +14,8 @@ use craft::ui::value_drag::SliderScale;
use serde_json::{Map, Value, json};
use vectorcraft_plugins::{Manifest, Param as PluginParam, ParamSpec};
use crate::i18n::LangExt as _;
/// The fields of the form dialogs ([`grid_params`]) that are distances, by dialog kind.
fn lengths(kind: &str) -> &'static [&'static str] {
match kind {
@@ -290,11 +292,42 @@ fn text_row(
.opens_with(start)
}
/// The row of the plug-in parameter `key`, without its visibility.
fn plugin_row(key: &str, p: &PluginParam) -> Param {
/// The UI language's code, which a plug-in's translations are looked up under.
fn plugin_lang() -> &'static str {
crate::i18n::current().code()
}
/// Plug-in text `s` as a dialog shows it: each line with its control and bidirectional characters
/// escaped ([`vectorcraft_plugins::permissions::display_text`]), so a label or help can't reorder
/// the text around it.
fn plugin_text(s: &str) -> String {
let lines: Vec<String> =
s.split('\n').map(|l| vectorcraft_plugins::permissions::display_text(l, vectorcraft_plugins::dialog::MAX_HELP)).collect();
lines.join("\n")
}
/// Parameter `k`'s `label` in manifest `m`, in the UI language as dialogs show it ([`plugin_text`]);
/// `None` when it gives none.
pub(crate) fn plugin_param_label(m: &Manifest, k: &str) -> Option<String> {
m.param_label_in(k, plugin_lang()).map(plugin_text)
}
/// Parameter `k`'s `help` in manifest `m`, in the UI language as dialogs show it.
pub(crate) fn plugin_param_help(m: &Manifest, k: &str) -> Option<String> {
m.param_help_in(k, plugin_lang()).map(plugin_text)
}
/// The label of value `option` of choice `k` in manifest `m`, in the UI language as dialogs show it.
pub(crate) fn plugin_option_label(m: &Manifest, k: &str, option: &str) -> String {
plugin_text(m.option_label_in(k, option, plugin_lang()))
}
/// The row of the plug-in parameter `key` of manifest `m`, without its visibility. Its label, help and choices are
/// the plug-in's text in the UI language ([`vectorcraft_plugins::translations`]), escaped as [`plugin_text`] shows it.
fn plugin_row(m: &Manifest, key: &str, p: &PluginParam) -> Param {
let unit_text = p.ui.unit.as_deref().unwrap_or_default();
let unit = unit_kind(unit_text);
let base = p.ui.label.clone().unwrap_or_else(|| humanize(key));
let base = plugin_param_label(m, key).unwrap_or_else(|| humanize(key));
let base = base.trim_end_matches(':');
// A unit the framework has no kind for stays in the label, so the plug-in's own unit is still shown.
let name = Label::from(if unit.is_none() && !unit_text.is_empty() { format!("{base} ({unit_text})") } else { base.to_owned() });
@@ -328,7 +361,7 @@ fn plugin_row(key: &str, p: &PluginParam) -> Param {
}
ParamSpec::Bool { default } => Param::new(key, name, ParamKind::bool(*default)),
ParamSpec::Choice { options, default } => {
let entries = options.iter().map(|o| (o.clone(), Label::from(o.clone()))).collect();
let entries = options.iter().map(|o| (o.clone(), Label::from(plugin_option_label(m, key, o)))).collect();
Param::new(key, name, ParamKind::choice(entries, default.clone()))
}
ParamSpec::Text { default, max_length } => text_row(
@@ -355,8 +388,8 @@ fn plugin_row(key: &str, p: &PluginParam) -> Param {
if let Some(unit) = unit {
row = row.unit(unit);
}
if let Some(help) = &p.ui.help {
row = row.tooltip(help.clone());
if let Some(help) = plugin_param_help(m, key) {
row = row.tooltip(help);
}
if let Some(url) = &p.ui.help_url {
row = row.help_link(url.clone());
@@ -365,9 +398,9 @@ fn plugin_row(key: &str, p: &PluginParam) -> Param {
}
/// A plug-in's parameter rows from its manifest (the filter, live effect and exporter dialogs): a row each, labelled
/// as the manifest says (else from the parameter's name), with its help on the label and on a help button that opens
/// its page ([`open_help`]). Parameters outside any group come first, then each group as a section that folds
/// ([`Manifest::sections`]).
/// as the manifest says in the UI language (else from the parameter's name), with its help on the label and on a help
/// button that opens its page ([`open_help`]). Parameters outside any group come first, then each group as a section
/// that folds ([`Manifest::sections`]), headed by the group's text in the UI language.
///
/// A parameter whose `visibleWhen` the values don't meet is hidden by its row, as [`Manifest::visible`] decides it:
/// shown only when every parameter it names is itself shown, so a row carries its own conditions and those of the
@@ -391,11 +424,11 @@ pub(crate) fn plugin_params(manifest: &Manifest, _fields: &Map<String, Value>) -
let mut rows = Vec::new();
for (group, members) in manifest.sections() {
if let Some(group) = group {
rows.push(Param::group(Label::from(group.to_owned())));
rows.push(Param::group(Label::from(plugin_text(manifest.group_in(group, plugin_lang())))));
}
for (key, p) in members {
let when = conditions.remove(key.as_str()).unwrap_or_default();
rows.push(when.into_iter().fold(plugin_row(key, p), |row, (other, allowed)| row.visible_when_in(other, allowed)));
rows.push(when.into_iter().fold(plugin_row(manifest, key, p), |row, (other, allowed)| row.visible_when_in(other, allowed)));
}
}
rows
@@ -501,7 +534,6 @@ pub(super) fn humanized(k: &str) -> String {
#[cfg(test)]
mod plugin_field_tests {
use super::*;
use crate::i18n::LangExt as _;
/// [`json_of`] reads back what [`fields_of`] took in: numbers as the command reads them, a flag pair as a bool,
/// unknown keys through, UI-only keys dropped.
+146 -16
View File
@@ -56,6 +56,7 @@ use vectorcraft_plugins::{Budget, ContextMenu, ContextWhen, Kind, Manifest, Plug
use super::form;
use super::preview::LivePreview;
use crate::VectorcraftApp;
use crate::i18n::LangExt as _;
use crate::menus::{Sep, c, cp, placeholder, sub};
/// The key of the hosted dialog of plug-in filters.
@@ -66,6 +67,75 @@ const CMD: &str = "plugin.run";
/// Object › Plug-ins' disabled row while no filter plug-in is installed.
pub const NO_FILTERS: &str = "No filter plug-ins installed";
/// The UI language's code, which a plug-in's translations are looked up under
/// ([`vectorcraft_plugins::translations`]): plug-in text comes from the plug-in, never from the
/// app's catalogs.
fn lang() -> &'static str {
crate::i18n::current().code()
}
/// Menu path `path` (English, `›`-separated) with each segment put through `tr`, except the
/// segments after Object › Plug-ins or Effect › Plug-ins: those are a plug-in's name and its items,
/// already in the UI language from the plug-in's translations.
pub(crate) fn translate_path<'a>(path: &'a str, tr: impl Fn(&'a str) -> &'a str) -> String {
let parts: Vec<&str> = path.split(" › ").collect();
let plugin = matches!(parts.as_slice(), ["Object" | "Effect", "Plug-ins", _, ..]);
parts.iter().enumerate().map(|(i, s)| if plugin && i >= 2 { s } else { tr(s) }).collect::<Vec<_>>().join(" › ")
}
/// Plug-in `id`'s name in the UI language as menus show it, without a trailing ellipsis (`None`
/// while no such plug-in is installed).
pub(crate) fn shown_name(id: &str) -> Option<String> {
registry::get(id).map(|p| p.manifest().shown_name(lang()).trim_end_matches('…').to_string())
}
/// The name of live effect `effect` (an effect id) in the UI language when a plug-in gives it
/// ([`shown_name`]); `None` for a built-in effect.
pub(crate) fn effect_name(effect: &str) -> Option<String> {
vectorcraft_plugins::effect::plugin_id(effect).and_then(shown_name)
}
/// Effect › Plug-ins' label for live effect `e`: its plug-in's name in the UI language, with an
/// ellipsis when it opens a dialog ([`label`]); the catalog's label once the plug-in is gone.
pub(crate) fn effect_item_label(e: &vectorcraft_effects::EffectInfo) -> &'static str {
match vectorcraft_plugins::effect::plugin_id(e.id).and_then(registry::get) {
Some(p) => label(&p.manifest().shown_name(lang()), !p.manifest().params.is_empty()),
None => e.label,
}
}
/// The menu label of plug-in item `key` (`plugin:<filter id>` or `effect:<effect id>`) in language
/// `code`, as [`object_menu`] and [`effect_menu`] show it in that language; `None` for any other key
/// or a plug-in that is not installed.
pub(crate) fn item_label_in(key: &str, code: &str) -> Option<&'static str> {
let m = item_plugin(key)?;
let m = m.manifest();
Some(label(&m.shown_name(code), !m.params.is_empty()))
}
/// Menu path `group` of plug-in item `key` ([`item_label_in`]) with its plug-in's submenu, the
/// segment after Object › Plug-ins or Effect › Plug-ins, named in language `code`; `group` as it
/// is for an item without a submenu.
pub(crate) fn item_group_in(key: &str, group: &str, code: &str) -> String {
let mut parts: Vec<String> = group.split(" › ").map(str::to_string).collect();
if parts.get(1).is_some_and(|p| p == "Plug-ins")
&& let (Some(plugin), Some(submenu)) = (item_plugin(key), parts.get_mut(2))
{
*submenu = plugin.manifest().shown_name(code);
}
parts.join(" › ")
}
/// The plug-in of item `key` (`plugin:<filter id>` or `effect:<effect id>`), if it is installed.
fn item_plugin(key: &str) -> Option<Arc<Plugin>> {
let id = match (key.strip_prefix("plugin:"), key.strip_prefix("effect:")) {
(Some(id), _) => id,
(_, Some(effect)) => vectorcraft_plugins::effect::plugin_id(effect)?,
_ => return None,
};
registry::get(id)
}
/// A menu label for plug-in `name`: with an ellipsis when it opens a dialog.
fn label(name: &str, has_params: bool) -> &'static str {
let dots = if has_params && !name.ends_with('…') { "…" } else { "" };
@@ -75,7 +145,7 @@ fn label(name: &str, has_params: bool) -> &'static str {
/// A filter or live effect `plugin`'s item `own`, as the menu lists it: alone, or for a plug-in
/// with commands of its own, a submenu named after it holding `own` and then its commands. Each
/// command runs its command id (`plugin.<id>.<command>`), with an ellipsis when it has parameters,
/// whose dialog [`open_command`] opens.
/// whose dialog [`open_command`] opens. Names and labels are in the UI language.
fn with_commands(plugin: &Plugin, own: Node) -> Node {
let m = plugin.manifest();
if m.commands.is_empty() {
@@ -84,9 +154,9 @@ fn with_commands(plugin: &Plugin, own: Node) -> Node {
let mut items = vec![own, Sep];
items.extend(m.commands.iter().map(|command| {
let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &command.id));
c(label(&command.shown_label(), !command.params.is_empty()), id)
c(label(&m.shown_command_label(command, lang()), !command.params.is_empty()), id)
}));
sub(registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)), items)
sub(registry::intern(&m.shown_name(lang())), items)
}
/// Moves each plug-in command whose manifest's `menu` names another menu
@@ -116,7 +186,7 @@ pub fn place_commands(tree: &mut [(&'static str, Vec<Node>)]) {
menu.iter().find(|it| is_anchor(it, anchor_key(a))).and_then(own_key).map(str::to_string)
});
let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &command.id));
let item = c(label(&command.menu_label(&m.name), !command.params.is_empty()), id);
let item = c(label(&m.shown_command_menu_label(command, lang()), !command.params.is_empty()), id);
match spots.iter_mut().find(|s| s.0 == place.path && s.1 == after) {
Some(s) => s.2.push(item),
None => spots.push((place.path, after, vec![item])),
@@ -274,13 +344,16 @@ pub fn canvas_item_enabled(app: &VectorcraftApp, id: &str, p: &Value) -> bool {
}
/// Object › Plug-ins: the installed object filters (each with its commands, if it has any) and
/// generators, then Edit Generated Art…, Install Plug-in…, Reload Plug-ins and Plug-ins That Didn't
/// Load… ([`super::failed_plugins`]).
/// generators by their names in the UI language, then Edit Generated Art…, Install Plug-in…, Reload
/// Plug-ins and Plug-ins That Didn't Load… ([`super::failed_plugins`]).
pub fn object_menu() -> Vec<Node> {
let mut items: Vec<Node> = registry::list()
.iter()
.filter(|p| matches!(p.manifest().kind, Kind::Filter | Kind::Generator))
.map(|p| with_commands(p, cp(label(&p.manifest().name, !p.manifest().params.is_empty()), "plugin.dialog", json!({ "id": p.id() }))))
.map(|p| {
let m = p.manifest();
with_commands(p, cp(label(&m.shown_name(lang()), !m.params.is_empty()), "plugin.dialog", json!({ "id": p.id() })))
})
.collect();
if items.is_empty() {
items.push(placeholder(NO_FILTERS));
@@ -298,11 +371,15 @@ pub fn object_menu() -> Vec<Node> {
/// File › Open With's disabled row while no importer plug-in is installed.
pub const NO_IMPORTERS: &str = "No importer plug-ins installed";
/// File › Open With: the installed importers (`file.openWith {importer}`), each by its name.
/// File › Open With: the installed importers (`file.openWith {importer}`), each by its name in the
/// UI language.
pub fn open_with_menu() -> Vec<Node> {
let items: Vec<Node> = vectorcraft_plugins::import::installed()
.iter()
.map(|p| cp(label(&p.manifest().name, true), "file.openWith", json!({ "importer": vectorcraft_plugins::export::format_id(p.id()) })))
.map(|p| {
let importer = vectorcraft_plugins::export::format_id(p.id());
cp(label(&p.manifest().shown_name(lang()), true), "file.openWith", json!({ "importer": importer }))
})
.collect();
if items.is_empty() { vec![placeholder(NO_IMPORTERS)] } else { items }
}
@@ -313,9 +390,10 @@ pub fn effect_menu() -> Option<Node> {
let items: Vec<Node> = vectorcraft_effects::plugin_effects()
.into_iter()
.map(|e| {
let label = effect_item_label(&e);
let own = match e.defaults.as_object().is_some_and(|o| o.is_empty()) {
true => cp(e.label, "effect.apply", json!({ "effect": e.id })),
false => cp(e.label, "effect.dialog", json!({ "effect": e.id })),
true => cp(label, "effect.apply", json!({ "effect": e.id })),
false => cp(label, "effect.dialog", json!({ "effect": e.id })),
};
match vectorcraft_plugins::effect::plugin_id(e.id).and_then(registry::get) {
Some(plugin) => with_commands(&plugin, own),
@@ -432,7 +510,12 @@ impl Opened {
/// How a hosted plug-in dialog looks.
struct Look {
/// The heading: the plug-in's or command's label, as it is (plug-in text is never translated).
/// The plug-in the dialog is for.
plugin: String,
/// The plug-in command the dialog is for (`plugin.<plug-in id>.<command id>`); `None` for the
/// plug-in's own dialog.
command: Option<String>,
/// The heading once the plug-in or command is gone: its manifest's own text ([`Look::heading`]).
title: String,
/// The plug-in's description, drawn above the rows.
description: String,
@@ -444,17 +527,44 @@ struct Look {
ok: Option<&'static str>,
}
impl Look {
/// The heading ([`heading`]), read each time the dialog is built so a change of language shows at once.
fn heading(&self) -> String {
heading(&self.plugin, self.command.as_deref(), &self.title)
}
}
/// The heading of the dialog of plug-in `plugin`, or of its command `command`
/// (`plugin.<plug-in id>.<command id>`): the command's label, else the plug-in's name, in the UI language as menus
/// show it; `gone` once the plug-in or command is no longer installed.
pub(super) fn heading(plugin: &str, command: Option<&str>, gone: &str) -> String {
let shown = match command {
None => shown_name(plugin),
Some(c) => vectorcraft_engine::cmd::plugin::command_of(c).map(|(p, c)| p.manifest().shown_command_label(&c, lang())),
};
shown.unwrap_or_else(|| gone.to_string())
}
/// The builder of a hosted plug-in dialog over its values: the rows of `all` whose parameter is
/// shown for the values (`m.visible`), after the description.
/// shown for the values (`m.visible`), after the description. The rows are made again in the UI
/// language when it changes while the dialog is open; the field values stay as they are.
fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
let rows_in = std::sync::Mutex::new((lang(), all));
move |fields| {
let all = {
let mut made = rows_in.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if made.0 != lang() {
*made = (lang(), form::plugin_params(&m, &m.defaults()).into());
}
Arc::clone(&made.1)
};
let shown = m.visible(&form::json_of(&all, fields));
let mut rows = Vec::with_capacity(all.len() + 1);
if !look.description.is_empty() {
rows.push(Param::read_only_text("description", "", look.description.clone()).full_width());
}
rows.extend(all.iter().filter(|p| shown.contains(p.key.as_str())).cloned());
let mut dialog = ParamDialog::new(key, look.title.clone(), Cow::Owned(rows)).previews(look.previews);
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews);
if let Some(ok) = look.ok {
dialog = dialog.ok_label(ok.into());
}
@@ -731,7 +841,15 @@ fn open_filter(
let own = plugin.manifest();
let heavy = own.budget == Budget::Heavy;
let light = !heavy && !crate::plugin_runs::in_workers(app);
let look = Look { title: heading.clone(), description: own.description.clone(), previews: light, note: heavy, ok: None };
let look = Look {
plugin: plugin.id().to_string(),
command: command.clone(),
title: heading.clone(),
description: own.description.clone(),
previews: light,
note: heavy,
ok: None,
};
let instance = command.as_deref().unwrap_or(plugin.id()).to_string();
let (id, params) = open_hosted(app, KIND, &instance, m, values, look)?;
let kind = Opened::Filter {
@@ -830,7 +948,15 @@ const EDIT_DOC_GONE: &str = "the document it was prepared for is no longer activ
/// defaults, for new generated art, or for drawing the object of `edit` again.
fn open_generate(app: &mut VectorcraftApp, plugin: &Plugin, edit: Option<EditTarget>, values: &Map<String, Value>) -> Result<(), String> {
let m = plugin.manifest();
let look = Look { title: m.name.trim_end_matches('…').to_string(), description: m.description.clone(), previews: false, note: false, ok: None };
let look = Look {
plugin: plugin.id().to_string(),
command: None,
title: m.name.trim_end_matches('…').to_string(),
description: m.description.clone(),
previews: false,
note: false,
ok: None,
};
let rows = vectorcraft_plugins::generate::resolve_over(plugin, values, &Value::Null).map_err(|error| error.to_string())?;
let (id, params) = open_hosted(app, GENERATE_KIND, plugin.id(), m.clone(), rows, look)?;
app.plugin_dialog = Some(PluginDialog { id, kind: Opened::Generate { plugin: plugin.id().to_string(), edit, params } });
@@ -889,6 +1015,8 @@ pub const IMPORT_KIND: &str = "pluginImport";
pub fn open_export(app: &mut VectorcraftApp, plugin: &Plugin, export: Value) {
let m = plugin.manifest();
let look = Look {
plugin: plugin.id().to_string(),
command: None,
title: m.name.trim_end_matches('…').to_string(),
description: m.description.clone(),
previews: false,
@@ -910,6 +1038,8 @@ pub fn open_export(app: &mut VectorcraftApp, plugin: &Plugin, export: Value) {
pub fn open_import(app: &mut VectorcraftApp, plugin: &Plugin, open: Value) {
let m = plugin.manifest();
let look = Look {
plugin: plugin.id().to_string(),
command: None,
title: m.name.trim_end_matches('…').to_string(),
description: m.description.clone(),
previews: false,
+5 -3
View File
@@ -302,10 +302,11 @@ fn option_rows(f: &Format, o: &FormatOption, menus: &Arc<Menus>, legacy: bool) -
});
return vec![row(ParamKind::choice(entries.collect(), None))];
}
// Only the colour preview can keep transparency.
// Only the colour preview can keep transparency. The options stand with no caption over them; the option's label
// names the group for assistive technology.
if f.id == "eps" && o.name == "transparentPreview" {
let kind = ParamKind::radio(vec![("true".into(), tl!("Transparent").into()), ("false".into(), tl!("Opaque").into())], None);
return vec![Param::new(o.name, "", kind).enabled_when("previewFormat", "tiffColor")];
return vec![Param::new(o.name, label.clone(), kind).stacked_options().enabled_when("previewFormat", "tiffColor")];
}
// Type is written as glyph outlines, which need no fonts: the row is on, and never enabled.
if f.id == "eps" && o.name == "embedFonts" {
@@ -320,7 +321,8 @@ fn option_rows(f: &Format, o: &FormatOption, menus: &Arc<Menus>, legacy: bool) -
let mut rows = vec![check];
if matches!(o.name, "separateArtboards" | "useArtboards") {
let all = ParamKind::radio(vec![("true".into(), tl!("All").into()), ("false".into(), tl!("Range:").into())], None);
rows.push(Param::new("all", "", all).enabled_when(o.name, true));
// Right under the check box, with no caption over the options.
rows.push(Param::new("all", "", all).stacked_options().enabled_when(o.name, true));
rows.push(Param::new("range", "", ParamKind::text("")).hint("1-3, 5").enabled_when("all", "false"));
}
rows
@@ -513,6 +513,60 @@ fn eps_save_transparency_follows_the_color_preview() {
assert_eq!(dialog(&mut app).bool("embedFonts"), Some(true));
}
/// The open dialog's labelled controls with their bounds, as a screen reader is told them, after a few frames of a
/// 1440x900 window.
fn labelled_controls(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> {
let ctx = app.ui_ctx.clone().unwrap();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
let mut nodes = Vec::new();
for _ in 0..4 {
let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() };
nodes = crate::testing::app_frame(app, &ctx, input).platform_output.accesskit_update.map_or_else(Vec::new, |u| u.nodes);
}
nodes
.iter()
.filter_map(|(_, node)| {
let b = node.bounds()?;
Some((node.label()?.to_string(), egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))))
})
.collect()
}
/// The bounds of the control labelled `label` in `controls`, with or without a final colon.
fn control(controls: &[(String, egui::Rect)], label: &str) -> egui::Rect {
let bare = |l: &str| l.trim_end_matches(':').to_string();
controls
.iter()
.find(|(l, _)| bare(l) == bare(label))
.map(|(_, r)| *r)
.unwrap_or_else(|| panic!("no control labelled {label:?} in {:?}", controls.iter().map(|(l, _)| l).collect::<Vec<_>>()))
}
/// The All and Range radios stand right under the artboard check box, and EPS's Transparent and Opaque radios right
/// under the Preview menu, with no empty caption over them: an empty caption leaves a band about a row tall.
#[test]
fn save_options_radios_have_no_empty_caption_over_them() {
for (picked, check) in [("art.eps", "Use Artboards"), ("art.ai", "Save each artboard to a separate file")] {
let (mut app, _, _) = desktop(picked);
save_as(&mut app, "file.saveAs");
let controls = labelled_controls(&mut app);
let (check, all, range) = (control(&controls, check), control(&controls, "All"), control(&controls, "Range:"));
assert!(all.top() - check.bottom() <= check.height() / 2.0, "{picked}: All at {all:?}, the check box at {check:?}");
assert!(range.top() - all.bottom() <= all.height() / 2.0, "{picked}: Range at {range:?}, All at {all:?}");
if picked == "art.eps" {
let transparent = control(&controls, "Transparent");
// The Preview menu: the nearest control so named above the radios (the window has other Preview controls).
let preview = controls
.iter()
.filter(|(l, r)| l.trim_end_matches(':') == "Preview" && r.bottom() <= transparent.top())
.map(|(_, r)| *r)
.max_by(|a, b| a.bottom().total_cmp(&b.bottom()))
.expect("the Preview menu above Transparent");
assert!(transparent.top() - preview.bottom() <= check.height() / 2.0, "Transparent at {transparent:?}, Preview at {preview:?}");
}
}
}
#[test]
fn a_native_save_options_draft_cannot_redirect_its_path_to_another_drawing() {
let (mut app, written, _) = desktop("original.vectorcraft");
+4 -3
View File
@@ -4,7 +4,7 @@
//! A script's ScriptUI dialog is in [`script_window`]; these questions and dialogs open over it.
//!
//! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it
//! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show
//! asks for a `.js`, `.mjs` or `.jsx` file through the app's file asks. With Preferences › General › Show
//! External Script Warning off, the chosen script runs at once. With General › Run Startup Scripts
//! on, the startup scripts run first (`script.startup.run`). The warning (kind `scriptRun`) is a
//! prompt: its `choice` field (`proceed` runs, `cancel` does not), `skip` (true: turn the warning
@@ -551,7 +551,8 @@ pub(crate) fn picked_script(app: &mut VectorcraftApp, picked: Picked) -> Result<
return Err(TOO_LARGE.to_string());
}
let source = String::from_utf8(bytes).map_err(|_| "the script is not UTF-8 text".to_string())?;
return chosen(app, json!({"source": source, "name": name}));
let module = Path::new(&name).extension().is_some_and(|e| e.eq_ignore_ascii_case("mjs"));
return chosen(app, json!({"source": source, "name": name, "module": module}));
}
match picked.paths().into_iter().next() {
Some(path) => chosen(app, json!({ "path": path.to_string_lossy() })),
@@ -563,7 +564,7 @@ pub(crate) fn picked_script(app: &mut VectorcraftApp, picked: Picked) -> Result<
pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result<Value, String> {
let path = params.get("path").and_then(Value::as_str);
if path.is_some_and(|path| !runs(path)) {
return Err("Choose a .js or .jsx script".into());
return Err("Choose a .js, .mjs or .jsx script".into());
}
if !app.session.prefs.show_external_script_warning {
return crate::script_runs::run_chosen(app, params);
@@ -11,6 +11,7 @@ use vectorcraft_plugins::wat as tpl;
use super::tests_export::fields;
use super::tests_plugin_export::top;
use crate::VectorcraftApp;
use crate::i18n::LangExt as _;
/// A filter whose parameters use every presentation key.
fn manifest(id: &str) -> String {
@@ -33,9 +34,14 @@ type Harness = egui_kittest::Harness<'static, VectorcraftApp>;
/// The dialog of plug-in `id` in a window running whole app frames.
fn harness(id: &str) -> Harness {
harness_of(id, &manifest(id))
}
/// The dialog of plug-in `id`, installed from `manifest`, in a window running whole app frames.
fn harness_of(id: &str, manifest: &str) -> Harness {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let wasm = wat::parse_str(tpl::module(&manifest(id), tpl::ECHO, "", 1)).unwrap();
let wasm = wat::parse_str(tpl::module(manifest, tpl::ECHO, "", 1)).unwrap();
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap();
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state(
@@ -155,3 +161,99 @@ fn the_help_button_opens_the_parameter_s_page() {
assert!(opened(&h).is_empty(), "nothing opened for automation");
remove(&mut h, id);
}
/// A row of a plug-in's dialog as shown: its key, its label and its choices' (value, label) pairs.
type ShownRow = (String, String, Vec<(String, String)>);
/// A plug-in's dialog shows the text its manifest's `translations` give in the UI language (the
/// heading, a label, a group heading and a choice's label) and its own text in any other language;
/// the choice still passes its value. Plug-in text with a right-to-left override is shown escaped.
#[test]
fn plugin_dialogs_show_the_plugins_text_in_the_ui_language() {
let id = "test.dialogs.translated";
// The override as a JSON escape in the manifest.
let rlo = format!("\\u{:04X}", 0x202E);
let manifest = format!(
r#"{{"id":"{id}","name":"Tidy","kind":"filter","params":{{
"mode":{{"type":"choice","options":["soft","hard"],"label":"Mode","group":"Shape","help":"How hard."}},
"flip":{{"type":"bool","label":"Flip{rlo}txt"}}}},
"commands":[{{"id":"grow","label":"Grow","params":{{"by":{{"type":"number","min":0,"max":10,"default":2,"label":"By"}}}}}}],
"translations":{{"de":{{"name":"Aufräumen","params":{{"mode":{{"label":"Modus","options":{{"soft":"Weich"}}}}}},
"groups":{{"Shape":"Form"}},"commands":{{"grow":{{"label":"Wachsen","params":{{"by":{{"label":"Um"}}}}}}}}}}}}}}"#
);
let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap();
let installed = vectorcraft_plugins::registry::install_bytes(&module).unwrap();
// The rows' labels, section headings and choice labels in `lang`, as (key, label, choices).
let shown = |lang: &str, m: &vectorcraft_plugins::Manifest| {
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).expect("language registered"));
let rows = super::form::plugin_params(m, &Map::new());
crate::i18n::set_current(crate::i18n::Lang::EN);
rows.iter()
.map(|p| {
let choices: Vec<(String, String)> = match &p.kind {
craft::ui::patterns::form_dialogs::ParamKind::Choice { options, .. } => {
options.iter().map(|(v, l)| (v.clone(), l.as_str().to_string())).collect()
}
_ => Vec::new(),
};
(p.key.clone(), p.label.as_str().to_string(), choices)
})
.collect::<Vec<_>>()
};
let label = |rows: &[ShownRow], key: &str| rows.iter().find(|r| r.0 == key).map(|r| r.1.clone()).unwrap_or_else(|| panic!("no row for {key}"));
let sections = |rows: &[ShownRow]| rows.iter().filter(|r| r.0.starts_with("section:")).map(|r| r.1.clone()).collect::<Vec<_>>();
let choices = |rows: &[ShownRow]| rows.iter().find(|r| r.0 == "mode").map(|r| r.2.clone()).unwrap_or_default();
let m = installed.manifest();
let (de, en) = (shown("de", m), shown("en", m));
assert_eq!((label(&de, "mode"), sections(&de)), ("Modus".to_string(), vec!["Form".to_string()]));
assert_eq!(choices(&de), [("soft".to_string(), "Weich".to_string()), ("hard".to_string(), "hard".to_string())], "values stay");
assert_eq!((label(&en, "mode"), sections(&en)), ("Mode".to_string(), vec!["Shape".to_string()]));
assert_eq!(choices(&en), [("soft".to_string(), "soft".to_string()), ("hard".to_string(), "hard".to_string())]);
assert_eq!(label(&de, "flip"), "Flip\\u{202E}txt");
assert!(!de.iter().chain(&en).any(|r| r.1.contains('\u{202E}')), "the override is never shown as one");
// The heading follows the language it is drawn in, for the filter and for its command.
let command = format!("plugin.{id}.grow");
let heading = |lang: &str, command: Option<&str>, gone: &str| {
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap());
let shown = super::plugin::heading(id, command, gone);
crate::i18n::set_current(crate::i18n::Lang::EN);
shown
};
assert_eq!((heading("de", None, "Tidy"), heading("en", None, "Tidy")), ("Aufräumen".to_string(), "Tidy".to_string()));
assert_eq!((heading("de", Some(&command), "Grow"), heading("fr", Some(&command), "Grow")), ("Wachsen".to_string(), "Grow".to_string()));
let grow = m.for_command(m.command("grow").unwrap());
assert_eq!(label(&shown("de", &grow), "by"), "Um");
vectorcraft_plugins::registry::remove(id);
assert_eq!(heading("de", None, "Tidy"), "Tidy", "the manifest's own name once the plug-in is gone");
}
/// A change of the UI language while a plug-in's dialog is open shows its rows in the new
/// language, and the values set before stay.
#[test]
fn an_open_plugin_dialog_follows_a_change_of_language() {
use craft::ui::patterns::form_dialogs::HostedParamDialog;
let id = "test.ui.fields.relabel";
let manifest = format!(
r#"{{"id":"{id}","name":"Relabel","version":"1","kind":"filter","params":{{
"size":{{"type":"number","min":1,"max":9,"default":3,"label":"Size"}}}},
"translations":{{"de":{{"params":{{"size":{{"label":"Größe"}}}}}}}}}}"#
);
let mut h = harness_of(id, &manifest);
let labels = |h: &Harness| {
let dialog = h.get_by_role(egui::accesskit::Role::Dialog);
(dialog.query_all_by_label_contains("Size").count() > 0, dialog.query_all_by_label_contains("Größe").count() > 0)
};
assert_eq!(labels(&h), (true, false));
set(&mut h, "size", json!(7)).unwrap();
h.state_mut().session.prefs.interface_language = "de".into();
h.run_steps(2);
let shown = labels(&h);
let rows = super::form::plugin_params(vectorcraft_plugins::registry::get(id).unwrap().manifest(), &Map::new());
let dialogs = h.state().dialogs().unwrap();
let values = dialogs.with(|host| host.get::<HostedParamDialog>().map(|d| super::form::json_of(&rows, d.fields())));
h.state_mut().session.prefs.interface_language = "en".into();
h.run_steps(2);
remove(&mut h, id);
assert_eq!(shown, (false, true), "the label in German");
assert_eq!(values.unwrap()["size"].as_f64(), Some(7.0), "the value set before");
}
+1
View File
@@ -7390,6 +7390,7 @@ axis Y Axis Y ос
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Да се инсталира ли „{name}“, който иска тези права?
ID: {id} ID: {id}
Manifest name: {name} Име в манифеста: {name}
Version: {version} Версия: {version}
Install “{name}” in place of the plug-in with the same ID? Да се инсталира ли „{name}“ на мястото на приставката със същия ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Този файл не е приставката, инсталирана преди с този ID. Той получава настройките и кеша, пазени за този ID.
Can't render this file because it is too large.
+1
View File
@@ -6745,6 +6745,7 @@ axis Y Axis Y osa
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Instalirati „{name}”, koji traži ove dozvole?
ID: {id} ID: {id}
Manifest name: {name} Naziv u manifestu: {name}
Version: {version} Verzija: {version}
Install “{name}” in place of the plug-in with the same ID? Instalirati „{name}” umjesto dodatka s istim ID-om?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ova datoteka nije dodatak ranije instaliran s ovim ID-om. Dobija postavke i predmemoriju sačuvane za taj ID.
Can't render this file because it contains an unexpected character in line 2 and column 73.
+8 -2
View File
@@ -6466,7 +6466,7 @@ digits Malayalam Malaiàlam
Do not show this warning again No tornis a mostrar aquest avís
Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir.
This script has added a great many objects. Continue, or stop it and undo what it did? Aquest script ha afegit moltíssims objectes. Voleu continuar, o aturar-lo i desfer el que ha fet?
@msg Choose a .js or .jsx script Trieu un script .js o .jsx
@msg Choose a .js, .mjs or .jsx script Trieu un script .js, .mjs o .jsx
@msg Ran {name} S'ha executat {name}
@msg The script was stopped and its changes were undone L'script s'ha aturat i s'han desfet els seus canvis
@msg a script is running: stop it or wait for it to finish s'està executant un script: atureu-lo o espereu que acabi
@@ -6638,7 +6638,7 @@ liquify-list-end {0}, {1} {0} i {1}
@msg `args` is larger than 1 MiB `args` ocupa més d'1 MiB
@msg `path` is empty `path` és buit
@msg `installed` takes a `path`, not a `source` `installed` admet un `path`, no un `source`
@msg `path` must name a .js or .jsx file `path` ha d’indicar un fitxer .js o .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` ha d’indicar un fitxer .js, .mjs o .jsx
@msg give exactly one of `path` and `source` indiqueu exactament un de `path` i `source`
@msg Running a script S'està executant un script
@msg Copied the script report S’ha copiat l’informe de l’script
@@ -7906,6 +7906,7 @@ variable-list-end {0}, {1} {0} i {1}
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Instal·la «{name}», que demana aquests permisos?
ID: {id} ID: {id}
Manifest name: {name} Nom al manifest: {name}
Version: {version} Versió: {version}
Install “{name}” in place of the plug-in with the same ID? Instal·la «{name}» en lloc del complement amb el mateix ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Aquest fitxer no és el complement instal·lat abans amb aquest ID. Rep la configuració i la memòria cau desades per a aquest ID.
@@ -8019,6 +8020,11 @@ variable-list-end {0}, {1} {0} i {1}
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a «{name}» no se li ha concedit `{p}`, que la seva sortida necessita: no s’ha canviat res
@msg a heavy filter runs in the background, so it can't declare `commands` un filtre pesat s’executa en segon pla, de manera que no pot declarar `commands`
@msg at most {MAX_COMMANDS} `commands` com a màxim {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` dona com a màxim {MAX_LANGUAGES} idiomes
@msg {at} gives two options the same label {at} dona la mateixa etiqueta a dues opcions
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} no és un codi d’idioma com `de` o `pt-BR`, o en repeteix un de donat abans
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} ha de tenir 1-{max} caràcters imprimibles, sense caràcters de direcció ni separadors de línia
@msg {at} names or translates something the manifest doesn't declare {at} anomena o tradueix alguna cosa que el manifest no declara
@msg command {name} is declared twice l’ordre {name} està declarada dues vegades
@msg command {name}: `label` must be 1-64 printable characters ordre {name}: `label` ha de tenir 1-64 caràcters imprimibles
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ordre {name}: fes servir un id d’1-{MAX_COMMAND_ID} caràcters d’a-z 0-9 _ que comenci per una lletra
Can't render this file because it is too large.
+8 -2
View File
@@ -5273,7 +5273,7 @@ imageTrace Outline Obrys
Do not show this warning again Toto upozornění již nezobrazovat
Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu.
This script has added a great many objects. Continue, or stop it and undo what it did? Tento skript přidal velmi mnoho objektů. Pokračovat, nebo jej zastavit a vrátit jeho změny?
@msg Choose a .js or .jsx script Vyberte skript .js nebo .jsx
@msg Choose a .js, .mjs or .jsx script Vyberte skript .js, .mjs nebo .jsx
@msg Ran {name} Spuštěno: {name}
@msg The script was stopped and its changes were undone Skript byl zastaven a jeho změny byly vráceny
@msg a script is running: stop it or wait for it to finish běží skript: zastavte jej nebo počkejte na jeho dokončení
@@ -5420,7 +5420,7 @@ liquify-list-end {0}, {1} {0} a {1}
@msg `args` is larger than 1 MiB `args` je větší než 1 MiB
@msg `path` is empty `path` je prázdný
@msg `installed` takes a `path`, not a `source` `installed` přijímá `path`, ne `source`
@msg `path` must name a .js or .jsx file `path` musí označovat soubor .js nebo .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` musí označovat soubor .js, .mjs nebo .jsx
@msg give exactly one of `path` and `source` zadejte právě jedno z `path` a `source`
@msg Running a script Běží skript
@msg Copied the script report Zpráva o skriptu zkopírována
@@ -7517,6 +7517,7 @@ axis Y Axis osa Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Nainstalovat „{name}“, který žádá o tato oprávnění?
ID: {id} ID: {id}
Manifest name: {name} Název v manifestu: {name}
Version: {version} Verze: {version}
Install “{name}” in place of the plug-in with the same ID? Nainstalovat „{name}“ místo zásuvného modulu se stejným ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tento soubor není zásuvný modul dříve nainstalovaný s tímto ID. Získá nastavení a mezipaměť uchovávané pro toto ID.
@@ -7630,6 +7631,11 @@ axis Y Axis osa Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ nedostal `{p}`, které jeho výstup potřebuje: nic se nezměnilo
@msg a heavy filter runs in the background, so it can't declare `commands` těžký filtr běží na pozadí, takže nemůže deklarovat `commands`
@msg at most {MAX_COMMANDS} `commands` nejvýše {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` uvádí nejvýše {MAX_LANGUAGES} jazyků
@msg {at} gives two options the same label {at} dává dvěma možnostem stejný popisek
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} není kód jazyka jako `de` nebo `pt-BR`, nebo opakuje kód uvedený dříve
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} musí mít 1-{max} tisknutelných znaků, bez znaků směru textu a oddělovačů řádků
@msg {at} names or translates something the manifest doesn't declare {at} pojmenovává nebo překládá něco, co manifest nedeklaruje
@msg command {name} is declared twice příkaz {name} je deklarován dvakrát
@msg command {name}: `label` must be 1-64 printable characters příkaz {name}: `label` musí mít 1-64 tisknutelných znaků
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter příkaz {name}: použijte id o 1-{MAX_COMMAND_ID} znacích z a-z 0-9 _, které začíná písmenem
Can't render this file because it is too large.
+8 -2
View File
@@ -54,7 +54,7 @@
@msg it decompresses to more than {_1} MB den udpakkes til mere end {_1} MB
@msg its editing data is for a different page dens redigeringsdata er til en anden side
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` skal være "emBox", "capHeight", "xHeight" eller "icfBox"
@msg Choose a .js or .jsx script Vælg et .js- eller .jsx-script
@msg Choose a .js, .mjs or .jsx script Vælg et .js-, .mjs- eller .jsx-script
@msg Ran {name} Kørte {name}
@msg The script was stopped and its changes were undone Scriptet blev stoppet, og dets ændringer blev fortrudt
@msg a script is running: stop it or wait for it to finish et script kører: stop det, eller vent, til det er færdigt
@@ -245,7 +245,7 @@ liquify-list-end {0}, {1} {0} og {1}
@msg `args` is larger than 1 MiB `args` er større end 1 MiB
@msg `path` is empty `path` er tom
@msg `installed` takes a `path`, not a `source` `installed` tager en `path`, ikke en `source`
@msg `path` must name a .js or .jsx file `path` skal angive en .js- eller .jsx-fil
@msg `path` must name a .js, .mjs or .jsx file `path` skal angive en .js-, .mjs- eller .jsx-fil
@msg give exactly one of `path` and `source` angiv præcis én af `path` og `source`
@msg Running a script Kører et script
@msg Data Recovery can't keep copies in {path}: {e} Datagendannelse kan ikke opbevare kopier i {path}: {e}
@@ -797,6 +797,11 @@ liquify-list-end {0}, {1} {0} og {1}
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed »{name}« fik ikke tildelt `{p}`, som dets output kræver: intet blev ændret
@msg a heavy filter runs in the background, so it can't declare `commands` et tungt filter kører i baggrunden, så det kan ikke angive `commands`
@msg at most {MAX_COMMANDS} `commands` højst {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` angiver højst {MAX_LANGUAGES} sprog
@msg {at} gives two options the same label {at} giver to valgmuligheder samme etiket
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} er ikke en sprogkode som `de` eller `pt-BR`, eller gentager en, der er angivet før
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} skal være 1-{max} tegn, der kan udskrives, uden retnings- eller linjeskilletegn
@msg {at} names or translates something the manifest doesn't declare {at} navngiver eller oversætter noget, som manifestet ikke erklærer
@msg command {name} is declared twice kommandoen {name} er erklæret to gange
@msg command {name}: `label` must be 1-64 printable characters kommandoen {name}: `label` skal være 1-64 tegn, der kan udskrives
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommandoen {name}: brug et id på 1-{MAX_COMMAND_ID} tegn fra a-z 0-9 _, der starter med et bogstav
@@ -9745,6 +9750,7 @@ axis Y Axis Y-akse
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Installér »{name}«, som beder om disse rettigheder?
ID: {id} ID: {id}
Manifest name: {name} Navn i manifestet: {name}
Version: {version} Version: {version}
Install “{name}” in place of the plug-in with the same ID? Installér »{name}« i stedet for det plug-in, der har samme id?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Denne fil er ikke det plug-in, der før var installeret med dette id. Den får de indstillinger og den cache, der er gemt for dette id.
Can't render this file because it is too large.
+8 -2
View File
@@ -4859,7 +4859,7 @@ theme Appearance Erscheinungsbild
Do not show this warning again Diese Warnung nicht mehr anzeigen
Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut.
This script has added a great many objects. Continue, or stop it and undo what it did? Dieses Skript hat sehr viele Objekte hinzugefügt. Fortfahren oder das Skript stoppen und seine Änderungen rückgängig machen?
@msg Choose a .js or .jsx script Wählen Sie ein .js- oder .jsx-Skript
@msg Choose a .js, .mjs or .jsx script Wählen Sie ein .js-, .mjs- oder .jsx-Skript
@msg Ran {name} {name} ausgeführt
@msg The script was stopped and its changes were undone Das Skript wurde gestoppt und seine Änderungen wurden rückgängig gemacht
@msg a script is running: stop it or wait for it to finish ein Skript wird ausgeführt: stoppen Sie es oder warten Sie, bis es fertig ist
@@ -7098,6 +7098,7 @@ axis Y Axis Y-Achse
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? „{name}“ installieren, das diese Berechtigungen verlangt?
ID: {id} ID: {id}
Manifest name: {name} Name im Manifest: {name}
Version: {version} Version: {version}
Install “{name}” in place of the plug-in with the same ID? „{name}“ anstelle des Plug-ins mit derselben ID installieren?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Diese Datei ist nicht das Plug-in, das vorher mit dieser ID installiert war. Sie erhält die Einstellungen und den Cache, die für diese ID gespeichert sind.
@@ -7211,6 +7212,11 @@ axis Y Axis Y-Achse
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ wurde `{p}` nicht gewährt, das seine Ausgabe braucht: Es wurde nichts geändert
@msg a heavy filter runs in the background, so it can't declare `commands` ein schwerer Filter läuft im Hintergrund und kann daher keine `commands` deklarieren
@msg at most {MAX_COMMANDS} `commands` höchstens {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` gibt höchstens {MAX_LANGUAGES} Sprachen an
@msg {at} gives two options the same label {at} gibt zwei Optionen dieselbe Beschriftung
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} ist kein Sprachcode wie `de` oder `pt-BR` oder wiederholt einen zuvor angegebenen
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} muss 1-{max} druckbare Zeichen lang sein, ohne Schreibrichtungs- oder Zeilentrennzeichen
@msg {at} names or translates something the manifest doesn't declare {at} benennt oder übersetzt etwas, das das Manifest nicht deklariert
@msg command {name} is declared twice der Befehl {name} ist doppelt deklariert
@msg command {name}: `label` must be 1-64 printable characters Befehl {name}: `label` muss 1-64 druckbare Zeichen haben
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter Befehl {name}: Verwenden Sie eine ID aus 1-{MAX_COMMAND_ID} Zeichen aus a-z 0-9 _, die mit einem Buchstaben beginnt
@@ -8586,7 +8592,7 @@ breakText Glyphs Glyphen
@msg `args` is larger than 1 MiB `args` ist größer als 1 MiB
@msg `path` is empty `path` ist leer
@msg `installed` takes a `path`, not a `source` `installed` nimmt einen `path`, keine `source`
@msg `path` must name a .js or .jsx file `path` muss eine .js- oder .jsx-Datei angeben
@msg `path` must name a .js, .mjs or .jsx file `path` muss eine .js-, .mjs- oder .jsx-Datei angeben
@msg give exactly one of `path` and `source` geben Sie genau eines von `path` und `source` an
@msg `answers` must be a list of answers `answers` muss eine Liste von Antworten sein
@msg `artboard` must be the index of an artboard of the document `artboard` muss der Index einer Zeichenfläche des Dokuments sein
Can't render this file because it is too large.
+8 -2
View File
@@ -2656,7 +2656,7 @@ axis Both Και τα δύο
Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση
Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο.
This script has added a great many objects. Continue, or stop it and undo what it did? Αυτό το σενάριο πρόσθεσε πάρα πολλά αντικείμενα. Συνέχεια, ή διακοπή και αναίρεση όσων έκανε;
@msg Choose a .js or .jsx script Επιλέξτε ένα σενάριο .js ή .jsx
@msg Choose a .js, .mjs or .jsx script Επιλέξτε ένα σενάριο .js, .mjs ή .jsx
@msg Ran {name} Εκτελέστηκε: {name}
@msg The script was stopped and its changes were undone Το σενάριο διακόπηκε και οι αλλαγές του αναιρέθηκαν
@msg a script is running: stop it or wait for it to finish εκτελείται ένα σενάριο: διακόψτε το ή περιμένετε να τελειώσει
@@ -2829,7 +2829,7 @@ liquify-list-end {0}, {1} {0} και {1}
@msg `args` is larger than 1 MiB το `args` είναι μεγαλύτερο από 1 MiB
@msg `path` is empty το `path` είναι κενό
@msg `installed` takes a `path`, not a `source` το `installed` δέχεται `path`, όχι `source`
@msg `path` must name a .js or .jsx file το `path` πρέπει να ορίζει αρχείο .js ή .jsx
@msg `path` must name a .js, .mjs or .jsx file το `path` πρέπει να ορίζει αρχείο .js, .mjs ή .jsx
@msg give exactly one of `path` and `source` δώστε ακριβώς ένα από τα `path` και `source`
@msg Running a script Εκτελείται σενάριο
@msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε
@@ -7509,6 +7509,7 @@ axis Y Axis Άξονας Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Να εγκατασταθεί το «{name}», που ζητά αυτά τα δικαιώματα;
ID: {id} Αναγνωριστικό: {id}
Manifest name: {name} Όνομα στο manifest: {name}
Version: {version} Έκδοση: {version}
Install “{name}” in place of the plug-in with the same ID? Να εγκατασταθεί το «{name}» στη θέση του πρόσθετου με το ίδιο αναγνωριστικό;
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Αυτό το αρχείο δεν είναι το πρόσθετο που ήταν εγκατεστημένο πριν με αυτό το αναγνωριστικό. Παίρνει τις ρυθμίσεις και την κρυφή μνήμη που διατηρούνται για αυτό το αναγνωριστικό.
@@ -7622,6 +7623,11 @@ axis Y Axis Άξονας Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed στο «{name}» δεν παραχωρήθηκε το `{p}`, που χρειάζεται η έξοδός του: δεν άλλαξε τίποτα
@msg a heavy filter runs in the background, so it can't declare `commands` ένα βαρύ φίλτρο εκτελείται στο παρασκήνιο, οπότε δεν μπορεί να δηλώνει `commands`
@msg at most {MAX_COMMANDS} `commands` το πολύ {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages το `translations` δίνει το πολύ {MAX_LANGUAGES} γλώσσες
@msg {at} gives two options the same label το {at} δίνει την ίδια ετικέτα σε δύο επιλογές
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it το {at} δεν είναι κωδικός γλώσσας όπως `de` ή `pt-BR`, ή επαναλαμβάνει έναν που δόθηκε πριν
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters το {at} πρέπει να έχει 1-{max} εκτυπώσιμους χαρακτήρες, χωρίς χαρακτήρες κατεύθυνσης ή διαχωρισμού γραμμών
@msg {at} names or translates something the manifest doesn't declare το {at} ονομάζει ή μεταφράζει κάτι που το manifest δεν δηλώνει
@msg command {name} is declared twice η εντολή {name} δηλώνεται δύο φορές
@msg command {name}: `label` must be 1-64 printable characters εντολή {name}: το `label` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter εντολή {name}: χρησιμοποιήστε αναγνωριστικό 1-{MAX_COMMAND_ID} χαρακτήρων από a-z 0-9 _ που αρχίζει με γράμμα
Can't render this file because it is too large.
+8 -2
View File
@@ -4935,7 +4935,7 @@ axis Both Ambos
Do not show this warning again No volver a mostrar esta advertencia
Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir.
This script has added a great many objects. Continue, or stop it and undo what it did? Este script ha añadido muchísimos objetos. ¿Continuar, o detenerlo y deshacer lo que hizo?
@msg Choose a .js or .jsx script Elija un script .js o .jsx
@msg Choose a .js, .mjs or .jsx script Elija un script .js, .mjs o .jsx
@msg Ran {name} Se ejecutó {name}
@msg The script was stopped and its changes were undone El script se detuvo y sus cambios se deshicieron
@msg a script is running: stop it or wait for it to finish se está ejecutando un script: deténgalo o espere a que termine
@@ -5107,7 +5107,7 @@ liquify-list-end {0}, {1} {0}, {1}
@msg `args` is larger than 1 MiB `args` ocupa más de 1 MiB
@msg `path` is empty `path` está vacío
@msg `installed` takes a `path`, not a `source` `installed` admite un `path`, no un `source`
@msg `path` must name a .js or .jsx file `path` debe indicar un archivo .js o .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` debe indicar un archivo .js, .mjs o .jsx
@msg give exactly one of `path` and `source` indique exactamente uno de `path` y `source`
@msg Running a script Ejecutando un script
@msg Copied the script report Se copió el informe del script
@@ -7495,6 +7495,7 @@ axis Y Axis Eje Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? ¿Instalar “{name}”, que pide estos permisos?
ID: {id} ID: {id}
Manifest name: {name} Nombre en el manifiesto: {name}
Version: {version} Versión: {version}
Install “{name}” in place of the plug-in with the same ID? ¿Instalar “{name}” en lugar del plugin con el mismo ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este archivo no es el plugin instalado antes con este ID. Recibe la configuración y la caché guardadas para ese ID.
@@ -7608,6 +7609,11 @@ axis Y Axis Eje Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” no se le concedió `{p}`, que su resultado necesita: no se cambió nada
@msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesado se ejecuta en segundo plano, así que no puede declarar `commands`
@msg at most {MAX_COMMANDS} `commands` como máximo {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` da como máximo {MAX_LANGUAGES} idiomas
@msg {at} gives two options the same label {at} da la misma etiqueta a dos opciones
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} no es un código de idioma como `de` o `pt-BR`, o repite uno dado antes
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} debe tener 1-{max} caracteres imprimibles, sin caracteres de dirección ni separadores de línea
@msg {at} names or translates something the manifest doesn't declare {at} nombra o traduce algo que el manifiesto no declara
@msg command {name} is declared twice el comando {name} está declarado dos veces
@msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` debe tener 1-64 caracteres imprimibles
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que empiece por una letra
Can't render this file because it is too large.
+8 -2
View File
@@ -5178,7 +5178,7 @@ imageTrace Outline Ääriviiva
Do not show this warning again Älä näytä tätä varoitusta uudelleen
Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen.
This script has added a great many objects. Continue, or stop it and undo what it did? Tämä komentosarja on lisännyt hyvin paljon objekteja. Jatketaanko, vai pysäytetäänkö se ja kumotaan sen muutokset?
@msg Choose a .js or .jsx script Valitse .js- tai .jsx-komentosarja
@msg Choose a .js, .mjs or .jsx script Valitse .js-, .mjs- tai .jsx-komentosarja
@msg Ran {name} Suoritettu: {name}
@msg The script was stopped and its changes were undone Komentosarja pysäytettiin ja sen muutokset kumottiin
@msg a script is running: stop it or wait for it to finish komentosarja on käynnissä: pysäytä se tai odota sen valmistumista
@@ -5350,7 +5350,7 @@ liquify-list-end {0}, {1} {0} ja {1}
@msg `args` is larger than 1 MiB `args` on suurempi kuin 1 MiB
@msg `path` is empty `path` on tyhjä
@msg `installed` takes a `path`, not a `source` `installed` ottaa `path`-arvon, ei `source`-arvoa
@msg `path` must name a .js or .jsx file `path` on oltava .js- tai .jsx-tiedosto
@msg `path` must name a .js, .mjs or .jsx file `path` on oltava .js-, .mjs- tai .jsx-tiedosto
@msg give exactly one of `path` and `source` anna tasan yksi arvoista `path` ja `source`
@msg Running a script Suoritetaan komentosarjaa
@msg Copied the script report Komentosarjan raportti kopioitiin
@@ -7586,6 +7586,7 @@ axis Y Axis Y-akseli
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Asennetaanko ”{name}”, joka pyytää näitä käyttöoikeuksia?
ID: {id} Tunnus: {id}
Manifest name: {name} Nimi manifestissa: {name}
Version: {version} Versio: {version}
Install “{name}” in place of the plug-in with the same ID? Asennetaanko ”{name}” samaa tunnusta käyttävän laajennuksen tilalle?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tämä tiedosto ei ole laajennus, joka oli aiemmin asennettu tällä tunnuksella. Se saa tälle tunnukselle säilytetyt asetukset ja välimuistin.
@@ -7699,6 +7700,11 @@ axis Y Axis Y-akseli
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” ei saanut käyttöoikeutta `{p}`, jota sen tulos tarvitsee: mitään ei muutettu
@msg a heavy filter runs in the background, so it can't declare `commands` raskas suodin suoritetaan taustalla, joten se ei voi määritellä `commands`-kohtaa
@msg at most {MAX_COMMANDS} `commands` enintään {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` antaa enintään {MAX_LANGUAGES} kieltä
@msg {at} gives two options the same label {at} antaa kahdelle vaihtoehdolle saman nimen
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} ei ole kielikoodi kuten `de` tai `pt-BR`, tai toistaa aiemmin annetun koodin
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} saa olla 1-{max} tulostettavaa merkkiä ilman suunta- tai rivinerotinmerkkejä
@msg {at} names or translates something the manifest doesn't declare {at} nimeää tai kääntää jotain, mitä manifesti ei määrittele
@msg command {name} is declared twice komento {name} on määritelty kahdesti
@msg command {name}: `label` must be 1-64 printable characters komento {name}: `label`-kentässä on oltava 1-64 tulostettavaa merkkiä
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter komento {name}: käytä 1-{MAX_COMMAND_ID} merkin tunnusta merkeistä a-z 0-9 _, joka alkaa kirjaimella
Can't render this file because it is too large.
+8 -2
View File
@@ -4917,7 +4917,7 @@ axis Both Les deux
Do not show this warning again Ne plus afficher cet avertissement
Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau.
This script has added a great many objects. Continue, or stop it and undo what it did? Ce script a ajouté un très grand nombre d’objets. Continuer, ou l’arrêter et annuler ce qu’il a fait ?
@msg Choose a .js or .jsx script Choisissez un script .js ou .jsx
@msg Choose a .js, .mjs or .jsx script Choisissez un script .js, .mjs ou .jsx
@msg Ran {name} {name} exécuté
@msg The script was stopped and its changes were undone Le script a été arrêté et ses modifications ont été annulées
@msg a script is running: stop it or wait for it to finish un script est en cours d’exécution : arrêtez-le ou attendez qu’il se termine
@@ -5063,7 +5063,7 @@ liquify-list-end {0}, {1} {0} et {1}
@msg `args` is larger than 1 MiB `args` dépasse 1 Mio
@msg `path` is empty `path` est vide
@msg `installed` takes a `path`, not a `source` `installed` prend un `path`, pas un `source`
@msg `path` must name a .js or .jsx file `path` doit désigner un fichier .js ou .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` doit désigner un fichier .js, .mjs ou .jsx
@msg give exactly one of `path` and `source` indiquez exactement un paramètre parmi `path` et `source`
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l’application, la personne répond à chaque boîte de dialogue
@msg Running a script Exécution d’un script
@@ -7513,6 +7513,7 @@ axis Y Axis Axe Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Installer « {name} », qui demande ces autorisations ?
ID: {id} ID : {id}
Manifest name: {name} Le manifeste le nomme {name}
Version: {version} Version : {version}
Install “{name}” in place of the plug-in with the same ID? Installer « {name} » à la place du module externe qui a le même ID ?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ce fichier n’est pas le module externe installé auparavant avec cet ID. Il reçoit les réglages et le cache conservés pour cet ID.
@@ -7626,6 +7627,11 @@ axis Y Axis Axe Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed « {name} » n’a pas reçu `{p}`, dont sa sortie a besoin : rien n’a été modifié
@msg a heavy filter runs in the background, so it can't declare `commands` un filtre lourd s’exécute en arrière-plan, il ne peut donc pas déclarer `commands`
@msg at most {MAX_COMMANDS} `commands` au plus {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` donne au plus {MAX_LANGUAGES} langues
@msg {at} gives two options the same label {at} donne le même libellé à deux options
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} n’est pas un code de langue comme `de` ou `pt-BR`, ou répète un code donné avant
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} doit compter 1-{max} caractères imprimables, sans caractères de direction ni séparateurs de ligne
@msg {at} names or translates something the manifest doesn't declare {at} nomme ou traduit quelque chose que le manifeste ne déclare pas
@msg command {name} is declared twice la commande {name} est déclarée deux fois
@msg command {name}: `label` must be 1-64 printable characters commande {name} : `label` doit compter 1-64 caractères imprimables
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter commande {name} : utilisez un id de 1-{MAX_COMMAND_ID} caractères parmi a-z 0-9 _ commençant par une lettre
Can't render this file because it is too large.
+1
View File
@@ -1891,6 +1891,7 @@
Max Ascender મહત્તમ એસેન્ડર
ICF Top/Right ICF ઉપર/જમણે
ID: {id} ID: {id}
Manifest name: {name} મેનિફેસ્ટમાં નામ: {name}
Identify Objects By ઑબ્જેક્ટ્સ આ રીતે ઓળખો
If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. જો ડ્રોઇંગ ટેબ્લેટની પેન દોરતી ન હોય, તો X11 (XWayland) વિકલ્પ પસંદ કરો.
Ignore અવગણો
Can't render this file because it contains an unexpected character in line 72 and column 5.
+8 -2
View File
@@ -6670,6 +6670,7 @@ arrowhead Feather पंख
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? "{name}" स्थापित करें, जो ये अनुमतियां मांगता है?
ID: {id} ID: {id}
Manifest name: {name} मैनिफ़ेस्ट में नाम: {name}
Version: {version} संस्करण: {version}
Install “{name}” in place of the plug-in with the same ID? समान ID वाले प्लग-इन की जगह “{name}” इंस्टॉल करें?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. यह फ़ाइल इस ID के साथ पहले इंस्टॉल किया गया प्लग-इन नहीं है। इसे उस ID के लिए रखी गई सेटिंग्स और कैश मिलते हैं।
@@ -6764,6 +6765,11 @@ arrowhead Feather पंख
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” को `{p}` नहीं दी गई, जो उसके आउटपुट को चाहिए: कुछ नहीं बदला
@msg a heavy filter runs in the background, so it can't declare `commands` भारी फ़िल्टर पृष्ठभूमि में चलता है, इसलिए वह `commands` घोषित नहीं कर सकता
@msg at most {MAX_COMMANDS} `commands` अधिकतम {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` अधिकतम {MAX_LANGUAGES} भाषाएँ देता है
@msg {at} gives two options the same label {at} दो विकल्पों को एक ही लेबल देता है
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} `de` या `pt-BR` जैसा भाषा कोड नहीं है, या पहले दिए गए कोड को दोहराता है
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} में 1-{max} मुद्रण योग्य वर्ण होने चाहिए, दिशा या पंक्ति-विभाजक वर्णों के बिना
@msg {at} names or translates something the manifest doesn't declare {at} ऐसी चीज़ का नाम लेता है या अनुवाद करता है जिसे मैनिफ़ेस्ट घोषित नहीं करता
@msg command {name} is declared twice कमांड {name} दो बार घोषित है
@msg command {name}: `label` must be 1-64 printable characters कमांड {name}: `label` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter कमांड {name}: a-z 0-9 _ के 1-{MAX_COMMAND_ID} वर्णों वाली ऐसी id इस्तेमाल करें जो अक्षर से शुरू हो
@@ -7668,7 +7674,7 @@ arrowhead Feather पंख
Do not show this warning again यह चेतावनी फिर न दिखाएँ
Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें।
This script has added a great many objects. Continue, or stop it and undo what it did? इस स्क्रिप्ट ने बहुत सारे ऑब्जेक्ट जोड़े हैं। जारी रखें, या इसे रोककर इसके बदलाव पूर्ववत करें?
@msg Choose a .js or .jsx script .js या .jsx स्क्रिप्ट चुनें
@msg Choose a .js, .mjs or .jsx script .js, .mjs या .jsx स्क्रिप्ट चुनें
@msg Ran {name} {name} चलाई गई
@msg The script was stopped and its changes were undone स्क्रिप्ट रोकी गई और उसके बदलाव पूर्ववत किए गए
@msg a script is running: stop it or wait for it to finish एक स्क्रिप्ट चल रही है: उसे रोकें या पूरा होने की प्रतीक्षा करें
@@ -7841,7 +7847,7 @@ liquify-list-end {0}, {1} {0} और {1}
@msg `args` is larger than 1 MiB `args` 1 MiB से बड़ा है
@msg `path` is empty `path` खाली है
@msg `installed` takes a `path`, not a `source` `installed` एक `path` लेता है, `source` नहीं
@msg `path` must name a .js or .jsx file `path` में किसी .js या .jsx फ़ाइल का नाम होना चाहिए
@msg `path` must name a .js, .mjs or .jsx file `path` में किसी .js, .mjs या .jsx फ़ाइल का नाम होना चाहिए
@msg give exactly one of `path` and `source` `path` और `source` में से ठीक एक दें
@msg Running a script स्क्रिप्ट चल रही है
@msg Copied the script report Copied स्क्रिप्ट रिपोर्ट
Can't render this file because it is too large.
+8 -2
View File
@@ -5794,7 +5794,7 @@ imageTrace Outline Körvonal
Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés
Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra.
This script has added a great many objects. Continue, or stop it and undo what it did? Ez a parancsfájl nagyon sok objektumot adott hozzá. Folytatja, vagy leállítja és visszavonja a módosításait?
@msg Choose a .js or .jsx script Válasszon .js vagy .jsx parancsfájlt
@msg Choose a .js, .mjs or .jsx script Válasszon .js, .mjs vagy .jsx parancsfájlt
@msg Ran {name} Lefutott: {name}
@msg The script was stopped and its changes were undone A parancsfájl leállt, a módosításai visszavonva
@msg a script is running: stop it or wait for it to finish egy parancsfájl fut: állítsa le, vagy várja meg, hogy befejeződjön
@@ -5942,7 +5942,7 @@ liquify-list-end {0}, {1} {0} és {1}
@msg `args` is larger than 1 MiB `args`: nagyobb 1 MiB-nál
@msg `path` is empty a `path` üres
@msg `installed` takes a `path`, not a `source` az `installed` `path` értéket vár, nem `source` értéket
@msg `path` must name a .js or .jsx file a `path` értékének .js vagy .jsx fájlt kell megadnia
@msg `path` must name a .js, .mjs or .jsx file a `path` értékének .js, .mjs vagy .jsx fájlt kell megadnia
@msg give exactly one of `path` and `source` pontosan egyet adj meg ezek közül: `path`, `source`
@msg Running a script Parancsfájl futtatása
@msg Copied the script report Szkriptjelentés másolva
@@ -7502,6 +7502,7 @@ axis Y Axis Y tengely
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Telepíted a(z) „{name}” bővítményt, amely ezeket az engedélyeket kéri?
ID: {id} Azonosító: {id}
Manifest name: {name} Név a manifestben: {name}
Version: {version} Verzió: {version}
Install “{name}” in place of the plug-in with the same ID? Telepíted a(z) „{name}” bővítményt az azonos azonosítójú bővítmény helyére?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ez a fájl nem az a bővítmény, amely korábban ezzel az azonosítóval volt telepítve. Megkapja az ehhez az azonosítóhoz tárolt beállításokat és gyorsítótárat.
@@ -7615,6 +7616,11 @@ axis Y Axis Y tengely
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a(z) „{name}” nem kapta meg a(z) `{p}` engedélyt, amelyre a kimenetének szüksége van: semmi sem változott
@msg a heavy filter runs in the background, so it can't declare `commands` a nehéz szűrő a háttérben fut, ezért nem deklarálhat `commands` értéket
@msg at most {MAX_COMMANDS} `commands` legfeljebb {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages a `translations` legfeljebb {MAX_LANGUAGES} nyelvet adhat meg
@msg {at} gives two options the same label {at} két lehetőségnek ugyanazt a címkét adja
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} nem olyan nyelvkód, mint a `de` vagy a `pt-BR`, vagy egy korábban megadottat ismétel
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 1-{max} nyomtatható karakter lehet, irány- és sorelválasztó karakterek nélkül
@msg {at} names or translates something the manifest doesn't declare {at} olyasmit nevez meg vagy fordít, amit a manifest nem deklarál
@msg command {name} is declared twice a(z) {name} parancs kétszer van deklarálva
@msg command {name}: `label` must be 1-64 printable characters {name} parancs: a `label` 1-64 nyomtatható karakter legyen
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} parancs: használj 1-{MAX_COMMAND_ID} karakteres, a-z 0-9 _ karakterekből álló, betűvel kezdődő azonosítót
Can't render this file because it is too large.
+8 -2
View File
@@ -54,7 +54,7 @@
@msg it decompresses to more than {_1} MB hasil dekompresinya lebih dari {_1} MB
@msg its editing data is for a different page data penyuntingannya untuk halaman lain
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` harus "emBox", "capHeight", "xHeight" atau "icfBox"
@msg Choose a .js or .jsx script Pilih skrip .js atau .jsx
@msg Choose a .js, .mjs or .jsx script Pilih skrip .js, .mjs, atau .jsx
@msg Ran {name} {name} dijalankan
@msg The script was stopped and its changes were undone Skrip dihentikan dan perubahannya dibatalkan
@msg a script is running: stop it or wait for it to finish skrip sedang berjalan: hentikan atau tunggu hingga selesai
@@ -151,7 +151,7 @@
@msg `args` is larger than 1 MiB `args` lebih besar dari 1 MiB
@msg `path` is empty `path` kosong
@msg `installed` takes a `path`, not a `source` `installed` menerima `path`, bukan `source`
@msg `path` must name a .js or .jsx file `path` harus menyebut file .js atau .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` harus menyebut file .js, .mjs, atau .jsx
@msg give exactly one of `path` and `source` berikan tepat satu dari `path` dan `source`
@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why}
@msg `answers[{i}]` {e} `answers[{i}]` {e}
@@ -678,6 +678,11 @@
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” tidak diberi `{p}`, yang diperlukan keluarannya: tidak ada yang diubah
@msg a heavy filter runs in the background, so it can't declare `commands` filter berat berjalan di latar belakang, sehingga tidak dapat mendeklarasikan `commands`
@msg at most {MAX_COMMANDS} `commands` paling banyak {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` memberikan paling banyak {MAX_LANGUAGES} bahasa
@msg {at} gives two options the same label {at} memberikan label yang sama untuk dua opsi
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} bukan kode bahasa seperti `de` atau `pt-BR`, atau mengulang kode yang diberikan sebelumnya
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} harus berisi 1-{max} karakter yang dapat dicetak, tanpa karakter arah atau pemisah baris
@msg {at} names or translates something the manifest doesn't declare {at} menamai atau menerjemahkan sesuatu yang tidak dideklarasikan manifes
@msg command {name} is declared twice perintah {name} dideklarasikan dua kali
@msg command {name}: `label` must be 1-64 printable characters perintah {name}: `label` harus berupa 1-64 karakter yang dapat dicetak
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter perintah {name}: gunakan id sepanjang 1-{MAX_COMMAND_ID} karakter dari a-z 0-9 _ yang diawali huruf
@@ -7527,6 +7532,7 @@ axis Y Axis Sumbu Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Instal “{name}”, yang meminta izin berikut?
ID: {id} ID: {id}
Manifest name: {name} Nama di manifes: {name}
Version: {version} Versi: {version}
Install “{name}” in place of the plug-in with the same ID? Instal “{name}” sebagai pengganti plug-in dengan ID yang sama?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. File ini bukan plug-in yang sebelumnya diinstal dengan ID ini. File ini mendapatkan pengaturan dan cache yang disimpan untuk ID tersebut.
Can't render this file because it is too large.
+8 -2
View File
@@ -4997,7 +4997,7 @@ axis Both Entrambi
Do not show this warning again Non mostrare più questo avviso
Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo.
This script has added a great many objects. Continue, or stop it and undo what it did? Questo script ha aggiunto moltissimi oggetti. Continuare, oppure interromperlo e annullare ciò che ha fatto?
@msg Choose a .js or .jsx script Scegli uno script .js o .jsx
@msg Choose a .js, .mjs or .jsx script Scegli uno script .js, .mjs o .jsx
@msg Ran {name} {name} eseguito
@msg The script was stopped and its changes were undone Lo script è stato interrotto e le sue modifiche sono state annullate
@msg a script is running: stop it or wait for it to finish è in esecuzione uno script: interrompilo o attendi che finisca
@@ -7137,6 +7137,7 @@ axis Y Axis Asse Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Installare “{name}”, che chiede queste autorizzazioni?
ID: {id} ID: {id}
Manifest name: {name} Nome nel manifest: {name}
Version: {version} Versione: {version}
Install “{name}” in place of the plug-in with the same ID? Installare “{name}” al posto del plug-in con lo stesso ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Questo file non è il plug-in installato prima con questo ID. Riceve le impostazioni e la cache conservate per quell’ID.
@@ -7250,6 +7251,11 @@ axis Y Axis Asse Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” non è stata concessa `{p}`, che serve al suo risultato: non è stato modificato nulla
@msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesante viene eseguito in background, quindi non può dichiarare `commands`
@msg at most {MAX_COMMANDS} `commands` al massimo {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` indica al massimo {MAX_LANGUAGES} lingue
@msg {at} gives two options the same label {at} dà la stessa etichetta a due opzioni
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} non è un codice di lingua come `de` o `pt-BR`, o ripete uno indicato prima
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} deve avere 1-{max} caratteri stampabili, senza caratteri di direzione o separatori di riga
@msg {at} names or translates something the manifest doesn't declare {at} nomina o traduce qualcosa che il manifest non dichiara
@msg command {name} is declared twice il comando {name} è dichiarato due volte
@msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve avere 1-64 caratteri stampabili
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id di 1-{MAX_COMMAND_ID} caratteri tra a-z 0-9 _ che inizi con una lettera
@@ -8627,7 +8633,7 @@ breakText Glyphs Glifi
@msg `args` is larger than 1 MiB `args` supera 1 MiB
@msg `path` is empty `path` è vuoto
@msg `installed` takes a `path`, not a `source` `installed` accetta un `path`, non un `source`
@msg `path` must name a .js or .jsx file `path` deve indicare un file .js o .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` deve indicare un file .js, .mjs o .jsx
@msg give exactly one of `path` and `source` indica esattamente uno tra `path` e `source`
@msg `answers` must be a list of answers `answers` deve essere un elenco di risposte
@msg `artboard` must be the index of an artboard of the document `artboard` deve essere l'indice di una tavola da disegno del documento
Can't render this file because it is too large.
+8 -2
View File
@@ -5824,7 +5824,7 @@ variable-list-end {0}, {1} {0}、{1}
Do not show this warning again 今後この警告を表示しない
Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。
This script has added a great many objects. Continue, or stop it and undo what it did? このスクリプトは非常に多くのオブジェクトを追加しました。続行しますか、それとも停止して変更を取り消しますか?
@msg Choose a .js or .jsx script .js または .jsx スクリプトを選択してください
@msg Choose a .js, .mjs or .jsx script .js、.mjs または .jsx スクリプトを選択してください
@msg Ran {name} {name} を実行しました
@msg The script was stopped and its changes were undone スクリプトを停止し、変更を取り消しました
@msg a script is running: stop it or wait for it to finish スクリプトの実行中です: 停止するか、終了するまでお待ちください
@@ -5971,7 +5971,7 @@ liquify-list-end {0}, {1} {0}、{1}
@msg `args` is larger than 1 MiB `args` が 1 MiB を超えています
@msg `path` is empty `path` が空です
@msg `installed` takes a `path`, not a `source` `installed` には `source` ではなく `path` を指定してください
@msg `path` must name a .js or .jsx file `path` には .js または .jsx ファイルを指定してください
@msg `path` must name a .js, .mjs or .jsx file `path` には .js、.mjs または .jsx ファイルを指定してください
@msg give exactly one of `path` and `source` `path` と `source` のうち 1 つだけを指定してください
@msg Running a script スクリプトを実行中
@msg Copied the script report スクリプトのレポートをコピーしました
@@ -7212,6 +7212,7 @@ axis Y Axis Y 軸
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? これらの権限を求める「{name}」をインストールしますか?
ID: {id} ID: {id}
Manifest name: {name} マニフェストの名前: {name}
Version: {version} バージョン: {version}
Install “{name}” in place of the plug-in with the same ID? 同じ ID のプラグインの代わりに「{name}」をインストールしますか?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. このファイルは、以前にこの ID でインストールされていたプラグインではありません。この ID 用に保持されている設定とキャッシュを引き継ぎます。
@@ -7325,6 +7326,11 @@ axis Y Axis Y 軸
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」には出力に必要な `{p}` が付与されていません。何も変更されませんでした
@msg a heavy filter runs in the background, so it can't declare `commands` 重いフィルターはバックグラウンドで実行されるため、`commands` を宣言できません
@msg at most {MAX_COMMANDS} `commands` `commands` は最大 {MAX_COMMANDS} 個です
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` に指定できる言語は最大 {MAX_LANGUAGES} 個です
@msg {at} gives two options the same label {at} で 2 つの選択肢に同じラベルが付いています
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} は `de` や `pt-BR` のような言語コードではないか、前に指定したコードの繰り返しです
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} は方向制御文字や行区切り文字を含まない 1-{max} 文字の印字可能な文字にしてください
@msg {at} names or translates something the manifest doesn't declare {at} はマニフェストで宣言されていないものを指定または翻訳しています
@msg command {name} is declared twice コマンド {name} が 2 回宣言されています
@msg command {name}: `label` must be 1-64 printable characters コマンド {name}: `label` は印刷可能な 1-64 文字にしてください
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter コマンド {name}: a-z 0-9 _ からなり英字で始まる 1-{MAX_COMMAND_ID} 文字の ID を使用してください
Can't render this file because it is too large.
+8 -2
View File
@@ -2140,7 +2140,7 @@
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` უნდა იყოს მთელი რიცხვი 1-დან {_1}-მდე
@msg `max` must be 1 to {MAX_WORDS} `max` უნდა იყოს 1-დან {MAX_WORDS}-მდე
@msg `path` is empty `path` ცარიელია
@msg `path` must name a .js or .jsx file `path` უნდა მიუთითებდეს .js ან .jsx ფაილს
@msg `path` must name a .js, .mjs or .jsx file `path` უნდა მიუთითებდეს .js, .mjs ან .jsx ფაილს
@msg `reference` must be a whole number from 0 to 8 `reference` უნდა იყოს მთელი რიცხვი 0-დან 8-მდე
@msg `ringSeed` must be below 2^53, not {r} `ringSeed` უნდა იყოს 2^53-ზე ნაკლები და არა {r}
@msg `source` is the only path, line or label that graph group `target` stands for `source` ერთადერთი ტრაექტორია, ხაზი ან წარწერაა, რომელსაც დიაგრამის ჯგუფი `target` წარმოადგენს
@@ -8505,7 +8505,7 @@ imageTrace Outline კონტური
Do not show this warning again აღარ აჩვენო ეს გაფრთხილება
Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით.
This script has added a great many objects. Continue, or stop it and undo what it did? ამ სკრიპტმა ძალიან ბევრი ობიექტი დაამატა. გაგრძელდეს, თუ შეჩერდეს და გაუქმდეს მისი ცვლილებები?
@msg Choose a .js or .jsx script აირჩიეთ .js ან .jsx სკრიპტი
@msg Choose a .js, .mjs or .jsx script აირჩიეთ .js, .mjs ან .jsx სკრიპტი
@msg Ran {name} გაშვებულია: {name}
@msg The script was stopped and its changes were undone სკრიპტი შეჩერდა და მისი ცვლილებები გაუქმდა
@msg a script is running: stop it or wait for it to finish სკრიპტი მუშაობს: შეაჩერეთ ან დაელოდეთ დასრულებას
@@ -9624,6 +9624,7 @@ axis Y Axis Y ღერძი
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? დავაყენოთ „{name}“, რომელიც ამ ნებართვებს ითხოვს?
ID: {id} ID: {id}
Manifest name: {name} სახელი მანიფესტში: {name}
Version: {version} ვერსია: {version}
Install “{name}” in place of the plug-in with the same ID? დავაყენოთ „{name}“ იმავე ID-ის მქონე პლაგინის ნაცვლად?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. ეს ფაილი არ არის ამ ID-ით ადრე დაყენებული პლაგინი. ის მიიღებს ამ ID-სთვის შენახულ პარამეტრებს და ქეშს.
@@ -9737,6 +9738,11 @@ axis Y Axis Y ღერძი
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“-ს არ მიეცა `{p}`, რომელიც მის შედეგს სჭირდება: არაფერი შეცვლილა
@msg a heavy filter runs in the background, so it can't declare `commands` მძიმე ფილტრი ფონურ რეჟიმში მუშაობს, ამიტომ მას არ შეუძლია `commands`-ის გამოცხადება
@msg at most {MAX_COMMANDS} `commands` მაქსიმუმ {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` იძლევა მაქსიმუმ {MAX_LANGUAGES} ენას
@msg {at} gives two options the same label {at} ორ ვარიანტს ერთსა და იმავე წარწერას აძლევს
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} არ არის ენის კოდი, როგორიცაა `de` ან `pt-BR`, ან იმეორებს ადრე მოცემულ კოდს
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} უნდა იყოს 1-{max} დასაბეჭდი სიმბოლო, მიმართულების და ხაზის გამყოფი სიმბოლოების გარეშე
@msg {at} names or translates something the manifest doesn't declare {at} ასახელებს ან თარგმნის რაღაცას, რასაც მანიფესტი არ აცხადებს
@msg command {name} is declared twice ბრძანება {name} ორჯერაა გამოცხადებული
@msg command {name}: `label` must be 1-64 printable characters ბრძანება {name}: `label` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ბრძანება {name}: გამოიყენეთ 1-{MAX_COMMAND_ID} სიმბოლოიანი id a-z 0-9 _ სიმბოლოებიდან, რომელიც ასოთი იწყება
Can't render this file because it is too large.
+8 -2
View File
@@ -5753,7 +5753,7 @@ variable-list-end {0}, {1} {0} 및 {1}
Do not show this warning again 이 경고를 다시 표시하지 않음
Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요.
This script has added a great many objects. Continue, or stop it and undo what it did? 이 스크립트가 매우 많은 개체를 추가했습니다. 계속할까요, 아니면 중지하고 변경 내용을 취소할까요?
@msg Choose a .js or .jsx script .js 또는 .jsx 스크립트를 선택하세요
@msg Choose a .js, .mjs or .jsx script .js, .mjs 또는 .jsx 스크립트를 선택하세요
@msg Ran {name} {name} 실행됨
@msg The script was stopped and its changes were undone 스크립트를 중지하고 변경 내용을 취소했습니다
@msg a script is running: stop it or wait for it to finish 스크립트 실행 중: 중지하거나 끝날 때까지 기다리세요
@@ -5900,7 +5900,7 @@ liquify-list-end {0}, {1} {0} 및 {1}
@msg `args` is larger than 1 MiB `args`이(가) 1 MiB보다 큽니다
@msg `path` is empty `path`이(가) 비어 있습니다
@msg `installed` takes a `path`, not a `source` `installed`에는 `source`가 아니라 `path`를 지정하세요
@msg `path` must name a .js or .jsx file `path`은(는) .js 또는 .jsx 파일을 가리켜야 합니다
@msg `path` must name a .js, .mjs or .jsx file `path`은(는) .js, .mjs 또는 .jsx 파일을 가리켜야 합니다
@msg give exactly one of `path` and `source` `path`, `source` 중 정확히 하나를 지정하세요
@msg Running a script 스크립트 실행 중
@msg Copied the script report 스크립트 보고서를 복사했습니다
@@ -7109,6 +7109,7 @@ axis Y Axis Y축
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? 이 권한을 요청하는 “{name}”을(를) 설치하시겠습니까?
ID: {id} ID: {id}
Manifest name: {name} 매니페스트의 이름: {name}
Version: {version} 버전: {version}
Install “{name}” in place of the plug-in with the same ID? 같은 ID의 플러그인 대신 “{name}”을(를) 설치하시겠습니까?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 이 파일은 이전에 이 ID로 설치된 플러그인이 아닙니다. 이 ID에 보관된 설정과 캐시를 받습니다.
@@ -7222,6 +7223,11 @@ axis Y Axis Y축
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”에 출력에 필요한 `{p}` 권한이 부여되지 않았습니다. 아무것도 변경되지 않았습니다
@msg a heavy filter runs in the background, so it can't declare `commands` 무거운 필터는 백그라운드에서 실행되므로 `commands`를 선언할 수 없습니다
@msg at most {MAX_COMMANDS} `commands` `commands`는 최대 {MAX_COMMANDS}개입니다
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations`에는 언어를 최대 {MAX_LANGUAGES}개까지 지정할 수 있습니다
@msg {at} gives two options the same label {at}에서 두 옵션에 같은 레이블을 지정했습니다
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at}은(는) `de`나 `pt-BR` 같은 언어 코드가 아니거나 앞에서 지정한 코드를 반복합니다
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at}은(는) 방향 문자나 줄 구분 문자 없이 인쇄 가능한 문자 1-{max}자여야 합니다
@msg {at} names or translates something the manifest doesn't declare {at}은(는) 매니페스트가 선언하지 않은 항목을 지정하거나 번역합니다
@msg command {name} is declared twice 명령 {name}이(가) 두 번 선언되었습니다
@msg command {name}: `label` must be 1-64 printable characters 명령 {name}: `label`은 인쇄 가능한 문자 1-64자여야 합니다
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 명령 {name}: a-z 0-9 _로 이루어지고 문자로 시작하는 1-{MAX_COMMAND_ID}자 ID를 사용하세요
Can't render this file because it is too large.
+8 -2
View File
@@ -54,7 +54,7 @@
@msg it decompresses to more than {_1} MB gedecomprimeerd is het groter dan {_1} MB
@msg its editing data is for a different page zijn bewerkingsgegevens horen bij een andere pagina
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` moet "emBox", "capHeight", "xHeight" of "icfBox" zijn
@msg Choose a .js or .jsx script Kies een .js- of .jsx-script
@msg Choose a .js, .mjs or .jsx script Kies een .js-, .mjs- of .jsx-script
@msg Ran {name} {name} uitgevoerd
@msg The script was stopped and its changes were undone Het script is gestopt en de wijzigingen ervan zijn ongedaan gemaakt
@msg a script is running: stop it or wait for it to finish er wordt een script uitgevoerd: stop het of wacht tot het klaar is
@@ -221,7 +221,7 @@ liquify-list-end {0}, {1} {0} en {1}
@msg `args` is larger than 1 MiB `args` is groter dan 1 MiB
@msg `path` is empty `path` is leeg
@msg `installed` takes a `path`, not a `source` `installed` neemt een `path`, geen `source`
@msg `path` must name a .js or .jsx file `path` moet een .js- of .jsx-bestand aanwijzen
@msg `path` must name a .js, .mjs or .jsx file `path` moet een .js-, .mjs- of .jsx-bestand aanwijzen
@msg give exactly one of `path` and `source` geef precies een van `path` en `source`
@msg Running a script Er wordt een script uitgevoerd
@msg Data Recovery can't keep copies in {path}: {e} Gegevensherstel kan geen kopieën bewaren in {path}: {e}
@@ -640,6 +640,11 @@ liquify-list-end {0}, {1} {0} en {1}
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” heeft `{p}` niet gekregen, wat de uitvoer ervan nodig heeft: er is niets gewijzigd
@msg a heavy filter runs in the background, so it can't declare `commands` een zwaar filter wordt op de achtergrond uitgevoerd, dus kan het geen `commands` declareren
@msg at most {MAX_COMMANDS} `commands` maximaal {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` geeft maximaal {MAX_LANGUAGES} talen
@msg {at} gives two options the same label {at} geeft twee opties hetzelfde label
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} is geen taalcode zoals `de` of `pt-BR`, of herhaalt een eerder gegeven code
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} moet 1-{max} afdrukbare tekens zijn, zonder richtings- of regelscheidingstekens
@msg {at} names or translates something the manifest doesn't declare {at} noemt of vertaalt iets wat het manifest niet declareert
@msg command {name} is declared twice opdracht {name} is twee keer gedeclareerd
@msg command {name}: `label` must be 1-64 printable characters opdracht {name}: `label` moet uit 1-64 afdrukbare tekens bestaan
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter opdracht {name}: gebruik een id van 1-{MAX_COMMAND_ID} tekens uit a-z 0-9 _ die met een letter begint
@@ -9589,6 +9594,7 @@ axis Y Axis Y-as
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? „{name}” installeren, dat om deze machtigingen vraagt?
ID: {id} ID: {id}
Manifest name: {name} Naam in het manifest: {name}
Version: {version} Versie: {version}
Install “{name}” in place of the plug-in with the same ID? „{name}” installeren in plaats van de plug-in met dezelfde ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Dit bestand is niet de plug-in die eerder met deze ID was geïnstalleerd. Het krijgt de instellingen en cache die voor die ID bewaard zijn.
Can't render this file because it is too large.
+8 -2
View File
@@ -5099,7 +5099,7 @@ imageTrace Outline Kontur
Do not show this warning again Nie pokazuj więcej tego ostrzeżenia
Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie.
This script has added a great many objects. Continue, or stop it and undo what it did? Ten skrypt dodał bardzo wiele obiektów. Kontynuować, czy zatrzymać go i cofnąć jego zmiany?
@msg Choose a .js or .jsx script Wybierz skrypt .js lub .jsx
@msg Choose a .js, .mjs or .jsx script Wybierz skrypt .js, .mjs lub .jsx
@msg Ran {name} Wykonano: {name}
@msg The script was stopped and its changes were undone Skrypt został zatrzymany, a jego zmiany cofnięte
@msg a script is running: stop it or wait for it to finish skrypt jest uruchomiony: zatrzymaj go lub poczekaj na jego zakończenie
@@ -7370,6 +7370,7 @@ axis Y Axis Oś Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Zainstalować „{name}”, wtyczkę, która prosi o te uprawnienia?
ID: {id} ID: {id}
Manifest name: {name} Nazwa w manifeście: {name}
Version: {version} Wersja: {version}
Install “{name}” in place of the plug-in with the same ID? Zainstalować „{name}” zamiast wtyczki o tym samym ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ten plik nie jest wtyczką zainstalowaną wcześniej z tym ID. Otrzyma ustawienia i pamięć podręczną przechowywane dla tego ID.
@@ -7483,6 +7484,11 @@ axis Y Axis Oś Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” nie otrzymała `{p}`, którego potrzebuje jej wynik: nic nie zmieniono
@msg a heavy filter runs in the background, so it can't declare `commands` ciężki filtr działa w tle, więc nie może deklarować `commands`
@msg at most {MAX_COMMANDS} `commands` najwyżej {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` podaje najwyżej {MAX_LANGUAGES} języków
@msg {at} gives two options the same label {at} nadaje dwóm opcjom tę samą etykietę
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} nie jest kodem języka takim jak `de` czy `pt-BR` albo powtarza kod podany wcześniej
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} musi mieć 1-{max} drukowalnych znaków, bez znaków kierunku tekstu i separatorów wierszy
@msg {at} names or translates something the manifest doesn't declare {at} nazywa lub tłumaczy coś, czego manifest nie deklaruje
@msg command {name} is declared twice polecenie {name} jest zadeklarowane dwa razy
@msg command {name}: `label` must be 1-64 printable characters polecenie {name}: `label` musi mieć 1-64 drukowalnych znaków
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter polecenie {name}: użyj id z 1-{MAX_COMMAND_ID} znaków spośród a-z 0-9 _, zaczynającego się od litery
@@ -8830,7 +8836,7 @@ breakText Glyphs Glify
@msg `args` is larger than 1 MiB `args` ma rozmiar większy niż 1 MiB
@msg `path` is empty `path` jest puste
@msg `installed` takes a `path`, not a `source` `installed` przyjmuje `path`, a nie `source`
@msg `path` must name a .js or .jsx file `path` musi wskazywać plik .js lub .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` musi wskazywać plik .js, .mjs lub .jsx
@msg give exactly one of `path` and `source` podaj dokładnie jedno z: `path` i `source`
@msg `answers` must be a list of answers `answers` musi być listą odpowiedzi
@msg `artboard` must be the index of an artboard of the document `artboard` musi być indeksem obszaru kompozycji dokumentu
Can't render this file because it is too large.
+8 -2
View File
@@ -6144,7 +6144,7 @@ variable-list-end {0}, {1} {0} e {1}
Do not show this warning again Não mostrar este aviso novamente
Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente.
This script has added a great many objects. Continue, or stop it and undo what it did? Este script adicionou muitíssimos objetos. Continuar, ou pará-lo e desfazer o que ele fez?
@msg Choose a .js or .jsx script Escolha um script .js ou .jsx
@msg Choose a .js, .mjs or .jsx script Escolha um script .js, .mjs ou .jsx
@msg Ran {name} {name} executado
@msg The script was stopped and its changes were undone O script foi parado e suas alterações foram desfeitas
@msg a script is running: stop it or wait for it to finish um script está em execução: pare-o ou aguarde até que termine
@@ -7416,6 +7416,7 @@ axis Y Axis Eixo Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Instalar “{name}”, que pede estas permissões?
ID: {id} ID: {id}
Manifest name: {name} Nome no manifesto: {name}
Version: {version} Versão: {version}
Install “{name}” in place of the plug-in with the same ID? Instalar “{name}” no lugar do plug-in com o mesmo ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este arquivo não é o plug-in instalado antes com este ID. Ele recebe as configurações e o cache guardados para esse ID.
@@ -7529,6 +7530,11 @@ axis Y Axis Eixo Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” não recebeu `{p}`, de que sua saída precisa: nada foi alterado
@msg a heavy filter runs in the background, so it can't declare `commands` um filtro pesado é executado em segundo plano, então não pode declarar `commands`
@msg at most {MAX_COMMANDS} `commands` no máximo {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` dá no máximo {MAX_LANGUAGES} idiomas
@msg {at} gives two options the same label {at} dá o mesmo rótulo a duas opções
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} não é um código de idioma como `de` ou `pt-BR`, ou repete um dado antes
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} deve ter 1-{max} caracteres imprimíveis, sem caracteres de direção ou separadores de linha
@msg {at} names or translates something the manifest doesn't declare {at} nomeia ou traduz algo que o manifesto não declara
@msg command {name} is declared twice o comando {name} está declarado duas vezes
@msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve ter 1-64 caracteres imprimíveis
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: use um id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que comece com uma letra
@@ -9201,7 +9207,7 @@ swatch Yellow Green Verde-amarelado
@msg `args` is larger than 1 MiB `args` tem mais de 1 MiB
@msg `path` is empty `path` está vazio
@msg `installed` takes a `path`, not a `source` `installed` aceita um `path`, não um `source`
@msg `path` must name a .js or .jsx file `path` deve indicar um arquivo .js ou .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` deve indicar um arquivo .js, .mjs ou .jsx
@msg give exactly one of `path` and `source` informe exatamente um de `path` e `source`
@msg `answers` must be a list of answers `answers` deve ser uma lista de respostas
@msg `artboard` must be the index of an artboard of the document `artboard` deve ser o índice de uma prancheta do documento
Can't render this file because it is too large.
+8 -2
View File
@@ -4973,7 +4973,7 @@ axis Both Оба
Do not show this warning again Больше не показывать это предупреждение
Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз.
This script has added a great many objects. Continue, or stop it and undo what it did? Этот скрипт добавил очень много объектов. Продолжить или остановить его и отменить его изменения?
@msg Choose a .js or .jsx script Выберите скрипт .js или .jsx
@msg Choose a .js, .mjs or .jsx script Выберите скрипт .js, .mjs или .jsx
@msg Ran {name} Выполнено: {name}
@msg The script was stopped and its changes were undone Скрипт остановлен, его изменения отменены
@msg a script is running: stop it or wait for it to finish выполняется скрипт: остановите его или дождитесь завершения
@@ -5132,7 +5132,7 @@ liquify-list-end {0}, {1} {0} и {1}
@msg `args` is larger than 1 MiB `args` больше 1 МиБ
@msg `path` is empty параметр `path` пуст
@msg `installed` takes a `path`, not a `source` `installed` принимает `path`, а не `source`
@msg `path` must name a .js or .jsx file `path` должен указывать на файл .js или .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` должен указывать на файл .js, .mjs или .jsx
@msg give exactly one of `path` and `source` укажите ровно одно из: `path` и `source`
@msg Running a script Выполняется скрипт
@msg Copied the script report Отчёт о сценарии скопирован
@@ -7139,6 +7139,7 @@ axis Y Axis Ось Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Установить «{name}», которому нужны эти разрешения?
ID: {id} ID: {id}
Manifest name: {name} Имя в манифесте: {name}
Version: {version} Версия: {version}
Install “{name}” in place of the plug-in with the same ID? Установить «{name}» вместо модуля с тем же ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Этот файл не является модулем, установленным ранее с этим ID. Он получит настройки и кэш, сохранённые для этого ID.
@@ -7252,6 +7253,11 @@ axis Y Axis Ось Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не получил разрешение `{p}`, нужное для его результата: ничего не изменено
@msg a heavy filter runs in the background, so it can't declare `commands` тяжёлый фильтр выполняется в фоне, поэтому не может объявлять `commands`
@msg at most {MAX_COMMANDS} `commands` не более {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` задаёт не более {MAX_LANGUAGES} языков
@msg {at} gives two options the same label {at} даёт двум вариантам одинаковую подпись
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} не является кодом языка вроде `de` или `pt-BR` или повторяет код, заданный ранее
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} должен содержать 1-{max} печатных символов без символов направления текста и разделителей строк
@msg {at} names or translates something the manifest doesn't declare {at} называет или переводит то, что манифест не объявляет
@msg command {name} is declared twice команда {name} объявлена дважды
@msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` должен содержать 1-64 печатаемых символа
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: используйте id из 1-{MAX_COMMAND_ID} символов a-z 0-9 _, начинающийся с буквы
Can't render this file because it is too large.
+8 -2
View File
@@ -4832,7 +4832,7 @@ axis Both Båda
Do not show this warning again Visa inte den här varningen igen
Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen.
This script has added a great many objects. Continue, or stop it and undo what it did? Det här skriptet har lagt till väldigt många objekt. Fortsätta, eller stoppa det och ångra det det gjort?
@msg Choose a .js or .jsx script Välj ett .js- eller .jsx-skript
@msg Choose a .js, .mjs or .jsx script Välj ett .js-, .mjs- eller .jsx-skript
@msg Ran {name} Körde {name}
@msg The script was stopped and its changes were undone Skriptet stoppades och dess ändringar ångrades
@msg a script is running: stop it or wait for it to finish ett skript körs: stoppa det eller vänta tills det är klart
@@ -5005,7 +5005,7 @@ liquify-list-end {0}, {1} {0} och {1}
@msg `args` is larger than 1 MiB `args` är större än 1 MiB
@msg `path` is empty `path` är tomt
@msg `installed` takes a `path`, not a `source` `installed` tar en `path`, inte en `source`
@msg `path` must name a .js or .jsx file `path` måste ange en .js- eller .jsx-fil
@msg `path` must name a .js, .mjs or .jsx file `path` måste ange en .js-, .mjs- eller .jsx-fil
@msg give exactly one of `path` and `source` ange exakt en av `path` och `source`
@msg Running a script Kör ett skript
@msg Copied the script report Kopierade skriptrapporten
@@ -7519,6 +7519,7 @@ axis Y Axis Y-axel
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Installera ”{name}”, som begär dessa behörigheter?
ID: {id} ID: {id}
Manifest name: {name} Namn i manifestet: {name}
Version: {version} Version: {version}
Install “{name}” in place of the plug-in with the same ID? Installera ”{name}” i stället för det plugin som har samma id?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Den här filen är inte det plugin som tidigare installerades med detta id. Den får de inställningar och den cache som sparats för detta id.
@@ -7613,6 +7614,11 @@ axis Y Axis Y-axel
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” beviljades inte `{p}`, som dess utdata behöver: ingenting ändrades
@msg a heavy filter runs in the background, so it can't declare `commands` ett tungt filter körs i bakgrunden, så det kan inte deklarera `commands`
@msg at most {MAX_COMMANDS} `commands` högst {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` anger högst {MAX_LANGUAGES} språk
@msg {at} gives two options the same label {at} ger två alternativ samma etikett
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} är inte en språkkod som `de` eller `pt-BR`, eller upprepar en som angetts tidigare
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} måste vara 1-{max} utskrivbara tecken, utan riktnings- eller radavgränsartecken
@msg {at} names or translates something the manifest doesn't declare {at} namnger eller översätter något som manifestet inte deklarerar
@msg command {name} is declared twice kommandot {name} deklareras två gånger
@msg command {name}: `label` must be 1-64 printable characters kommando {name}: `label` måste ha 1-64 utskrivbara tecken
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommando {name}: använd ett id med 1-{MAX_COMMAND_ID} tecken av a-z 0-9 _ som börjar med en bokstav
Can't render this file because it is too large.
+8 -2
View File
@@ -4678,7 +4678,7 @@ axis Both Her İkisi
Do not show this warning again Bu uyarıyı bir daha gösterme
Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın.
This script has added a great many objects. Continue, or stop it and undo what it did? Bu betik çok sayıda nesne ekledi. Devam edilsin mi, yoksa durdurulup yaptıkları geri mi alınsın?
@msg Choose a .js or .jsx script Bir .js veya .jsx betiği seçin
@msg Choose a .js, .mjs or .jsx script Bir .js, .mjs veya .jsx betiği seçin
@msg Ran {name} {name} çalıştırıldı
@msg The script was stopped and its changes were undone Betik durduruldu ve değişiklikleri geri alındı
@msg a script is running: stop it or wait for it to finish bir betik çalışıyor: durdurun veya bitmesini bekleyin
@@ -4833,7 +4833,7 @@ liquify-list-end {0}, {1} {0} ve {1}
@msg `args` is larger than 1 MiB `args` 1 MiB'tan büyük
@msg `path` is empty `path` boş
@msg `installed` takes a `path`, not a `source` `installed` bir `path` alır, `source` almaz
@msg `path` must name a .js or .jsx file `path` bir .js veya .jsx dosyasını adlandırmalıdır
@msg `path` must name a .js, .mjs or .jsx file `path` bir .js, .mjs veya .jsx dosyasını adlandırmalıdır
@msg give exactly one of `path` and `source` `path` ve `source` değerlerinden tam olarak birini verin
@msg Running a script Betik çalıştırılıyor
@msg Copied the script report Komut dosyası raporu kopyalandı
@@ -7589,6 +7589,7 @@ axis Y Axis Y ekseni
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Bu izinleri isteyen “{name}” yüklensin mi?
ID: {id} Kimlik: {id}
Manifest name: {name} Manifestteki ad: {name}
Version: {version} Sürüm: {version}
Install “{name}” in place of the plug-in with the same ID? Aynı kimliğe sahip eklentinin yerine “{name}” yüklensin mi?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Bu dosya, daha önce bu kimlikle yüklenen eklenti değil. O kimlik için saklanan ayarları ve önbelleği alır.
@@ -7702,6 +7703,11 @@ axis Y Axis Y ekseni
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” öğesine çıktısının ihtiyaç duyduğu `{p}` izni verilmedi: hiçbir şey değiştirilmedi
@msg a heavy filter runs in the background, so it can't declare `commands` ağır bir filtre arka planda çalışır, bu yüzden `commands` bildiremez
@msg at most {MAX_COMMANDS} `commands` en fazla {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` en fazla {MAX_LANGUAGES} dil verir
@msg {at} gives two options the same label {at} iki seçeneğe aynı etiketi veriyor
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at}, `de` veya `pt-BR` gibi bir dil kodu değil ya da daha önce verilmiş bir kodu yineliyor
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at}, yön veya satır ayırıcı karakterleri olmadan 1-{max} yazdırılabilir karakter olmalıdır
@msg {at} names or translates something the manifest doesn't declare {at}, manifestin bildirmediği bir şeyi adlandırıyor veya çeviriyor
@msg command {name} is declared twice {name} komutu iki kez bildirilmiş
@msg command {name}: `label` must be 1-64 printable characters {name} komutu: `label` 1-64 yazdırılabilir karakter olmalıdır
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} komutu: a-z 0-9 _ karakterlerinden oluşan ve harfle başlayan 1-{MAX_COMMAND_ID} karakterlik bir kimlik kullanın
Can't render this file because it is too large.
+8 -2
View File
@@ -4981,7 +4981,7 @@ axis Both Обидві
Do not show this warning again Більше не показувати це попередження
Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз.
This script has added a great many objects. Continue, or stop it and undo what it did? Цей скрипт додав дуже багато об’єктів. Продовжити чи зупинити його та скасувати його зміни?
@msg Choose a .js or .jsx script Виберіть скрипт .js або .jsx
@msg Choose a .js, .mjs or .jsx script Виберіть скрипт .js, .mjs або .jsx
@msg Ran {name} Виконано: {name}
@msg The script was stopped and its changes were undone Скрипт зупинено, його зміни скасовано
@msg a script is running: stop it or wait for it to finish виконується скрипт: зупиніть його або дочекайтеся завершення
@@ -7119,6 +7119,7 @@ axis Y Axis Вісь Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Встановити «{name}», якому потрібні ці дозволи?
ID: {id} ID: {id}
Manifest name: {name} Назва в маніфесті: {name}
Version: {version} Версія: {version}
Install “{name}” in place of the plug-in with the same ID? Встановити «{name}» замість модуля з тим самим ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Цей файл не є модулем, установленим раніше з цим ID. Він отримає налаштування й кеш, збережені для цього ID.
@@ -7232,6 +7233,11 @@ axis Y Axis Вісь Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не отримав дозволу `{p}`, потрібного для його результату: нічого не змінено
@msg a heavy filter runs in the background, so it can't declare `commands` важкий фільтр виконується у фоні, тому не може оголошувати `commands`
@msg at most {MAX_COMMANDS} `commands` щонайбільше {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` задає щонайбільше {MAX_LANGUAGES} мов
@msg {at} gives two options the same label {at} дає двом варіантам однаковий підпис
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} не є кодом мови на кшталт `de` чи `pt-BR` або повторює код, заданий раніше
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} має містити 1-{max} друкованих символів без символів напрямку тексту й розділювачів рядків
@msg {at} names or translates something the manifest doesn't declare {at} називає або перекладає те, чого маніфест не оголошує
@msg command {name} is declared twice команду {name} оголошено двічі
@msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` має містити 1-64 друковані символи
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: використайте id з 1-{MAX_COMMAND_ID} символів a-z 0-9 _, що починається з літери
@@ -8786,7 +8792,7 @@ breakText Glyphs Гліфи
@msg `args` is larger than 1 MiB `args` більший за 1 МіБ
@msg `path` is empty параметр `path` порожній
@msg `installed` takes a `path`, not a `source` `installed` приймає `path`, а не `source`
@msg `path` must name a .js or .jsx file `path` має вказувати на файл .js або .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` має вказувати на файл .js, .mjs або .jsx
@msg give exactly one of `path` and `source` укажіть рівно одне з: `path`, `source`
@msg `answers` must be a list of answers `answers` має бути списком відповідей
@msg `artboard` must be the index of an artboard of the document `artboard` має бути індексом монтажної області документа
Can't render this file because it is too large.
+8 -2
View File
@@ -5460,7 +5460,7 @@ theme Appearance Giao diện
Do not show this warning again Không hiện lại cảnh báo này
Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại.
This script has added a great many objects. Continue, or stop it and undo what it did? Tập lệnh này đã thêm rất nhiều đối tượng. Tiếp tục, hay dừng lại và hoàn tác những gì nó đã làm?
@msg Choose a .js or .jsx script Chọn một tập lệnh .js hoặc .jsx
@msg Choose a .js, .mjs or .jsx script Chọn một tập lệnh .js, .mjs hoặc .jsx
@msg Ran {name} Đã chạy {name}
@msg The script was stopped and its changes were undone Tập lệnh đã dừng và các thay đổi của nó đã được hoàn tác
@msg a script is running: stop it or wait for it to finish một tập lệnh đang chạy: hãy dừng nó hoặc chờ nó kết thúc
@@ -5632,7 +5632,7 @@ liquify-list-end {0}, {1} {0} và {1}
@msg `args` is larger than 1 MiB `args` lớn hơn 1 MiB
@msg `path` is empty `path` trống
@msg `installed` takes a `path`, not a `source` `installed` nhận `path`, không nhận `source`
@msg `path` must name a .js or .jsx file `path` phải chỉ đến tệp .js hoặc .jsx
@msg `path` must name a .js, .mjs or .jsx file `path` phải chỉ đến tệp .js, .mjs hoặc .jsx
@msg give exactly one of `path` and `source` hãy cung cấp đúng một trong `path` và `source`
@msg Running a script Đang chạy tập lệnh
@msg Copied the script report Đã sao chép báo cáo script
@@ -7168,6 +7168,7 @@ axis Y Axis Trục Y
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? Cài đặt “{name}”, plug-in yêu cầu các quyền này?
ID: {id} ID: {id}
Manifest name: {name} Tên trong manifest: {name}
Version: {version} Phiên bản: {version}
Install “{name}” in place of the plug-in with the same ID? Cài đặt “{name}” thay cho plug-in có cùng ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tệp này không phải là plug-in đã cài đặt trước đây với ID này. Tệp sẽ nhận cài đặt và bộ nhớ đệm được lưu cho ID đó.
@@ -7281,6 +7282,11 @@ axis Y Axis Trục Y
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” chưa được cấp `{p}`, quyền mà đầu ra của nó cần: không có gì thay đổi
@msg a heavy filter runs in the background, so it can't declare `commands` bộ lọc nặng chạy ở chế độ nền nên không thể khai báo `commands`
@msg at most {MAX_COMMANDS} `commands` tối đa {MAX_COMMANDS} `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` chỉ định tối đa {MAX_LANGUAGES} ngôn ngữ
@msg {at} gives two options the same label {at} đặt cùng một nhãn cho hai tùy chọn
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} không phải mã ngôn ngữ như `de` hoặc `pt-BR`, hoặc lặp lại mã đã cho trước đó
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} phải có 1-{max} ký tự in được, không có ký tự định hướng hoặc ký tự phân cách dòng
@msg {at} names or translates something the manifest doesn't declare {at} đặt tên hoặc dịch một thứ mà manifest không khai báo
@msg command {name} is declared twice lệnh {name} được khai báo hai lần
@msg command {name}: `label` must be 1-64 printable characters lệnh {name}: `label` phải có 1-64 ký tự in được
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter lệnh {name}: hãy dùng id gồm 1-{MAX_COMMAND_ID} ký tự từ a-z 0-9 _ và bắt đầu bằng một chữ cái
Can't render this file because it is too large.
+8 -2
View File
@@ -5489,7 +5489,7 @@ imageTrace Outline 轮廓
Do not show this warning again 不再显示此警告
Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。
This script has added a great many objects. Continue, or stop it and undo what it did? 此脚本已添加大量对象。要继续,还是停止并撤销其更改?
@msg Choose a .js or .jsx script 请选择 .js 或 .jsx 脚本
@msg Choose a .js, .mjs or .jsx script 请选择 .js、.mjs 或 .jsx 脚本
@msg Ran {name} 已运行 {name}
@msg The script was stopped and its changes were undone 脚本已停止,其更改已撤销
@msg a script is running: stop it or wait for it to finish 脚本正在运行:请停止它或等待其完成
@@ -7349,6 +7349,7 @@ axis Y Axis Y 轴
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? 要安装需要这些权限的“{name}”吗?
ID: {id} ID:{id}
Manifest name: {name} 清单中的名称:{name}
Version: {version} 版本:{version}
Install “{name}” in place of the plug-in with the same ID? 要安装“{name}”来替换具有相同 ID 的插件吗?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此文件不是之前以此 ID 安装的插件。它将获得为该 ID 保存的设置和缓存。
@@ -7462,6 +7463,11 @@ axis Y Axis Y 轴
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”未获授予其输出所需的 `{p}`:未作任何更改
@msg a heavy filter runs in the background, so it can't declare `commands` 重型滤镜在后台运行,因此不能声明 `commands`
@msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 个 `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` 最多给出 {MAX_LANGUAGES} 种语言
@msg {at} gives two options the same label {at} 为两个选项给出了相同的标签
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} 不是 `de` 或 `pt-BR` 这样的语言代码,或重复了前面给出的代码
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 必须为 1-{max} 个可打印字符,且不含方向字符或行分隔符
@msg {at} names or translates something the manifest doesn't declare {at} 指定或翻译了清单未声明的内容
@msg command {name} is declared twice 命令 {name} 声明了两次
@msg command {name}: `label` must be 1-64 printable characters 命令 {name}:`label` 必须是 1-64 个可打印字符
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 命令 {name}:请使用由 a-z 0-9 _ 组成、以字母开头的 1-{MAX_COMMAND_ID} 个字符的 ID
@@ -8838,7 +8844,7 @@ breakText Glyphs 字形
@msg `args` is larger than 1 MiB `args` 大于 1 MiB
@msg `path` is empty `path` 为空
@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source`
@msg `path` must name a .js or .jsx file `path` 必须指向 .js 或 .jsx 文件
@msg `path` must name a .js, .mjs or .jsx file `path` 必须指向 .js、.mjs 或 .jsx 文件
@msg give exactly one of `path` and `source` `path` 和 `source` 中必须且只能给出一个
@msg `answers` must be a list of answers `answers` 必须是回答的列表
@msg `artboard` must be the index of an artboard of the document `artboard` 必须是文档中某个画板的索引
Can't render this file because it is too large.
+8 -2
View File
@@ -2821,7 +2821,7 @@ file-filter Templates 範本
Do not show this warning again 不再顯示此警告
Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。
This script has added a great many objects. Continue, or stop it and undo what it did? 此指令碼已新增大量物件。要繼續,還是停止並還原其變更?
@msg Choose a .js or .jsx script 請選擇 .js 或 .jsx 指令碼
@msg Choose a .js, .mjs or .jsx script 請選擇 .js、.mjs 或 .jsx 指令碼
@msg Ran {name} 已執行 {name}
@msg The script was stopped and its changes were undone 指令碼已停止,其變更已還原
@msg a script is running: stop it or wait for it to finish 指令碼正在執行:請停止它或等待其完成
@@ -2968,7 +2968,7 @@ liquify-list-end {0}, {1} {0}和{1}
@msg `args` is larger than 1 MiB `args` 大於 1 MiB
@msg `path` is empty `path` 為空
@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source`
@msg `path` must name a .js or .jsx file `path` 必須指向 .js 或 .jsx 檔案
@msg `path` must name a .js, .mjs or .jsx file `path` 必須指向 .js、.mjs 或 .jsx 檔案
@msg give exactly one of `path` and `source` `path` 和 `source` 請只提供其中一個
@msg Running a script 正在執行指令碼
@msg Copied the script report 已複製指令碼報告
@@ -7168,6 +7168,7 @@ axis Y Axis Y 軸
# Plug-in permissions (Install Plug-in…, plugin.install grant)
Install “{name}”, which asks for these permissions? 要安裝需要這些權限的「{name}」嗎?
ID: {id} ID:{id}
Manifest name: {name} 資訊清單中的名稱:{name}
Version: {version} 版本:{version}
Install “{name}” in place of the plug-in with the same ID? 要安裝「{name}」來取代具有相同 ID 的增效模組嗎?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此檔案不是先前以此 ID 安裝的增效模組。它會取得為該 ID 保存的設定和快取。
@@ -7281,6 +7282,11 @@ axis Y Axis Y 軸
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」未獲授予其輸出所需的 `{p}`:未做任何變更
@msg a heavy filter runs in the background, so it can't declare `commands` 重型濾鏡在背景執行,因此不能宣告 `commands`
@msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 個 `commands`
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` 最多提供 {MAX_LANGUAGES} 種語言
@msg {at} gives two options the same label {at} 為兩個選項提供了相同的標籤
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} 不是 `de` 或 `pt-BR` 這類語言代碼,或重複了前面提供的代碼
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 必須為 1-{max} 個可列印字元,且不含方向字元或行分隔字元
@msg {at} names or translates something the manifest doesn't declare {at} 指定或翻譯了資訊清單未宣告的內容
@msg command {name} is declared twice 指令 {name} 宣告了兩次
@msg command {name}: `label` must be 1-64 printable characters 指令 {name}:`label` 必須是 1-64 個可列印字元
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 指令 {name}:請使用由 a-z 0-9 _ 組成、以字母開頭的 1-{MAX_COMMAND_ID} 個字元的 ID
Can't render this file because it is too large.
+30 -11
View File
@@ -9,6 +9,7 @@ use craft::platform::open::same_file;
use super::save::{notes_of, show_with_notes, suggested};
use super::{Value, VectorcraftApp, dialogs, fileio, json};
use crate::file_asks::{self, Owner};
use crate::i18n::LangExt as _;
/// Template extensions New from Template's open dialog lists first.
const TEMPLATE_EXTS: &[&str] = &["vctemplate", "ait", "vectorcraft", "drawcraft"];
@@ -294,10 +295,11 @@ fn permission_words(name: &str, commands: &[String], context: bool) -> String {
/// Installs the plug-in module that `module` names (`plugin.install`'s `path`, or `dataBase64`
/// with `name`) → `plugin.install`'s result. A plug-in that lists permissions no person has granted
/// it yet asks first, showing its name, id, version, file hash and what each permission lets it
/// do, so does a filter that asks for a heavy budget, and so does a module that would take the
/// place of another one with its id and get its settings and cache (`replace`); OK installs it if
/// the module still has the hash the prompt showed, Cancel installs nothing → `{pending}` while it
/// asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves.
/// do, so does a filter that asks for a heavy budget, showing its id and file hash, and so does a
/// module that would take the place of another one with its id and get its settings and cache
/// (`replace`). When the name shown is a translation, the id lines also give the manifest's own
/// name. OK installs it if the module still has the hash the prompt showed, Cancel installs
/// nothing → `{pending}` while it asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves.
/// Every question opens the approval dialog ([`dialogs::plugin::ask_install`]). When automation
/// asked ([`VectorcraftApp::automation_asked`]), the question has no OK that installs, its
/// `replace: true` doesn't skip asking about replacing, and the answer while it asks adds
@@ -336,12 +338,25 @@ pub(crate) fn install_module_as(app: &mut VectorcraftApp, module: Value, automat
install["hash"] = info["hash"].clone();
}
let shown = |k: &str, max: usize| permissions::display_text(info[k].as_str().unwrap_or_default(), max);
let name = shown("name", permissions::MAX_SHOWN_NAME);
let identity = [
crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))]),
crate::i18n::fmt(tl!("File SHA-256: {hash}"), &[("hash", &shown("hash", 64))]),
]
.join("\n");
// The question names the plug-in in the UI language when its manifest translates the name, and
// then also gives the manifest's own name; both are fixed while the question is asked.
let own_name = shown("name", permissions::MAX_SHOWN_NAME);
let translations: vectorcraft_plugins::translations::Translations = serde_json::from_value(info["translations"].clone()).unwrap_or_default();
let name = translations
.name_in(crate::i18n::current().code())
.map(|n| permissions::display_text(n.trim(), permissions::MAX_SHOWN_NAME))
.unwrap_or_else(|| own_name.clone());
let id_lines = |id_line: String| {
let mut lines = vec![id_line];
if name != own_name {
lines.push(crate::i18n::fmt(tl!("Manifest name: {name}"), &[("name", &own_name)]));
}
lines
};
let id_line = crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))]);
let mut identity = id_lines(id_line.clone());
identity.push(crate::i18n::fmt(tl!("File SHA-256: {hash}"), &[("hash", &shown("hash", 64))]));
let identity = identity.join("\n");
let takes_place = tl!("This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID.");
if asks_replace {
install["replace"] = json!(true);
@@ -351,7 +366,7 @@ pub(crate) fn install_module_as(app: &mut VectorcraftApp, module: Value, automat
let asked = info["permissions"].as_array().cloned().unwrap_or_default();
let mut paragraphs = vec![];
if needs_grant {
let mut lines = vec![crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))])];
let mut lines = id_lines(id_line);
let version = shown("version", permissions::MAX_SHOWN_FIELD);
if !version.is_empty() {
lines.push(crate::i18n::fmt(tl!("Version: {version}"), &[("version", &version)]));
@@ -368,6 +383,10 @@ pub(crate) fn install_module_as(app: &mut VectorcraftApp, module: Value, automat
install["grant"] = Value::Array(asked.clone());
}
if heavy {
// A heavy filter that asks nothing else shows its id and file hash first.
if !needs_grant && !asks_replace {
paragraphs.push(identity.clone());
}
let (minutes, times) = vectorcraft_plugins::heavy_terms();
paragraphs.push(crate::i18n::fmt(
tl!(
+1 -1
View File
@@ -93,7 +93,7 @@ pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number};
#[cfg(test)]
use slots::RECENT_FONT_IDS;
pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state};
pub(crate) use state::{command_shortcuts, why_off};
pub(crate) use state::{command_shortcuts, shown_state_with, why_off};
pub(crate) use submenus::PATH_EFFECTS;
pub use tree::{Listed, menu_tree, menu_tree_named};
pub use ui_commands::UI_COMMANDS;
+15 -3
View File
@@ -93,11 +93,17 @@ fn slot_label(app: &VectorcraftApp, id: &str) -> Option<String> {
Some(text)
}
/// The name Last Effect gives effect `e`: its Effect menu label, a plug-in's name in the UI language
/// as Effect › Plug-ins shows it ([`crate::dialogs::plugin::effect_item_label`]).
fn last_effect_name(e: &str) -> &str {
vectorcraft_effects::effect_info(e).map(|i| crate::dialogs::plugin::effect_item_label(&i)).unwrap_or(e)
}
/// The labels that follow the last effect, the envelope being edited, the history and the perspective grid.
fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option<String> {
let text: String = match id {
"effect.last" => match &app.last_effect {
Some((e, _)) => format!("Last Effect: {}", vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str())),
Some((e, _)) => format!("Last Effect: {}", last_effect_name(e)),
None => label.into(),
},
// Repeat Pathfinder is named after the Shape Mode or Pathfinder operation that ran last.
@@ -169,7 +175,8 @@ pub(crate) fn shows_a_name(id: &str, label: &str) -> bool {
)
|| vectorcraft_engine::cmd::plugin::is_command_id(id)
|| (id == "window.workspace" && !crate::workspaces::builtins().iter().any(|w| w.name.eq_ignore_ascii_case(label.trim())))
|| (matches!(id, "effect.apply" | "effect.dialog") && vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label))
|| (matches!(id, "effect.apply" | "effect.dialog")
&& vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label || crate::dialogs::plugin::effect_item_label(e) == label))
}
/// Does the menu item `id` with `params` list an installed plug-in (an Object › Plug-ins filter, an
@@ -207,7 +214,12 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String {
"window.toolbarAdvanced" => crate::i18n::tr(lang, label).to_string(),
"effect.last" => match &app.last_effect {
Some((e, _)) => {
let name = crate::i18n::effect_menu_label(lang, e).unwrap_or_else(|| e.clone());
// A plug-in's name is already in the UI language from its translations.
let name = if vectorcraft_plugins::effect::plugin_id(e).is_some() {
last_effect_name(e).to_string()
} else {
crate::i18n::effect_menu_label(lang, e).unwrap_or_else(|| e.clone())
};
fmt(tl!("Last Effect: {name}"), &[("name", &name)])
}
None => crate::i18n::tr_id(lang, id, label).to_string(),
+38 -8
View File
@@ -18,7 +18,7 @@ use craft::ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
use super::labels::holds_plugin_commands;
use super::{Listed, PLACEHOLDER, TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state, why_off};
use super::{Listed, PLACEHOLDER, TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state_with, why_off};
use crate::i18n::LangExt as _;
use crate::{UiState, VectorcraftApp};
@@ -424,7 +424,9 @@ fn linked_defaults(command: &CommandRef) -> Option<Vec<Binding>> {
/// The state of the row `command`, named `label` in the catalog: on or dimmed with its reason, checked, and its title
/// where the app shows another.
fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> CommandState {
let (enabled, checked) = shown_state(app, crate::keymap::state_id(command), &command.params).unwrap_or((false, None));
let state_id = crate::keymap::state_id(command);
let why = why_off(app, state_id);
let (enabled, checked) = shown_state_with(app, state_id, &command.params, &why).unwrap_or((false, None));
let mut state = CommandState::new().enabled(enabled);
if let Some(on) = checked {
state = state.checked(on);
@@ -434,7 +436,7 @@ fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> Command
state = state.title(shown.clone());
}
if !enabled {
state = state.hint(off_reason(app, command, &shown));
state = state.hint(off_reason_with(app, command, &shown, why));
}
state
}
@@ -442,9 +444,13 @@ fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> Command
/// What the dimmed row `command`, named `label`, says in the interface language: the engine's reason, the panels' in
/// Presentation Mode, else that the command is not available right now.
pub(crate) fn off_reason(app: &VectorcraftApp, command: &CommandRef, label: &str) -> String {
why_off(app, crate::keymap::state_id(command))
.flatten()
.or_else(|| crate::palette::refusal(app, command).filter(|_| command.id == "window.panel"))
off_reason_with(app, command, label, why_off(app, crate::keymap::state_id(command)))
}
/// [`off_reason`] from `why`, what [`why_off`] answered for the command's state id.
fn off_reason_with(app: &VectorcraftApp, command: &CommandRef, label: &str, why: Option<Option<String>>) -> String {
why.flatten()
.or_else(|| if command.id == "window.panel" { crate::palette::refusal(app, command) } else { None })
.map_or_else(|| crate::i18n::msg(&format!("command `{label}` is not available right now")), |why| crate::i18n::msg(&why))
}
@@ -520,7 +526,8 @@ impl Build<'_> {
return Some(item);
}
let (id, params) = (command.id.as_str(), &command.params);
let (enabled, checked) = shown_state(self.app, id, params)?;
let why = why_off(self.app, id);
let (enabled, checked) = shown_state_with(self.app, id, params, &why)?;
let title = self.item_title(id, params, &item.label);
let mut state = CommandState::new().enabled(enabled).title(title.clone());
if let Some(on) = checked {
@@ -532,7 +539,10 @@ impl Build<'_> {
} else if enabled {
None
} else {
Some(off_reason(self.app, &command, &title))
// The reason reads the check of the command's state id, which is `id` but for the framework's own rows.
let state_id = crate::keymap::state_id(&command);
let why = if state_id == id { why } else { why_off(self.app, state_id) };
Some(off_reason_with(self.app, &command, &title, why))
};
if let Some(tip) = tip {
state = state.hint(tip.clone());
@@ -625,4 +635,24 @@ mod tests {
assert!(app.menus.states.get(&CommandRef::new("edit.undo")).is_some_and(CommandState::is_enabled), "the states follow the edits");
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled));
}
/// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together.
#[test]
fn a_rebuild_checks_each_dimmed_row_once() {
let (mut app, ctx) = app_with_document();
// `object.group` is a row of the Object menu; `appearance.addFill` is a catalog row only, dimmed with no subject.
let ids = ["object.group", "appearance.addFill"];
for id in ids {
assert!(!app.menus.states.get(&CommandRef::new(id)).is_some_and(CommandState::is_enabled), "{id} is dimmed");
}
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
app.run("select.none", json!({})).unwrap();
super::super::state::WHY_OFF_ASKED.with_borrow_mut(Vec::clear);
refresh(&mut app, &ctx);
let asked = super::super::state::WHY_OFF_ASKED.take();
for id in ids {
assert_eq!(asked.iter().filter(|a| *a == id).count(), 1, "{id}");
assert!(app.menus.states.get(&CommandRef::new(id)).is_some_and(|s| !s.is_enabled()), "{id} is still dimmed");
}
}
}

Some files were not shown because too many files have changed in this diff Show More