Merge main into feat/scripts-doc-defaults

This commit is contained in:
dotCooCoo committed 2026-11-28 23:20:21 -08:00
commit 0bd735f53d
201 files changed
+13721 -999

No files matched your search

+1
View File
@@ -851,6 +851,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop};
/// Document Info's category titles, the Objects category's count labels, and how its image rows
/// write a resolution and a number of bytes.
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
+354 -72
View File
@@ -146,18 +146,52 @@ 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",
[],
None,
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}",
always,
contrast
),
]
}
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`"))?;
@@ -1032,7 +1066,229 @@ const BELOW_SIDE: f64 = 1.0;
/// The pixels per point [`color_below`] renders at.
const BELOW_SCALE: f64 = 4.0;
/// What `color.contrast` measures a color against: the background, and how the color is drawn over
/// it (its row, object, groups and layer, each with its blend mode and opacity over the art below
/// it). The Color Wheel panel's contrast lines measure many colors against one.
#[derive(Clone, Debug, PartialEq)]
pub struct Backdrop {
/// The background in display sRGB.
against: [f32; 3],
/// The background in working RGB, rounded to 8 bits, as the answer writes it.
written: [u8; 3],
/// The levels the color is drawn through, innermost first, without those that leave it as it is.
passes: Vec<Pass>,
/// The color and amount a fill stains the picked object of a dynamic symbol instance with.
stain: Option<(Color, f32)>,
/// Whether the canvas shows 100 % K alone as black (a rich black Appearance of Black).
rich_black: bool,
}
/// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color
/// and its alpha), whether it blends without isolating or isolates its blending, and the alpha of
/// the art below it inside the level around it, while a blending level lies further out.
#[derive(Clone, Debug, PartialEq)]
struct Pass {
blend: BlendMode,
opacity: f32,
backdrop: ([f32; 3], f32),
blends: bool,
isolate: bool,
inner: f32,
}
/// A color drawn through the levels so far: the color, its alpha, and the alpha of what the next
/// level out holds drawn alone.
type Through = ([f32; 3], f32, f32);
impl Pass {
/// What the level draws for color and alpha `x`, drawn over the art below it: a level that
/// blends takes that art back out by `alone`, the alpha of what it holds drawn alone.
fn source(&self, x: ([f32; 3], f32), alone: f32) -> ([f32; 3], f32) {
if !self.blends {
return x;
}
if alone <= 0.0 {
return (x.0, 0.0);
}
let b = self.backdrop;
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * b.0[i] * b.1) / alone).clamp(0.0, 1.0)), alone)
}
/// `d` drawn through the level. The level's opacity applies to what it holds, a level that
/// isolates its blending carries out the alpha of what it holds composited on its own, and the
/// art beside it in the level around it adds to the alpha once.
fn draw(&self, (color, alpha, alone): Through) -> Through {
let source = self.source((color, alpha), alone);
let drawn = if self.isolate { alpha } else { alone } * self.opacity.clamp(0.0, 1.0);
let (color, alpha) = composite(self.blend, source, self.opacity, self.backdrop);
(color, alpha, drawn + self.inner * (1.0 - drawn))
}
/// The level with its opacity, the art below it and its alphas passed through `q`.
fn with(&self, q: impl Fn(f32) -> f32) -> Pass {
let (color, alpha) = self.backdrop;
Pass { opacity: q(self.opacity), backdrop: (color.map(&q), q(alpha)), inner: q(self.inner), ..self.clone() }
}
}
impl Backdrop {
/// `c` as the measured object draws it: the picked object of a dynamic symbol instance that a
/// fill stains mixes its solid color towards the stain.
pub fn drawn_color(&self, c: &Color) -> Color {
match self.stain {
Some((stain, amount)) => c.lerp(&stain, amount),
None => *c,
}
}
/// The display sRGB the canvas shows for `c` drawn as the measured object draws it, through
/// `cms` and the Appearance of Black the backdrop was read with.
pub fn shown(&self, cms: &vectorcraft_color::cms::Cms, c: &Color) -> [f32; 3] {
shown_rgb(cms, self.rich_black, &self.drawn_color(c))
}
/// Display sRGB `shown`, drawn as the measured color is drawn, over the background.
pub fn front(&self, shown: [f32; 3]) -> [f32; 3] {
let (color, alpha, _) = self.passes.iter().fold((shown, 1.0f32, 1.0f32), |d, p| p.draw(d));
if alpha >= 1.0 { color } else { wcag::over(color, alpha, self.against) }
}
/// The contrast ratio of display sRGB `shown`, drawn as the measured color is drawn, against
/// the background.
pub fn ratio(&self, shown: [f32; 3]) -> f64 {
wcag::contrast_ratio(self.front(shown), self.against)
}
/// [`Backdrop::ratio`] with every value rounded to 8 bits per channel: the color, the art
/// below each level, the background, the opacities, and the color and alpha each level gives.
fn ratio_at_eight_bits(&self, shown: [f32; 3]) -> f64 {
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
let painted = |c: [f32; 3]| c.map(eight);
let against = painted(self.against);
let (color, alpha, _) = self.passes.iter().fold((painted(shown), 1.0f32, 1.0f32), |d, p| {
let (color, alpha, alone) = p.with(eight).draw(d);
(painted(color), eight(alpha), eight(alone))
});
let front = if alpha >= 1.0 { color } else { wcag::over(color, alpha, against) };
wcag::contrast_ratio(painted(front), against)
}
/// The background as `#rrggbb` in working RGB, the form a color param takes.
pub fn against_hex(&self) -> String {
let [r, g, b] = self.written;
format!("#{r:02x}{g:02x}{b:02x}")
}
}
/// The display sRGB the canvas shows for `c` through `cms`: with a rich black Appearance of Black,
/// 100 % K alone shows as black.
fn shown_rgb(cms: &vectorcraft_color::cms::Cms, rich_black: bool, c: &Color) -> [f32; 3] {
match *c {
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
_ => cms.display_rgb(c),
}
}
/// Display sRGB `srgb` as a color in the model of `like`, as a pick on the Color Wheel stores it:
/// an RGB color in the working RGB space, a CMYK or Lab color converted with the color settings, a
/// Gray color as gray.
fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) -> Color {
let [r, g, b] = cms.srgb_to_rgb(srgb);
let rgb = Color::rgb(r, g, b);
match like {
Color::Rgb { .. } => rgb,
Color::Cmyk { .. } => {
let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent);
Color::cmyk(c, m, y, k)
}
Color::Lab { .. } => {
let l = cms.lab(&rgb);
Color::lab(l.l, l.a, l.b)
}
Color::Gray { .. } => keep_model(*like, rgb),
}
}
/// The closest color in the model of `color` whose contrast against `backdrop` meets `minimum`
/// ([`wcag::closest_passing`]), checked as the canvas shows it once stored (a symbol's stain
/// included). A candidate meets it by [`Backdrop::ratio`] and also with its values rounded to 8
/// bits per channel ([`Backdrop::ratio_at_eight_bits`]). None when `color` already meets it by
/// [`Backdrop::ratio`], or when no lightness of its hue does.
fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64) -> Option<Color> {
let cms = vectorcraft_color::cms::active();
let ratio = |srgb: [f32; 3]| {
let shown = backdrop.shown(&cms, &in_model_of(&cms, srgb, color));
backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown))
};
if backdrop.ratio(backdrop.shown(&cms, color)) >= minimum {
return None;
}
let fix = wcag::closest_passing(shown_rgb(&cms, backdrop.rich_black, color), minimum, &ratio)?;
Some(in_model_of(&cms, fix, color))
}
fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
contrast_measure(s, p).map(|(answer, _)| answer)
}
/// `color.contrast`'s answer for params `p`, and what it measured the color against.
pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> {
const C: &str = "color.contrast";
let category = match p.get("for") {
None | Some(Value::Null) => Category::NormalText,
Some(v) => {
let key = "for";
let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
v.as_str().and_then(Category::parse).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", ids.join(", "))))?
}
};
let (color, backdrop) = contrast_backdrop(s, p)?;
let ratio = backdrop.ratio(backdrop.shown(&vectorcraft_color::cms::active(), &color));
let levels = |c: Category| {
let (aa, aaa) = c.passes(ratio);
match aaa {
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
None => json!({ "aa": aa }),
}
};
let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum) {
Some(c) => serde_json::to_value(c).unwrap_or(Value::Null),
None => Value::Null,
};
let fixes = match category.minimums() {
(aa, Some(aaa)) => json!({ "aa": fix(aa), "aaa": fix(aaa) }),
(aa, None) => json!({ "aa": fix(aa) }),
};
let answer = json!({
"ratio": ratio,
"against": backdrop.against_hex(),
"normalText": levels(Category::NormalText),
"largeText": levels(Category::LargeText),
"graphics": levels(Category::Graphics),
"for": category.id(),
"fix": fixes,
});
Ok((answer, backdrop))
}
/// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and
/// what it measures it against.
fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> {
let (color, backdrop) = contrast_reading(s, p, true)?;
let color = color.ok_or_else(|| bad("color.contrast", no_color()))?;
Ok((color, backdrop))
}
/// What a color picked for the active proxy would be measured against by `color.contrast` with
/// params `p` (without `color`), also when the proxy has no color to measure (None, a pattern): the
/// Color Wheel's contrast lines show where a pick would pass.
pub fn contrast_pick_backdrop(s: &Session, p: &Value) -> Result<Backdrop> {
contrast_reading(s, p, false).map(|(_, backdrop)| backdrop)
}
/// [`contrast_backdrop`], with None for the color when the proxy has none, which is an error when
/// `need_color`.
fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option<Color>, Backdrop)> {
const C: &str = "color.contrast";
check_numbers(p, &["opacity"], C)?;
let opacity = match p.get("opacity").and_then(Value::as_f64) {
@@ -1044,23 +1300,28 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
None => None,
};
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
let given = p.get("color").is_some_and(|v| !v.is_null());
let (color, drawn) = match p.get("color") {
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
Some(v) => (Some(color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?), Drawn::default()),
};
if need_color && color.is_none() {
return Err(bad(C, no_color()));
}
let rich_black = s.prefs.black_on_screen == "rich";
let cms = vectorcraft_color::cms::active();
let shown = |c: &Color| match *c {
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
_ => cms.display_rgb(c),
};
let shown = |c: &Color| shown_rgb(&cms, rich_black, c);
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
// Whether the background read is one color across its pixels.
let mut uniform = true;
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
let (against, written) = match p.get("against").filter(|_| !below) {
None => {
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
// one the ratio uses, and giving it back answers the same ratio.
let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
let ((sample, _), one) = color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?;
uniform &= one;
let working = to_8bit(cms.srgb_to_rgb(sample));
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
}
Some(v) => {
@@ -1096,60 +1357,51 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
// then takes that art back out by the alpha of what it holds drawn alone, and blends the rest:
// `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity
// applies to what it holds, and the art beside it in the level around it adds to the alpha once.
// The alphas, the art below each level and `alone` do not depend on the color, so each level
// is read once here and [`Backdrop::front`] draws any color through the levels.
let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate;
let mut x = (shown(&color), 1.0f32);
let mut passes = vec![];
let mut alpha = 1.0f32;
let mut alone = 1.0f32;
// Whether a level so far read art that is not one color.
let mut mixed = false;
for (k, step) in steps.iter().enumerate() {
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 {
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && alpha >= 1.0 && alone >= 1.0 {
continue;
}
let above = &steps[k + 1..];
let scope = above.iter().find(|a| a.isolate);
let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::<Vec<_>>();
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
let backdrop = match scope {
Some(_) if !sampled => ([0.0; 3], 0.0),
None if !sampled => (against, 1.0),
let (backdrop, one) = match scope {
Some(_) if !sampled => (([0.0; 3], 0.0), true),
None if !sampled => ((against, 1.0), uniform),
// The background itself, as the answer writes it.
None if step.hide.is_none() && full.is_empty() => (against, 1.0),
None if step.hide.is_none() && full.is_empty() => ((against, 1.0), uniform),
_ => read(scope.map(|a| &a.within))?,
};
// The alpha of the art below the level inside the level around it, while a blending level
// lies further out (none for a given background).
let inner = match above.first() {
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
_ => 0.0,
let (inner, inner_one) = match above.first() {
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => {
let ((_, a), one) = read(Some(&around.within))?;
(a, one)
}
_ => (0.0, true),
};
let source = if !blends(step) {
x
} else if alone <= 0.0 {
(x.0, 0.0)
} else {
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
};
// A level that isolates its blending carries out the alpha of what it holds composited on
// its own.
let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
x = composite(step.blend, source, step.opacity, backdrop);
alone = drawn + inner * (1.0 - drawn);
}
let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
let ratio = wcag::contrast_ratio(front, against);
let levels = |c: Category| {
let (aa, aaa) = c.passes(ratio);
match aaa {
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
None => json!({ "aa": aa }),
// A blend mode mixes the color with the art below it pixel by pixel, which one color read for
// art of several colors does not stand for, also when that art reaches it through the levels
// inside it.
mixed |= !one || !inner_one;
if mixed && step.blend != BlendMode::Normal && step.opacity > 0.0 {
return Err(bad(C, "the art behind the selection is not one color where it is read, and the color blends with it: give `against`"));
}
};
let [r, g, b] = written;
Ok(json!({
"ratio": ratio,
"against": format!("#{r:02x}{g:02x}{b:02x}"),
"normalText": levels(Category::NormalText),
"largeText": levels(Category::LargeText),
"graphics": levels(Category::Graphics),
}))
let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, blends: blends(step), isolate: step.isolate, inner };
(_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone));
passes.push(pass);
}
let stain = if given { None } else { stain_of(s, !need_color) };
Ok((color, Backdrop { against, written, passes, stain, rich_black }))
}
/// An object around the proxy's object: one in the document, or a group of the picked object's
@@ -1232,7 +1484,8 @@ fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32;
/// levels that change what they draw must be the same objects too, since the art below each one is
/// read with that object hidden, and the object's opacity must be the same apart from its row's,
/// since the row draws over the object's rows below it and the object over the art behind it, and a
/// row that blends or is translucent must lie over the same shown rows.
/// row that blends or is translucent must lie over the same shown rows, and over a lower row that
/// blends, with the same isolation.
fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0);
let level = |x: &Level, y: &Level| {
@@ -1248,10 +1501,26 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1);
// A row that blends or lets art through draws over the rows below it, read at one point.
let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0);
// A lower row that blends reads the art behind the object unless the object isolates its
// blending, so a row drawn over it reads a backdrop that depends on the isolation. A blending
// row at no opacity does not show, nor does a fill row without effects under an opaque solid
// Normal fill row without effects, which covers the same shape (a stroke reaches outside it).
let plain_fill = |i: &vectorcraft_doc::AppearanceItem| i.is_fill() && i.effects().is_empty();
let covers = |i: &vectorcraft_doc::AppearanceItem| {
plain_fill(i) && i.blend() == BlendMode::Normal && i.opacity() >= 1.0 && matches!(i.paint(), Paint::Solid { .. })
};
let over_blended = |d: &Drawn| {
over_rows(d)
&& d.lower
.iter()
.enumerate()
.any(|(k, i)| i.blend() != BlendMode::Normal && i.opacity() > 0.0 && !(plain_fill(i) && d.lower[k + 1..].iter().any(covers)))
};
row(a) == row(b)
&& (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower)
&& a.blend == b.blend
&& (row(a).is_none() || a.isolate == b.isolate)
&& (given_opacity || !below || !(over_blended(a) || over_blended(b)) || a.isolate == b.isolate)
&& (given_opacity || (total(a) - total(b)).abs() < 1e-6)
&& (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6)
&& la.len() == lb.len()
@@ -1263,8 +1532,9 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
/// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not
/// compared, since the given opacity takes their place; with `below` (the background is sampled),
/// objects in different translucent or blending groups or layers differ, since the art below each
/// such level is read with it hidden.
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> {
/// such level is read with it hidden. The color is None when the proxy has none (None, a pattern),
/// and the drawing is then the one a solid color in its place would have.
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Option<Color>, Drawn), String> {
let stroke = !s.fill_active;
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
if if stroke { stroke_mixed } else { fill_mixed } {
@@ -1320,20 +1590,28 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
} else {
drawing = source()?.unwrap_or_default();
}
let no_color = || "the active fill or stroke has no color: give `color`".to_string();
match if stroke { stroke_paint } else { fill } {
Paint::Solid { color, .. } => Ok((stained(s, color), drawing)),
let found = match if stroke { stroke_paint } else { fill } {
Paint::Solid { color, .. } => Some((color, drawing.clone())),
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color)
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity)))
}
Paint::Gradient(g) => {
let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color)
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity)))
}
Paint::None | Paint::Pattern { .. } => Err(no_color()),
}
Paint::None | Paint::Pattern { .. } => None,
};
Ok(match found {
Some((color, drawn)) => (Some(color), drawn),
None => (None, drawing),
})
}
/// The message for an active fill or stroke with no color to measure.
fn no_color() -> String {
"the active fill or stroke has no color: give `color`".to_string()
}
/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its
@@ -1398,19 +1676,21 @@ fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, stroke: bool) -> s
Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower })
}
/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
/// `color` itself otherwise.
fn stained(s: &Session, color: Color) -> Color {
let stain = s.active().and_then(|st| {
let sp = st.selection.symbol_part.as_ref()?;
st.selected_symbol_part()?;
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
});
match stain {
Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
None => color,
/// The color and amount a fill stains the picked object of a dynamic symbol instance with
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill), when
/// such an object is picked and its proxy shows a solid color. For a pick (`pick`), a proxy of None
/// or a pattern counts too, as the pick puts a solid color in its place.
fn stain_of(s: &Session, pick: bool) -> Option<(Color, f32)> {
let (fill, stroke) = s.proxy_paints();
match if s.fill_active { fill } else { stroke } {
Paint::Solid { .. } => {}
Paint::None | Paint::Pattern { .. } if pick => {}
_ => return None,
}
let st = s.active()?;
let sp = st.selection.symbol_part.as_ref()?;
st.selected_symbol_part()?;
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?).map(|(c, amount)| (c, amount.clamp(0.0, 1.0)))
}
/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and
@@ -1455,14 +1735,14 @@ fn enclosing(s: &Session, id: NodeId) -> Vec<Level> {
/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it;
/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer
/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing,
/// without artboards.
/// without artboards. Also whether the square's pixels are all one color.
fn color_below(
s: &Session,
rich_black: bool,
hide: Option<&Part>,
full: &[&Part],
scope: Option<&Part>,
) -> std::result::Result<([f32; 3], f32), String> {
) -> std::result::Result<(([f32; 3], f32), bool), String> {
super::has_selection(s)?;
let st = s.active().ok_or("no document open")?;
let ids = st.selection.objects.clone();
@@ -1591,8 +1871,10 @@ fn color_below(
let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts);
let px = img.pixels.as_chunks::<4>().0;
if px.is_empty() {
return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) });
return Ok((if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) }, true));
}
// Whether the pixels are one color, to within one step of 255 per channel.
let uniform = px.first().is_none_or(|first| px.iter().all(|p| p.iter().zip(first).all(|(a, b)| a.abs_diff(*b) <= 1)));
// The pixels are premultiplied: the average color is their sum over their alpha's.
let mut sum = [0.0f64; 4];
for p in px {
@@ -1602,10 +1884,10 @@ fn color_below(
}
let alpha = sum[3] / (px.len() as f64 * 255.0);
if alpha <= 0.0 {
return Ok(([0.0; 3], 0.0));
return Ok((([0.0; 3], 0.0), uniform));
}
let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32);
Ok((rgb, alpha as f32))
Ok(((rgb, alpha as f32), uniform))
}
/// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it.
@@ -602,6 +602,53 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
}
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a clipped PSD
/// file with many more pixels keeps its corners when the image is tiny: the new image's transform
/// is the old one scaled down to the new pixel size, which is invertible however small it is.
#[test]
fn replacing_a_tiny_distorted_image_by_a_large_clipped_psd_keeps_its_corners() {
let dir = vectorcraft_testkit::TempDir::new("psd-replace-tiny-distorted");
let plane = vec![255u8; 2000 * 2000];
let zero = vec![0u8; 2000 * 2000];
let big = psd(1, 3, (2000, 2000), 8, 3, &[], &triangle_resources(), &[], &raw(&[&plane, &zero, &zero]));
let cut = write_file(&dir, "big.psd", &big);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
let r = s
.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": [100, 100, 0.001, 0.001]}))
.unwrap();
let old = NodeId(r["ids"][0].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [old.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[100, 100], [100.001, 100.0001], [100.0009, 100.001], [99.9998, 100.0008]]})).unwrap();
assert!(s.doc().unwrap().doc.node(old).unwrap().is_distorted_image(), "the old image is distorted");
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
let r = s.execute("file.place", &json!({"path": cut, "replace": true})).unwrap();
let image = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
assert!(image.is_distorted_image());
assert_eq!(image.image_corners().unwrap(), corners);
}
/// Place with Replace of a clipped PSD file's image changed by Perspective Distort or Free Distort
/// by a DCS file keeps the image's corners: the DCS file's image fills them.
#[test]
fn replacing_a_distorted_clipped_psd_by_a_dcs_file_keeps_its_corners() {
let dir = vectorcraft_testkit::TempDir::new("psd-replace-distorted-dcs");
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
let dcs = write_file(&dir, "pic.eps", &crate::tests::dcs::two_plates());
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap();
let r = s.execute("file.place", &json!({"path": dcs, "replace": true})).unwrap();
let new = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
assert!(new.is_distorted_image(), "the DCS file's image takes the corners");
assert_eq!(new.image_corners().unwrap(), corners);
}
/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective
/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners,
/// a clip group of the old file's clipping path loses it when the new file names none, and a later
@@ -456,6 +456,30 @@ fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
}
}
/// A file placed with Replace over an image changed by Perspective Distort or Free Distort takes
/// its corners, and its slices cover what the corners put their part of the pixels on.
#[test]
fn slices_placed_over_a_distorted_image_follow_its_corners() {
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 10, 10])], &[]));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
s.execute("file.place", &json!({"name": "a.png", "dataBase64": b64(&png), "at": [100, 100]})).unwrap();
s.execute("object.distort", &json!({"corners": [[100, 100], [160, 104], [150, 140], [96, 136]]})).unwrap();
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "replace": true})).unwrap();
assert_eq!(r["slices"].as_array().map(Vec::len), Some(1), "{r}");
let d = &s.doc().unwrap().doc;
let image = d.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
assert!(image.is_distorted_image());
let vectorcraft_doc::NodeKind::Image(im) = &image.kind else { panic!("an image") };
// The top left quarter of the 20 × 20 px canvas.
let (w, h) = (f64::from(im.width) / 2.0, f64::from(im.height) / 2.0);
let want = image.image_map().unwrap().map_rect_bbox(Rect::new(0.0, 0.0, w, h)).unwrap();
let got = slices(&s)[0].0;
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
assert!(near(got.x0, want.x0) && near(got.y0, want.y0) && near(got.x1, want.x1) && near(got.y1, want.y1), "{got:?} vs {want:?}");
}
#[test]
fn linked_files_are_placed_without_their_slices() {
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
+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)]
+1 -1
View File
@@ -1314,7 +1314,7 @@ fn refill_distorted(
/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points
/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front
/// of it, and one past it to the far side. `None` when a point maps to no finite page point.
fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
pub(super) fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
let [[a, b, c], [d, e, f], [g, h, i]] = map.0;
let apply = |p: vectorcraft_geom::Point| {
let w = g * p.x + h * p.y + i;
+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 ----------
+84 -16
View File
@@ -57,7 +57,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes};
use vectorcraft_geom::{Affine, Point, Rect, shapes};
use vectorcraft_geom::{Affine, Homography, Point, Rect, shapes};
use vectorcraft_pdf::CropTo;
use super::fileio::{self, Format, RasterImage};
@@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place…",
["File"],
Some("Cmd+Shift+P"),
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 12 Line truncated
has_doc,
place
),
@@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
/// The transform that puts new art with the natural box `natural` where `old` is: an image's scale
/// and rotation relative to its 100% size (its resolution's) and its centre are kept (with
/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by
/// `image_xf`), also for an image alone in a clip group when the new art is a raster or DCS image, clipped by
/// its file's clipping path or not (`new_image`); other objects keep their centre.
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine {
let image = replace_measured(d, old, new_image);
@@ -663,7 +663,7 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
let full = Affine::scale_non_uniform(sx, sy);
let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0);
if im.xf.determinant().abs() > 1e-12 {
if Homography::affine_is_invertible(im.xf) {
return im.xf * full.inverse() * Affine::translate(centre - natural.center());
}
}
@@ -672,8 +672,8 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
}
/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an
/// image (`new_image`), except a DCS file's plates; else `old` itself.
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is a
/// raster or DCS image (`new_image`), except a DCS file's plates; else `old` itself.
fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node {
match &old.kind {
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
@@ -687,6 +687,60 @@ fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Nod
}
}
/// What Replace does when the image it measures, `old`, is distorted and the art placed is a
/// raster image or a DCS file's image (`art`): the transform that puts the new pixels on `old`'s
/// transform scaled to their size, as Update Links scales it, the corners the new image takes, and
/// the map from the art's natural box to the page through those corners, which a PSD file's slices
/// follow. `None` for other art, for an image with no pixels, and for corners the new pixels can't
/// fill ([`Node::set_image_corners`]).
fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homography)> {
let NodeKind::Image(im) = &old.kind else { return None };
let q = old.image_quad()?;
let (pixels, width, height) = match art {
Art::Image(img, _) => {
let (sx, sy) = pt_per_px(img.ppi);
(Affine::scale_non_uniform(sx, sy), img.width, img.height)
}
Art::Dcs(a) => (a.xf, a.img.width, a.img.height),
_ => return None,
};
if width == 0 || height == 0 || !Homography::affine_is_invertible(pixels) {
return None;
}
let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height));
let new = ImageObject { key: String::new(), width, height, xf, link: None, placement: Default::default(), pixels: None };
let mut probe = Node::new(old.id, NodeKind::Image(Box::new(new)));
probe.set_image_corners(q).ok()?;
let page = probe.image_map()?.checked_then_after(&Homography::from_affine(pixels.inverse()))?;
Some((xf * pixels.inverse(), q, page))
}
/// Placed raster `node` (an image, or an image in a clip group of its file's clipping path, as
/// [`build`] makes them) with the image's corners at `q`: the pixels fill them, and the clipping
/// path is drawn through them as the pixels are. `None` when the corners can't hold the image.
fn with_corners(mut node: Node, q: [Point; 4]) -> Option<Node> {
match &mut node.kind {
NodeKind::Image(_) => node.set_image_corners(q).ok()?,
NodeKind::Group { children, clip: true } => {
let [path, image] = &mut children[..] else { return None };
let image = Arc::make_mut(image);
let NodeKind::Image(im) = &image.kind else { return None };
if !Homography::affine_is_invertible(im.xf) {
return None;
}
// The clipping path in the image's pixels, which its transform placed on the page.
let to_pixels = im.xf.inverse();
image.set_image_corners(q).ok()?;
let map = image.image_map()?;
let NodeKind::Path { path: p, .. } = &mut Arc::make_mut(path).kind else { return None };
p.transform(to_pixels);
*p = super::links::warped(p, &map)?;
}
_ => return None,
}
Some(node)
}
/// `rect` fitted with `natural`'s aspect, centred.
fn fit(natural: Rect, r: Rect) -> Affine {
let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b);
@@ -846,19 +900,24 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
loaded.natural = Rect::from_origin_size(Point::ORIGIN, size);
}
let natural = loaded.natural;
// Replace keeps the transform of the image it measures (`replace_measured`), which a
// distortion's corners do not follow. Type, and any other object it measures, is placed by the
// bounds of what it replaces, so a distorted image there is not refused.
// Replace keeps the transform of the image it measures (`replace_measured`). When that image
// is distorted, a raster placed in its place takes its corners ([`distorted_replace`]); other
// art is refused. Type, and any other object it measures, is placed by the bounds of what it
// replaces, so a distorted image there is not refused.
let mut distorted = None;
let new_image = matches!(loaded.art, Art::Image(..) | Art::Dcs(..));
if let Some(o) = old_node
&& !is_text
{
let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
let image = replace_measured(&st.doc, o, new_image);
if image.is_distorted_image() {
return Err(super::xform::distorted_image_error(PLACE, image.id));
let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?;
distorted = Some((image.id, fit));
}
}
let m = match (old_node, rect) {
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
(Some(_), _) if let Some((_, (m, ..))) = distorted => m,
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, new_image),
(None, Some(r)) => fit(natural, r),
// Its artboard's bottom-left corner on the target's.
(None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)),
@@ -908,13 +967,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
if let Art::Dcs(a) = &loaded.art {
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
}
// A PSD file's slices move and scale with its art; one that would leave the canvas is left out.
// A PSD file's slices move and scale with its art, through a distorted image's corners when
// it takes them; one that would leave the canvas is left out.
let read_count = read_slices.len();
let slices: Slices = read_slices
.into_iter()
.filter_map(|(r, o)| {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c));
let placed = match distorted {
Some((_, (_, _, page))) => page.map_rect_bbox(r)?,
None => {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c))
}
};
super::slices::slice_rect_ok(placed).then_some((placed, o))
})
.collect();
@@ -924,7 +989,10 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
}
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
let node = transformed(build(d, loaded, link), m);
let mut node = transformed(build(d, loaded, link), m);
if let Some((old_image, (_, q, _))) = distorted {
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
}
let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default();
let (into, index) = match old {
Some(old) => {
+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
),
@@ -153,6 +153,7 @@ pub(super) const ALLOWED: &[&str] = &[
"charStyle.setAttrs",
"charStyle.unused",
"color.convert",
"color.format",
"color.gamutCheck",
"color.harmony",
"color.parse",
@@ -542,6 +543,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",
+7 -4
View File
@@ -18,7 +18,7 @@ use crate::script;
pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"];
/// The extensions of the scripts `script.run` takes as a file, in any case.
pub const RUN_EXTS: &[&str] = &["js", "jsx"];
pub const RUN_EXTS: &[&str] = &["js", "mjs", "jsx"];
/// Does `path` name a file `script.run` takes?
pub fn runs(path: &str) -> bool {
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event Line truncated
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler Line truncated
always,
run
),
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Installed Scripts",
[],
None,
"{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
"{} list the .js, .mjs and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
always,
list_installed
),
@@ -198,6 +198,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
let fuel = max_fuel(p)?;
let installed = switch_or(p, "installed", false, "script.run")?;
let module = switch_or(p, "module", script::include::module_script(path), "script.run")?;
let mut checked_real = None;
let text = match (path, source) {
(Some(""), None) => return Err(param("`path` is empty")),
@@ -213,7 +214,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
return Err(EngineError::Other(COMPILED.to_string()));
}
if !runs(path) {
return Err(param("`path` must name a .js or .jsx file"));
return Err(param("`path` must name a .js, .mjs or .jsx file"));
}
// One byte more than a script may have shows that the file is too large.
let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?;
@@ -242,6 +243,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
fuel,
locale,
answers,
module,
actions,
})
}
@@ -444,6 +446,7 @@ impl Session {
fuel,
locale,
answers: vec![],
module: script::include::module_script(path.to_str()),
actions: vec![],
};
let runs = self.script_runs;
+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.
+13 -5
View File
@@ -148,8 +148,11 @@ macro_rules! style_cmds {
};
}
/// The largest document `charStyle.load`, `paraStyle.load` and `textStyle.loadAll` read, in bytes.
pub const MAX_LOAD_BYTES: usize = 64 << 20;
/// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`.
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats; at most 64 MB) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
pub fn specs() -> Vec<CommandSpec> {
let mut v = style_cmds!(
@@ -1222,12 +1225,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result<Value> {
_ => "textStyle.loadAll".to_string(),
};
let path = str_param(p, "path");
let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
(Some(path), ..) => super::fileio::read_file(path)?,
(None, Some(text), _) => text.as_bytes().to_vec(),
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?,
let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20));
let bytes: std::borrow::Cow<[u8]> = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
(Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?.into(),
(None, Some(text), _) => text.as_bytes().into(),
(None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()),
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?.into(),
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
};
if bytes.len() > MAX_LOAD_BYTES {
return Err(too_large());
}
let file = str_param(p, "name").or(path).unwrap_or("Styles");
let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?;
if src.preview_only {
+21
View File
@@ -896,6 +896,27 @@ fn load_all_styles_loads_both_kinds_in_one_step() {
assert_eq!(s.doc().unwrap().doc, before);
}
/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit.
#[test]
fn loading_refuses_a_file_larger_than_64_mb() {
let (mut s, _) = session_with_text("Title");
let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Big.vectorcraft");
std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap();
let before = s.doc().unwrap().doc.clone();
let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()}));
std::fs::remove_dir_all(&dir).ok();
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8);
let r = s.execute("paraStyle.load", &json!({"dataBase64": b64}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
let text = " ".repeat(MAX_LOAD_BYTES + 1);
let r = s.execute("textStyle.loadAll", &json!({"data": text}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
assert_eq!(s.doc().unwrap().doc, before);
}
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or
/// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped.
#[test]
+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]
+6
View File
@@ -127,6 +127,12 @@ impl HistoryEntry {
self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str()))
}
/// A number no other step takes ([`History::step`]). Undo and Redo make the step they move
/// with a new number, and so does an edit merged into the newest step.
pub fn serial(&self) -> u64 {
self.serial
}
/// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the
/// document before the undo, whose next state is now `now` (that step's document). Its figures
/// are that step's the other way round when `doc` is still the document they were taken
+4 -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;
@@ -373,6 +373,9 @@ pub struct Session {
pub(crate) startup_failures: Vec<(String, String)>,
/// Each open document's highest next id a run has seen, by [`DocState::uid`].
pub(crate) script_high_water: std::collections::HashMap<u64, u64>,
/// The styles the steps of a batch a script runs removed or renamed and the documents they
/// reverted ([`script::note_style_lists`]).
pub(crate) script_style_trail: script::StyleTrail,
/// While a slice of a script runs in this session.
pub(crate) script_in_run: bool,
/// The desktop app supplies each window by (document uid, runtime window identity) while a
+44 -5
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
@@ -221,19 +224,24 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
return f(h);
}
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
let styles = text::styles::mark(h);
let mark = h.growth_mark();
h.dom.saving.set(true);
let r = f(h);
h.dom.saving.set(false);
let mut s = h.session.borrow_mut();
if r.is_ok() {
save.keep(&mut s);
} else {
{
let mut s = h.session.borrow_mut();
if r.is_ok() {
save.keep(&mut s);
return r;
}
h.put_growth_back(mark);
if !save.restore(&mut s) {
return Err(HostError::Abort(HISTORY_LOST.to_string()));
}
}
// Style objects are put back with the documents.
text::styles::put_back(h, styles);
r
}
@@ -871,6 +879,11 @@ fn on_doc<T>(
Ok(v)
}
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
pub(super) fn after_kept_command(h: &Host) {
text::styles::after_command(h);
}
/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
/// paths stay valid through the change ([`paths::see_all_points`]).
@@ -908,6 +921,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 {
@@ -1854,6 +1889,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()));
@@ -2436,7 +2472,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
}
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
/// The error of `move` and `duplicate` given an object of another document.
pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available";
@@ -2786,6 +2822,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", &[])),
]);
@@ -2867,6 +2905,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
("toString", method(l, doc_to_string), returns("string", &[])),
]);
document.extend(defaults::document_members(l));
document.extend(text::styles::doc_members(l));
document.extend(
["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)),
);
+5 -2
View File
@@ -50,6 +50,7 @@ use super::{
};
use crate::{DocState, Document, NodeId, NodeKind};
pub(super) mod styles;
pub(super) mod threads;
/// The error of a text range, or of a collection of one, whose frame's text changed other than
@@ -201,6 +202,8 @@ pub(in crate::script) struct TextState {
made: Cell<u64>,
/// The span of each range object, by its number, whose `length` the script set.
resized: RefCell<HashMap<u64, (usize, usize, u64)>>,
/// The styles the run's style objects name.
styles: styles::StyleState,
}
fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> {
@@ -1680,14 +1683,13 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
range.extend(attr_members(l));
range.push(threads::range_member(l));
range.extend(para_members(l));
range.extend(styles::range_members(l));
range.extend(
[
"lines",
"insertionPoints",
"textRanges",
"kerning",
"characterStyles",
"paragraphStyles",
"textSelection",
"changeCaseTo",
"select",
@@ -1786,6 +1788,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
None,
),
];
out.extend(styles::classes(l));
out.extend(stories);
out
}
+802
View File
@@ -0,0 +1,802 @@
//! Character and paragraph styles in the script object model: `document.characterStyles` and
//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text
//! of a `TextRange` uses, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/> describe them.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A document's collection lists its Normal style first, then its other styles in the order the
//! panel lists them.
//! - A style object names its style for the rest of the run, also after the script renames it
//! through `name`. Once the style is removed, or renamed or removed other than through the object
//! model, or its document is closed or reverted with File › Revert, every member throws
//! `Stale style`; a style added later under the same name is another style.
//! - A style name is trimmed, and must then be 1 to 256 characters long with no control
//! characters.
//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the
//! style does not set. Setting one redefines the style: text in the style takes the new value
//! where it had the style's old one and keeps its other changes.
//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words
//! or paragraphs of one, in the style's document. A character style styles exactly that text and
//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches.
//! `clearingOverrides` left out is false; true resets the text to the Normal style first.
//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or
//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in
//! no other style. They do not add or remove styles.
//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its
//! look and is in the Normal style after.
//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`,
//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read.
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef};
use vectorcraft_geom::Point;
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
use super::{
ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref,
function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text,
text_of, this_range, typename_of, usize_of, whole_span, with_doc,
};
use crate::DocState;
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs};
use crate::script::dom::{Described, returns, typed};
/// The error of a style object whose style is gone.
pub const STALE_STYLE: &str = "Stale style";
/// The longest style name, in characters, after trimming.
pub const MAX_STYLE_NAME: usize = 256;
/// The most styles one run's style objects name.
pub const MAX_HELD: usize = 4096;
/// A style that a run's style objects name: its document and the document's revert count then, its
/// kind and its name now.
struct Slot {
uid: u64,
reverts: u64,
para: bool,
name: String,
live: bool,
}
/// A document's uid and its character and paragraph style lists when the slots were last checked.
type Seen = (u64, Shared<Vec<TextStyleDef>>, Shared<Vec<TextStyleDef>>);
/// The styles a run's style objects name; an object holds its slot's number.
#[derive(Default)]
pub(super) struct StyleState {
slots: RefCell<Vec<Slot>>,
seen: RefCell<Vec<Seen>>,
}
/// Marks stale each style object whose style the command just run removed or renamed, so a style
/// removed and made again under its name by later commands, or by later steps of the same batch,
/// is another style. A document whose style lists did not change is not checked again. A live
/// slot's style was in its document's list when the command started, so a step that removed or
/// renamed it is in the trail's removed names.
pub(in crate::script) fn after_command(h: &Host) {
let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail);
let mut slots = h.dom.text.styles.slots.borrow_mut();
if !slots.iter().any(|s| s.live) {
return;
}
for slot in slots.iter_mut().filter(|x| x.live) {
if trail.reverted.contains(&slot.uid)
|| (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone())))
{
slot.live = false;
}
}
let s = h.session.borrow();
let mut seen = h.dom.text.styles.seen.borrow_mut();
seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid));
for st in s.documents() {
let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles));
if same {
continue;
}
seen.retain(|(uid, ..)| *uid != st.uid);
seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone()));
for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) {
slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name);
}
}
for slot in slots.iter_mut().filter(|x| x.live) {
if !s.documents().iter().any(|d| d.uid == slot.uid) {
slot.live = false;
}
}
}
/// The style objects' state when a savepoint was taken: each slot's name and whether it was
/// live, and the style lists last checked.
pub(in crate::script) struct Mark {
slots: Vec<(String, bool)>,
seen: Vec<Seen>,
}
/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored.
pub(in crate::script) fn mark(h: &Host) -> Mark {
let styles = &h.dom.text.styles;
let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect();
Mark { slots, seen: styles.seen.borrow().clone() }
}
/// Puts the style objects back as they were at `mark`, after the documents were put back to the
/// savepoint taken with it. A slot added since then stays live only while its document has the
/// style and no older live slot names it.
pub(in crate::script) fn put_back(h: &Host, mark: Mark) {
let styles = &h.dom.text.styles;
let mut slots = styles.slots.borrow_mut();
let kept = mark.slots.len();
for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) {
slot.name = name;
slot.live = live;
}
let s = h.session.borrow();
for i in kept..slots.len() {
let (older, newer) = slots.split_at_mut(i);
let Some(slot) = newer.first_mut() else { break };
let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name);
slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name));
}
*styles.seen.borrow_mut() = mark.seen;
}
fn normal(para: bool) -> &'static str {
if para { NORMAL_PARA } else { NORMAL_CHAR }
}
fn cmd(para: bool, verb: &str) -> String {
format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" })
}
fn style_class(para: bool) -> &'static str {
if para { "ParagraphStyle" } else { "CharacterStyle" }
}
fn list_class(para: bool) -> &'static str {
if para { "ParagraphStyles" } else { "CharacterStyles" }
}
fn defs(st: &DocState, para: bool) -> &Vec<TextStyleDef> {
if para { &st.doc.para_styles } else { &st.doc.char_styles }
}
/// The document's style names of a kind, the Normal style first.
fn names(st: &DocState, para: bool) -> Vec<String> {
let mut out = vec![normal(para).to_string()];
out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para)));
out
}
fn has_style(st: &DocState, para: bool, name: &str) -> bool {
name == normal(para) || defs(st, para).iter().any(|d| d.name == name)
}
fn stale() -> HostError {
HostError::Error(STALE_STYLE.into())
}
fn held_too_many() -> HostError {
HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))
}
/// The style object for the style `name` of the document `uid`: the same slot as every other
/// object naming it in this run.
fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer {
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
let mut slots = h.dom.text.styles.slots.borrow_mut();
let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) {
Some(i) => i,
None => {
if slots.len() >= MAX_HELD {
return Err(held_too_many());
}
slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true });
slots.len() - 1
}
};
Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)]))
}
/// A style a style object names.
struct Style {
doc: Doc,
para: bool,
slot: usize,
name: String,
}
/// The style `d` names, when it is an object of one of `classes` (with the kind each names).
fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result<Style, HostError> {
let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para)));
let Some((handle, para)) = found else {
return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0))));
};
let [run, uid, slot] = handle.as_slice() else { return Err(stale()) };
let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?;
let slot = usize_of(*slot).ok_or_else(stale)?;
let mut slots = h.dom.text.styles.slots.borrow_mut();
let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?;
if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) {
s.live = false;
return Err(stale());
}
Ok(Style { doc, para, slot, name: s.name.clone() })
}
fn this_style(h: &Host, a: &[Data]) -> std::result::Result<Style, HostError> {
style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)])
}
/// Marks the slots of the styles `names` of the document `uid` as removed.
fn forget(h: &Host, uid: u64, para: bool, names: &[String]) {
for s in h.dom.text.styles.slots.borrow_mut().iter_mut() {
if s.uid == uid && s.para == para && names.contains(&s.name) {
s.live = false;
}
}
}
/// A style name a script gave, trimmed.
fn style_name(v: &Data) -> std::result::Result<String, HostError> {
let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) };
if s.len() > super::super::MAX_TEXT_BYTES {
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
}
let t = s.trim();
if t.is_empty() {
return Err(HostError::Range("a style name must not be empty".into()));
}
if t.chars().count() > MAX_STYLE_NAME {
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
}
if t.chars().any(char::is_control) {
return Err(HostError::Range("a style name must not hold control characters".into()));
}
Ok(t.to_string())
}
/// Runs the style command `verb` of the kind on the document of `doc`.
fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result<Data, HostError> {
on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params))
}
// ---- CharacterStyle and ParagraphStyle ----
fn style_name_get(h: &Host, a: &[Data]) -> Answer {
Ok(text(this_style(h, a)?.name))
}
/// `name = …`: renames the style; the Normal style keeps its name.
fn style_name_set(h: &Host, a: &[Data]) -> Answer {
let style = this_style(h, a)?;
let to = style_name(arg(a, 1))?;
if to == style.name {
return Ok(Data::Undefined);
}
if style.name == normal(style.para) {
return Err(HostError::Error(format!("{} cannot be renamed", style.name)));
}
if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) {
return Err(HostError::Error(format!("a style named {to} already exists")));
}
run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?;
forget(h, style.doc.uid, style.para, std::slice::from_ref(&to));
if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) {
s.name = to;
s.live = true;
}
Ok(Data::Undefined)
}
fn style_parent(h: &Host, a: &[Data]) -> Answer {
Ok(doc_ref(h, this_style(h, a)?.doc.uid))
}
fn style_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text(style_class(this_style(h, a)?.para)))
}
fn attributes(h: &Host, a: &[Data], class: &str) -> Answer {
let style = this_style(h, a)?;
Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)]))
}
fn style_character_attributes(h: &Host, a: &[Data]) -> Answer {
attributes(h, a, "CharacterStyleAttributes")
}
fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer {
attributes(h, a, "ParagraphStyleAttributes")
}
/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after.
fn style_remove(h: &Host, a: &[Data]) -> Answer {
let style = this_style(h, a)?;
if style.name == normal(style.para) {
return Err(HostError::Error(format!("{} cannot be removed", style.name)));
}
run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?;
forget(h, style.doc.uid, style.para, &[style.name]);
Ok(Data::Undefined)
}
/// The text a style is applied to: a text range, a text frame, or the characters, words or
/// paragraphs of one.
fn target_span(h: &Host, d: &Data) -> std::result::Result<Span, HostError> {
if handle_of(d, "TextFrame").is_some() {
return Ok(whole_span(h, item_of(h, d)?)?.1);
}
const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"];
if !TEXT.iter().any(|c| handle_of(d, c).is_some()) {
return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into()));
}
span_of(h, d, &TEXT)
}
/// `applyTo(textItem, clearingOverrides?)`.
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
let style = this_style(h, a)?;
let target = target_span(h, arg(a, 1))?;
let clear = match arg(a, 2) {
Data::Undefined => false,
Data::Bool(b) => *b,
_ => return Err(HostError::Type("clearingOverrides must be true or false".into())),
};
if target.item.doc.uid != style.doc.uid {
return Err(HostError::Error("the text is in another document than the style".into()));
}
let (index, s, e, _) = resolve(h, target)?;
h.charge_call(16 + (e - s) as u64)?;
let (start, end) = if style.para {
let (_, ba, bb) = para_range(&index, s, e);
(ba, bb)
} else {
// An empty range inside text changes nothing; empty text takes the style on its runs.
if s == e && index.len() > 0 {
return Ok(Data::Undefined);
}
(index.byte(s, false), index.byte(e, true))
};
let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end});
run(h, style.doc, style.para, "apply", &p)?;
Ok(Data::Undefined)
}
// ---- the attributes of a style ----
/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets.
const CHAR_KEYS: [(&str, &str); 11] = [
("size", "size"),
("leading", "leading"),
("tracking", "tracking"),
("baselineShift", "baseline_shift"),
("hScale", "h_scale"),
("vScale", "v_scale"),
("rotation", "rotation"),
("underline", "underline"),
("strikethrough", "strikethrough"),
("font", "font_family"),
("style", "font_style"),
];
/// The script's `Justification` members and the alignments a paragraph style stores.
const JUSTIFY: [(&str, &str); 7] = [
("LEFT", "Left"),
("CENTER", "Center"),
("RIGHT", "Right"),
("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"),
("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"),
("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"),
("FULLJUSTIFY", "JustifyAll"),
];
/// The style an attributes object belongs to and the attributes it sets.
fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map<String, Value>), HostError> {
let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" };
let style = style_of(h, arg(a, 0), &[(class, para)])?;
let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?;
Ok((style, attrs))
}
fn char_value(h: &Host, attr: Attr, m: &Map<String, Value>) -> Data {
let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num);
let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool);
match attr {
Attr::Size => n("size"),
Attr::Leading => n("leading"),
Attr::AutoLeading => match m.get("leading") {
Some(Value::Null) => Data::Bool(true),
Some(v) if v.is_number() => Data::Bool(false),
_ => Data::Undefined,
},
Attr::Tracking => n("tracking"),
Attr::BaselineShift => n("baseline_shift"),
Attr::HorizontalScale => n("h_scale"),
Attr::VerticalScale => n("v_scale"),
Attr::Rotation => n("rotation"),
Attr::Underline => b("underline"),
Attr::StrikeThrough => b("strikethrough"),
Attr::TextFont => match m.get("font_family").and_then(Value::as_str) {
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
None => Data::Undefined,
},
}
}
/// The `typename` of a style's `characterAttributes`, which throws once the style is gone.
fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer {
attrs_of(h, a, false)?;
Ok(text("CharacterAttributes"))
}
/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone.
fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer {
attrs_of(h, a, true)?;
Ok(text("ParagraphAttributes"))
}
fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer {
let (_, m) = attrs_of(h, a, false)?;
Ok(char_value(h, attr, &m))
}
/// Redefines the style with `attrs`, unless they are what it has.
fn redefine(h: &Host, style: &Style, old: &Map<String, Value>, attrs: Map<String, Value>) -> Answer {
if attrs == *old {
return Ok(Data::Undefined);
}
run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?;
Ok(Data::Undefined)
}
fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
let (style, old) = attrs_of(h, a, false)?;
// `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph
// with the default justification.
let base = CharStyle::default();
let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size);
let leading = old.get("leading").and_then(Value::as_f64);
let sample = CharStyle { size, leading, ..base };
let t = TextObject::point(Point::default(), "", sample.clone());
let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?;
let mut attrs = old.clone();
for (k, v) in param.as_object().into_iter().flatten() {
let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue };
let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() };
attrs.insert((*key).to_string(), v);
}
redefine(h, &style, &old, attrs)
}
fn para_key(attr: ParaAttr) -> &'static str {
match attr {
ParaAttr::Justification => "justify",
ParaAttr::FirstLineIndent => "first_line_indent",
ParaAttr::LeftIndent => "left_indent",
ParaAttr::RightIndent => "right_indent",
ParaAttr::SpaceBefore => "space_before",
ParaAttr::SpaceAfter => "space_after",
}
}
fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer {
let (_, m) = attrs_of(h, a, true)?;
let v = m.get(para_key(attr));
Ok(match attr {
ParaAttr::Justification => match v.and_then(Value::as_str) {
Some("Auto") => text("Justification.LEFT"),
Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))),
None => Data::Undefined,
},
_ => v.and_then(Value::as_f64).map_or(Data::Undefined, num),
})
}
fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
let (style, old) = attrs_of(h, a, true)?;
let (_, _, wants) = para_param(attr, name, arg(a, 1))?;
let value = match (&wants, attr) {
(Data::String(s), ParaAttr::Justification) => {
let m = s.strip_prefix("Justification.").unwrap_or(s);
let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j);
json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?)
}
(Data::Number(n), _) => json!(n),
_ => return Err(HostError::Type(format!("{name} must be a finite number"))),
};
let mut attrs = old.clone();
attrs.insert(para_key(attr).to_string(), value);
redefine(h, &style, &old, attrs)
}
/// The body of a member that captures what it reads or sets.
type Body = Rc<dyn Fn(&Host, &[Data]) -> Answer>;
/// Members whose getter and setter each charge the call, as [`function`] does.
fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember {
let wrap = |f: Body| -> HostFunction {
let l = link.clone();
Rc::new(move |a: Vec<Data>| {
let h = super::super::current(&l)?;
h.charge_call(16 + a.iter().map(super::super::data_size).sum::<u64>())?;
f(&h, &a)
})
};
HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) }
}
fn char_members(link: &Link) -> Vec<Described> {
ATTRS
.iter()
.map(|&(name, attr)| {
let data_type = match attr {
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
Attr::TextFont => "TextFont",
_ => "number",
};
(name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)), typed(data_type))
})
.collect()
}
fn para_members(link: &Link) -> Vec<Described> {
PARA_ATTRS
.iter()
.map(|&(name, attr)| {
let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" };
(name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)), typed(data_type))
})
.collect()
}
// ---- CharacterStyles and ParagraphStyles ----
/// What a collection of styles lists: a document's styles, or those a text range uses.
enum Of {
Doc(Doc),
Range(Span),
}
fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> {
let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) {
(Some(_), _) => false,
(_, Some(_)) => true,
_ => return Err(HostError::Type("this is not a CharacterStyles".into())),
};
let class = list_class(para);
let len = handle_of(d, class).map_or(0, |v| v.len());
Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para))
}
/// The document and the names of the styles a collection lists.
fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec<String>), HostError> {
match of {
Of::Doc(doc) => {
let names = with_doc(h, *doc, |_, st| names(st, para));
h.charge_call(names.len() as u64)?;
Ok((*doc, names))
}
Of::Range(r) => {
let (index, s, e, _) = resolve(h, *r)?;
let used = with_doc(h, r.item.doc, |_, st| {
let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
let used: Vec<Option<String>> = if para {
let (paras, _, _) = para_range(&index, s, e);
paras.map(|i| t.para_at(i).style_name.clone()).collect()
} else {
styles_in(t, index.byte(s, false), index.byte(e, true), false)?.into_iter().map(|(c, _)| c.style_name).collect()
};
h.charge_call(used.len() as u64)?;
let mut out: Vec<String> = Vec::new();
for n in used {
let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string());
if !out.contains(&n) {
out.push(n);
}
}
if out.is_empty() {
out.push(normal(para).to_string());
}
Ok::<_, HostError>(out)
})?;
Ok((r.item.doc, used))
}
}
}
fn list_length(h: &Host, a: &[Data]) -> Answer {
let (of, para) = list_of(h, arg(a, 0))?;
Ok(num(float(listed(h, &of, para)?.1.len() as u64)))
}
fn list_parent(h: &Host, a: &[Data]) -> Answer {
let (of, _) = list_of(h, arg(a, 0))?;
match of {
Of::Doc(doc) => Ok(doc_ref(h, doc.uid)),
Of::Range(r) => {
let (_, s, e, stamp) = resolve(h, r)?;
Ok(range_ref(h, r.item, s, e, stamp, "TextRange"))
}
}
}
fn list_at(h: &Host, a: &[Data]) -> Answer {
let (of, para) = list_of(h, arg(a, 0))?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
let found = match &of {
Of::Doc(doc) => with_doc(h, *doc, |_, st| match i {
0 => Some(normal(para).to_string()),
_ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(),
})
.map(|n| (*doc, n)),
Of::Range(_) => {
let (doc, names) = listed(h, &of, para)?;
names.get(i).cloned().map(|n| (doc, n))
}
};
match found {
Some((doc, name)) => style_ref(h, doc.uid, para, &name),
None => Ok(Data::Undefined),
}
}
fn list_by_name(h: &Host, a: &[Data]) -> Answer {
let (of, para) = list_of(h, arg(a, 0))?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
if name.len() > super::super::MAX_TEXT_BYTES {
return Err(HostError::Range("the name is too long".into()));
}
let (doc, names) = listed(h, &of, para)?;
match names.iter().find(|n| *n == name) {
Some(n) => style_ref(h, doc.uid, para, n),
None => Err(HostError::Error(NOT_FOUND.into())),
}
}
fn list_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => list_by_name(h, a),
Data::Number(_) => match list_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
_ => Err(HostError::Type("give a name or an index".into())),
}
}
/// The document of a document's collection; a range's collection cannot be changed.
fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> {
match list_of(h, arg(a, 0))? {
(Of::Doc(doc), para) => Ok((doc, para)),
(Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())),
}
}
/// `add(name)`: a new style that sets no attributes.
fn list_add(h: &Host, a: &[Data]) -> Answer {
let (doc, para) = changed_doc(h, a)?;
let name = style_name(arg(a, 1))?;
if with_doc(h, doc, |_, st| has_style(st, para, &name)) {
return Err(HostError::Error(format!("a style named {name} already exists")));
}
// The new style needs a slot of its own: a run that names as many styles as it may adds none.
if h.dom.text.styles.slots.borrow().len() >= MAX_HELD {
return Err(held_too_many());
}
run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?;
// An object of a removed style of this name stays stale.
forget(h, doc.uid, para, std::slice::from_ref(&name));
style_ref(h, doc.uid, para, &name)
}
/// `removeAll()`: deletes every style but the Normal style, in one command.
fn list_remove_all(h: &Host, a: &[Data]) -> Answer {
let (doc, para) = changed_doc(h, a)?;
let gone: Vec<String> = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect();
if gone.is_empty() {
return Ok(Data::Undefined);
}
run(h, doc, para, "delete", &json!({"names": gone}))?;
forget(h, doc.uid, para, &gone);
Ok(Data::Undefined)
}
fn doc_char_styles(h: &Host, a: &[Data]) -> Answer {
let doc = doc_of(h, arg(a, 0), "Document")?;
Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)]))
}
fn doc_para_styles(h: &Host, a: &[Data]) -> Answer {
let doc = doc_of(h, arg(a, 0), "Document")?;
Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)]))
}
fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer {
let r = this_range(h, a)?;
let (_, s, e, stamp) = resolve(h, r)?;
Ok(range_ref(h, r.item, s, e, stamp, list_class(para)))
}
fn range_char_styles(h: &Host, a: &[Data]) -> Answer {
range_styles(h, a, false)
}
fn range_para_styles(h: &Host, a: &[Data]) -> Answer {
range_styles(h, a, true)
}
/// `document.characterStyles` and `document.paragraphStyles`.
pub(in crate::script) fn doc_members(l: &Link) -> Vec<Described> {
named(vec![
("characterStyles", get(l, doc_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
("paragraphStyles", get(l, doc_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
])
}
/// `TextRange.characterStyles` and `TextRange.paragraphStyles`.
pub(super) fn range_members(l: &Link) -> Vec<Described> {
named(vec![
("characterStyles", get(l, range_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
("paragraphStyles", get(l, range_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
])
}
/// The style classes.
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
let style = |para: bool| {
let mut members = named(vec![
("typename", get(l, style_typename), typed("string")),
("name", property(l, style_name_get, style_name_set), typed("string")),
("parent", get(l, style_parent), typed("Document")),
("applyTo", method(l, style_apply_to), returns("undefined", &[("textItem", "*"), ("clearingOverrides", "boolean")])),
("remove", method(l, style_remove), returns("undefined", &[])),
]);
if para {
members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes), typed("ParagraphStyleAttributes")));
members.push(super::super::later(l, "ParagraphStyle", "characterAttributes"));
} else {
members.push(("characterAttributes".into(), get(l, style_character_attributes), typed("CharacterStyleAttributes")));
}
class(style_class(para), None, members, None)
};
let list = |para: bool| {
let name = list_class(para);
let item = style_class(para);
class(
name,
None,
named(vec![
("typename", typename_of(name), typed("string")),
("length", get(l, list_length), typed("number")),
("parent", get(l, list_parent), typed("*")),
("index", method(l, list_index), returns(item, &[("itemKey", "*")])),
("getByName", method(l, list_by_name), returns(item, &[("name", "string")])),
("add", method(l, list_add), returns(item, &[("name", "string")])),
("removeAll", method(l, list_remove_all), returns("undefined", &[])),
]),
Some(function(l, list_at)),
)
};
let mut chars = named(vec![("typename", get(l, attrs_typename_char), typed("string"))]);
chars.extend(char_members(l));
let mut paras = named(vec![("typename", get(l, attrs_typename_para), typed("string"))]);
paras.extend(para_members(l));
vec![
style(false),
style(true),
list(false),
list(true),
class("CharacterStyleAttributes", None, chars, None),
class("ParagraphStyleAttributes", None, paras, None),
]
}
+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);
+142 -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 };
@@ -1297,6 +1319,7 @@ fn note_ids(s: &mut Session) {
/// it, for a result that cannot cross to the script.
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<Savepoint>)> {
raise_ids(s);
s.script_style_trail = StyleTrail::start(s);
let mutating = waits_for_tool_edit(id);
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back.
let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id));
@@ -1344,6 +1367,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
Ok((v, objects, bytes, save))
}
Err(e) => {
s.script_style_trail = StyleTrail::default();
if let Some(save) = save
&& !save.restore(s)
{
@@ -1424,12 +1448,77 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
}
}
dom::after_command(host, before);
// Style objects follow only a command that is kept.
if crossed.is_ok() {
dom::see_points(host);
dom::after_kept_command(host);
} else {
session.borrow_mut().script_style_trail = StyleTrail::default();
}
crossed.map(|data| (data, value))
}
/// A document's uid, revert count, and character and paragraph style lists.
pub(crate) type StyleLists =
(u64, u64, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>);
/// What the steps of a command a script runs did to the documents' style lists
/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step
/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the
/// documents a step reverted.
#[derive(Default)]
pub(crate) struct StyleTrail {
lists: Vec<StyleLists>,
pub(crate) gone: std::collections::HashSet<(u64, bool, String)>,
pub(crate) reverted: Vec<u64>,
}
impl StyleTrail {
/// A trail that starts from the documents' style lists now.
fn start(s: &Session) -> Self {
let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect();
StyleTrail { lists, ..Default::default() }
}
}
/// After a step of a batch a script runs: notes the styles the step removed or renamed and the
/// documents it reverted, so the style objects see a style the batch removed and made again under
/// its name as another style ([`dom::after_kept_command`]). The trail keeps one copy of each open
/// document's lists, however many steps change them.
pub(crate) fn note_style_lists(s: &mut Session) {
let trail = &mut s.script_style_trail;
trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid));
for st in &s.docs {
let (c, p) = (&st.doc.char_styles, &st.doc.para_styles);
let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else {
trail.lists.push((st.uid, st.reverts, c.clone(), p.clone()));
continue;
};
if last.1 != st.reverts {
if !trail.reverted.contains(&st.uid) {
trail.reverted.push(st.uid);
}
} else {
for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] {
if vectorcraft_doc::Shared::ptr_eq(old, new) {
continue;
}
let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect();
for d in old.iter().filter(|d| !names.contains(d.name.as_str())) {
trail.gone.insert((st.uid, para, d.name.clone()));
}
}
}
*last = (st.uid, st.reverts, c.clone(), p.clone());
}
}
/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]).
#[cfg(test)]
pub(crate) fn retained_style_lists(s: &Session) -> usize {
s.script_style_trail.lists.len()
}
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
/// of a crossing throws a `RangeError`.
fn vc_document(host: &Host) -> std::result::Result<Data, HostError> {
@@ -1535,6 +1624,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![
@@ -1549,9 +1639,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()));
};
@@ -1565,7 +1663,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),
@@ -1675,6 +1773,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 {
@@ -2092,7 +2206,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,
@@ -2123,9 +2249,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.
@@ -2194,6 +2319,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()),
@@ -2258,7 +2384,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
@@ -189,6 +189,7 @@ impl Session {
startup_loading: None,
startup_failures: vec![],
script_high_water: Default::default(),
script_style_trail: Default::default(),
script_in_run: false,
window_views: vec![],
script_copy_first: cfg!(target_arch = "wasm32"),
+3
View File
@@ -129,6 +129,9 @@ impl Session {
self.execute_spec(spec, id, params)
};
self.reading = outer;
if self.script_in_run && self.depth > 0 && r.is_ok() {
crate::script::note_style_lists(self);
}
r
}
+33 -1
View File
@@ -49,7 +49,7 @@ mod css;
mod curvature_circle;
mod cut;
mod dashalign;
mod dcs;
pub(super) mod dcs;
mod delete_keeps_joined;
mod distort;
mod docsetup;
@@ -186,8 +186,10 @@ mod script_engines;
mod script_folder;
mod script_include;
mod script_io;
mod script_modules;
mod script_run;
mod script_scriptui;
mod script_styles;
mod script_tags;
mod script_text;
mod script_threads;
@@ -5172,6 +5174,36 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() {
assert!(!s.doc().unwrap().selection.contains(b));
}
/// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With
/// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that
/// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked
/// adds its corner. A Ctrl/Cmd-click (the Selection tool, lent) leaves the picks as they are.
#[test]
fn corner_widgets_pick_corners_across_paths_through_the_session() {
let mut s = session();
let v = ViewInfo::default();
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
let all = json!([[0, 0], [0, 1], [0, 2], [0, 3]]);
let start = json!({"items": [{"id": a.0, "anchors": [[0, 0]]}, {"id": b.0, "anchors": all}]});
s.select_tool("directSelection", v).unwrap();
let click = |s: &mut Session, x: f64, y: f64, mods: vectorcraft_tools::Mods| {
s.execute("select.anchorsMany", &start).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, x, y).with_mods(mods), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, x, y).with_mods(mods), v).unwrap();
let sel = &s.doc().unwrap().selection;
assert!(sel.contains(a) && sel.contains(b), "both stay selected");
(sel.partial(a).cloned(), sel.partial(b).cloned())
};
let shift = vectorcraft_tools::Mods { shift: true, ..Default::default() };
// The top-right widget of b.
assert_eq!(click(&mut s, 390.0, 110.0, shift), (Some([(0, 0)].into()), Some([(0, 0), (0, 2), (0, 3)].into())));
// The top-right widget of a, not picked.
assert_eq!(click(&mut s, 190.0, 110.0, shift), (Some([(0, 0), (0, 1)].into()), None));
let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() };
assert_eq!(click(&mut s, 190.0, 110.0, cmd), (Some([(0, 0)].into()), None), "a Ctrl/Cmd-click leaves the picks");
}
#[test]
fn path_commands_reject_bad_anchors_before_modifying_geometry() {
let mut s = session();
+333
View File
@@ -776,6 +776,33 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() {
let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap();
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}");
// The fix is the color to store: the stain mixes it half way to black again, and the result
// just meets AA against white.
let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap();
assert_eq!(r["normalText"]["aa"], false, "{r}");
let fix = fix_color(&r["fix"]["aa"]);
let drawn = fix.lerp(&vectorcraft_color::Color::BLACK, 0.5).to_rgb_uncalibrated();
let got = vectorcraft_color::wcag::contrast_ratio(drawn, [1.0; 3]);
assert!((4.5..4.57).contains(&got), "{fix:?} draws {drawn:?}: {got}");
}
/// A pick for a picked symbol object with a fill of None puts a solid color there, which the
/// instance's stain mixes like any other, so the Color Wheel's contrast lines measure it stained.
#[test]
fn a_pick_for_a_picked_symbol_object_with_no_fill_is_measured_with_the_stain() {
let mut s = picked_symbol_part();
let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance;
s.active_mut().unwrap().selection.symbol_part = None;
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap();
s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
s.execute("paint.setFill", &json!({"none": true})).unwrap();
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({"against": "#000000", "opacity": 100})).unwrap();
let cms = vectorcraft_color::cms::active();
let white = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(1.0, 1.0, 1.0)));
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
assert!((white - want).abs() < 1e-3, "a white pick stained half way to black: {white} against {want}");
}
#[test]
@@ -877,3 +904,309 @@ fn a_fill_of_none_has_no_color_to_measure() {
assert!(e.contains("has no color"), "{e}");
assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok());
}
fn fix_color(v: &Value) -> vectorcraft_color::Color {
crate::cmd::color_value(v).unwrap_or_else(|| panic!("not a color: {v}"))
}
fn oklch_hue(c: &vectorcraft_color::Color) -> f64 {
let [_, a, b] = vectorcraft_color::libraries::to_oklab(c);
b.atan2(a).to_degrees()
}
#[test]
fn a_failing_color_answers_the_closest_passing_color_of_its_hue() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap();
assert_eq!(r["for"], "normalText");
let aa = fix_color(&r["fix"]["aa"]);
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
let want = oklch_hue(&vectorcraft_color::Color::from_hex("#fdc96e").unwrap());
assert!((oklch_hue(&aa) - want).abs() < 1.0, "{} {want}", oklch_hue(&aa));
assert!(matches!(aa, vectorcraft_color::Color::Rgb { .. }), "an RGB color answers RGB: {aa:?}");
// White on #355F78 is 6.87:1 and black 3.05:1, so no color reaches AAA's 7:1.
assert!(r["fix"]["aaa"].is_null(), "{r}");
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
let aaa = s.execute("color.contrast", &json!({"color": large["fix"]["aaa"], "against": "#355f78"})).unwrap();
assert!((4.5..4.57).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}");
}
/// The canvas paints a color with 8 bits per channel, so a fix passes once rounded that way too:
/// #777777 on white is 4.48:1, a gray of about 118.7/255 meets 4.5:1 but paints as #777777 again,
/// and the fix has to paint as #767676 (4.54:1) or darker.
#[test]
fn a_fix_passes_as_the_canvas_paints_it() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap();
let fix = fix_color(&r["fix"]["aa"]);
let painted = fix.to_rgb_uncalibrated().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0);
let got = vectorcraft_color::wcag::contrast_ratio(painted, [1.0; 3]);
assert!(got >= 4.5, "{fix:?} paints as {painted:?}: {got}");
// The fix is the closest one: the gray one 8-bit step lighter fails.
let lighter = painted.map(|v| (v + 1.0 / 255.0).min(1.0));
assert!(vectorcraft_color::wcag::contrast_ratio(lighter, [1.0; 3]) < 4.5, "{fix:?} paints as {painted:?}");
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff"})).unwrap();
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
}
/// The backdrop shows 100 % K alone as `color.contrast` measures it under each Appearance of Black,
/// so the Color Wheel's contrast lines use the same color.
#[test]
fn the_backdrop_shows_black_as_the_appearance_of_black_setting_does() {
let k = vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0);
let cms = vectorcraft_color::cms::active();
let mut s = Session::new();
let p = json!({"color": serde_json::to_value(k).unwrap(), "against": "#ffffff"});
let (accurate, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
assert_ne!(backdrop.shown(&cms, &k), [0.0; 3]);
s.prefs.black_on_screen = "rich".into();
let (rich, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
assert_eq!(backdrop.shown(&cms, &k), [0.0; 3]);
assert!(ratio(&rich) > ratio(&accurate), "{rich} {accurate}");
}
/// A translucent fix also meets the minimum with the color, the opacity, the background and the
/// composited pixel rounded to 8 bits per channel.
#[test]
fn a_translucent_fix_passes_at_eight_bits() {
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
let at_eight_bits = |fix: &vectorcraft_color::Color, opacity: f32, against: f32| {
let (a, b) = (eight(opacity), eight(against));
let pixel = fix.to_rgb_uncalibrated().map(|c| eight(eight(c) * a + b * (1.0 - a)));
vectorcraft_color::wcag::contrast_ratio(pixel, [b; 3])
};
let mut s = Session::new();
// A gray can pass only before rounding: #808080 at 91.1 % over black measures 4.53:1, and at
// 232 / 255 its pixel is #747474 (4.49:1).
let r = s.execute("color.contrast", &json!({"color": "#707070", "against": "#000000", "opacity": 91.1})).unwrap();
let fix = fix_color(&r["fix"]["aa"]);
assert!(at_eight_bits(&fix, 0.911, 0.0) >= 4.5, "{fix:?}");
// #040404 at 195 / 255 over a gray of 137.51 / 255 measures 4.5002:1, and over 138 / 255 it is
// 4.4965:1.
let bg = 137.51 / 255.0;
let p = json!({"color": "#303030", "against": [bg, bg, bg], "opacity": 19500.0 / 255.0});
let r = s.execute("color.contrast", &p).unwrap();
let fix = fix_color(&r["fix"]["aa"]);
assert!(at_eight_bits(&fix, 195.0 / 255.0, bg) >= 4.5, "{fix:?}");
// Black at 41.7 % over white measures 3.008:1, and its pixel at 8 bits is 2.995:1, so no gray
// at that opacity gets a fix.
let p = json!({"color": "#202020", "against": "#ffffff", "opacity": 41.7, "for": "graphics"});
let r = s.execute("color.contrast", &p).unwrap();
assert_eq!(r["graphics"]["aa"], false, "{r}");
assert!(r["fix"]["aa"].is_null(), "{r}");
}
#[test]
fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
assert_eq!(r["fix"], json!({"aa": null, "aaa": null}));
let g = s.execute("color.contrast", &json!({"color": "#cccccc", "against": "#ffffff", "for": "graphics"})).unwrap();
assert_eq!(g["for"], "graphics");
let fix = g["fix"].as_object().unwrap();
assert_eq!(fix.keys().collect::<Vec<_>>(), ["aa"], "{g}");
let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap();
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
assert!(large["fix"]["aa"].is_null(), "4.49:1 meets large text AA: {large}");
assert!(!large["fix"]["aaa"].is_null(), "{large}");
}
#[test]
fn a_cmyk_color_answers_a_cmyk_fix() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": {"c": 0, "m": 40, "y": 70, "k": 20}, "against": "#355f78"})).unwrap();
assert_eq!(r["normalText"]["aa"], false, "{r}");
let fix = fix_color(&r["fix"]["aa"]);
assert!(matches!(fix, vectorcraft_color::Color::Cmyk { .. }), "{fix:?}");
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
assert!(ratio(&back) >= 4.5, "{back}");
}
#[test]
fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() {
let mut s = Session::new();
// #808080 at 50 % over white draws as a light gray: black at 50 % draws 0.5 gray, 3.98:1, which
// meets large text AA (3:1) but not AAA (4.5:1).
let p = json!({"color": "#808080", "against": "#ffffff", "opacity": 50, "for": "largeText"});
let r = s.execute("color.contrast", &p).unwrap();
assert_eq!(r["largeText"]["aa"], false, "{r}");
assert!(r["fix"]["aaa"].is_null(), "no gray at 50 % reaches 4.5:1: {r}");
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff", "opacity": 50})).unwrap();
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
}
/// A square with a 50 % top fill row over locked orange, with and without a lower fill row and in a
/// Screen group or not: isolating the object's blending leaves what a translucent Normal row draws
/// as it is, on the canvas and in the answer, for each blend mode of the object.
#[test]
fn isolation_leaves_a_translucent_normal_row_as_it_draws() {
let id = |v: Value| v["id"].as_u64().unwrap();
for blend in ["normal", "multiply", "screen", "difference", "overlay"] {
for fill in ["#808080", "#ffffff", "#2040a0"] {
for lower in [false, true] {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let n = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap());
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
if lower {
s.execute("appearance.addFill", &json!({})).unwrap();
}
let st = s.active().unwrap();
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": top, "color": fill, "opacity": 50})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
s.execute("transparency.set", &json!({"item": null, "blend": blend})).unwrap();
if lower {
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"blend": "screen"})).unwrap();
s.execute("select.set", &json!({"ids": [n]})).unwrap();
}
let plain = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &plain);
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
let isolated = s.execute("color.contrast", &json!({})).unwrap();
let (q, _) = canvas_ratio(&s, &isolated);
let case = format!("{blend} {fill} lower row and group: {lower}");
assert_eq!(p, q, "the canvas draws the same: {case}");
assert!((ratio(&plain) - ratio(&isolated)).abs() < 1e-6, "{case}: {plain} {isolated}");
assert!((ratio(&plain) - drawn).abs() < 0.02, "{case}: {plain} against {drawn}");
}
}
}
}
/// Two squares over locked orange, each with a 50 % white top fill over a blue Multiply fill, one
/// isolating its blending: the blue multiplies with the orange in one and draws over nothing in the
/// other, so the white draws over different rows and there is no one answer. A given background
/// stands for the rows below and answers.
#[test]
fn a_translucent_row_over_a_blending_row_in_objects_of_different_isolation_has_no_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 180, "height": 180})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let square = |s: &mut Session, x: i32, isolate: bool| {
let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap());
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let st = s.active().unwrap();
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
let top = items.iter().rposition(|i| i.is_fill()).unwrap();
let lower = items.iter().position(|i| i.is_fill()).unwrap();
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
s.execute("appearance.setItem", &json!({"index": lower, "blend": "multiply"})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
if isolate {
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
}
n
};
let a = square(&mut s, 30, false);
let b = square(&mut s, 120, true);
s.execute("select.set", &json!({"ids": [a]})).unwrap();
let ra = ratio(&s.execute("color.contrast", &json!({})).unwrap());
s.execute("select.set", &json!({"ids": [b]})).unwrap();
let rb = ratio(&s.execute("color.contrast", &json!({})).unwrap());
assert!((ra - rb).abs() > 0.1, "the white draws over different rows: {ra} {rb}");
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ"), "{e}");
s.execute("color.contrast", &json!({"against": "#000000"})).unwrap();
// A blending row at no opacity does not show, so the isolation no longer changes the answer.
for n in [a, b] {
let st = s.active().unwrap();
let lower = st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items.iter().position(|i| i.is_fill()).unwrap();
s.execute("appearance.setItem", &json!({"ids": [n], "index": lower, "opacity": 0})).unwrap();
}
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("color.contrast", &json!({})).unwrap();
}
/// A Difference square centered on the edge between locked black and white art: the art behind it
/// is not one color where it is read, so no one color stands for it; a given background answers,
/// and over one color the background is read as before.
#[test]
fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("select.all", &json!({})).unwrap();
// Without the default stroke, which would cover the edge.
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("is not one color where it is read") && e.contains("give `against`"), "{e}");
let given = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&given) - 21.0).abs() < 1e-6, "white minus white is black: {given}");
// In Normal mode the color is drawn as it is, over the background read as one color.
s.execute("transparency.set", &json!({"blend": "normal"})).unwrap();
s.execute("color.contrast", &json!({})).unwrap();
// Moved over the white art alone, the square blends with one color again.
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
s.execute("object.move", &json!({"dx": 40, "dy": 0})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}");
}
/// A Difference square over a white square in a 50 % group that isolates its blending, over the
/// edge between black and white art: the square blends only with the white inside the group, so
/// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer.
#[test]
fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap());
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
s.execute("object.group", &json!({"ids": [back, square]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap();
s.execute("select.set", &json!({"ids": [square]})).unwrap();
s.execute("color.contrast", &json!({})).unwrap();
}
/// With a fill of None, what a pick would be measured against is still read: the Color Wheel's
/// contrast lines show where a solid color in its place passes.
#[test]
fn a_pick_for_a_fill_of_none_is_measured_against_the_background() {
let mut s = blended_over_red("normal");
s.execute("paint.setFill", &json!({"none": true})).unwrap();
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({})).unwrap();
let cms = vectorcraft_color::cms::active();
let black = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(0.0, 0.0, 0.0)));
let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 0.0, 0.0]);
assert!((black - want).abs() < 1e-3, "black over the red art: {black} against {want}");
assert_eq!(backdrop.against_hex(), "#ff0000");
}
#[test]
fn for_takes_only_the_three_categories() {
let mut s = Session::new();
for bad in [json!("NormalText"), json!("aa"), json!(1), json!(true)] {
let e = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "for": bad})).unwrap_err().to_string();
assert!(e.contains("`for` must be one of normalText, largeText, graphics"), "{e}");
}
}
+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());
+28 -1
View File
@@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec<u8> {
}
/// Cyan solid on the top row, PANTONE 185 C at 50% on the left column.
fn two_plates() -> Vec<u8> {
pub(crate) fn two_plates() -> Vec<u8> {
single_file(
&[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))],
"%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n",
@@ -267,6 +267,33 @@ fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_cor
assert_eq!(node(&s).image_corners().unwrap(), corners);
}
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a DCS file puts
/// the file's image between the corners and draws its clipping path through them.
#[test]
fn place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners() {
let dir = temp_dir("replace-distorted-clip");
let path = write(&dir, "pic.eps", &two_plates());
let mut s = session();
let png = crate::tests_links::png(4, 4, [255, 0, 0]);
let r = s.execute("file.place", &json!({ "name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100] })).unwrap();
let old = NodeId(r["ids"][0].as_u64().unwrap());
s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap();
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
let r = s.execute("file.place", &json!({ "path": path, "replace": true })).unwrap();
let group = NodeId(r["ids"][0].as_u64().unwrap());
let id = NodeId(r["image"].as_u64().unwrap());
let node = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(node.is_distorted_image());
assert_eq!(node.image_corners().unwrap(), corners);
let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") };
let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") };
let anchors: Vec<_> = path.anchors().map(|(_, _, a)| a.p).collect();
// The left half of the 2 × 2 pixels, where the corners put it.
let map = node.image_map().unwrap();
let want = [(0.0, 0.0), (1.0, 0.0), (1.0, 2.0), (0.0, 2.0)].map(|(x, y)| map.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
assert!(anchors.len() == want.len() && want.iter().all(|w| anchors.iter().any(|a| a.distance(*w) < 1e-6)), "{anchors:?} vs {want:?}");
}
#[test]
fn update_link_clips_an_image_whose_file_gained_a_clipping_path() {
let dir = temp_dir("update-gained-clip");
+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();
+41
View File
@@ -812,6 +812,47 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() {
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// Place with Replace of a distorted image by an image file keeps its corners, in one undo step:
/// the new file's pixels fill them, the new image is linked to that file, and its transform is the
/// old image's scaled to the new pixel size. Undo brings the old image back between the same
/// corners.
#[test]
fn place_with_replace_keeps_a_distorted_images_corners() {
let dir = Folder::new("distorted-place-replace");
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
write(&photo, &png(20, 10, RED));
write(&other, &png(60, 20, BLUE));
let mut s = session();
let id = place(&mut s, &photo);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
// Around the artboard's center, where `centre_colour` looks.
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).cloned();
let before = node(&s, id).unwrap().image_corners().unwrap();
let old_xf = image(&s, id).xf;
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
let undo = undo_len(&s);
let r = s.execute("file.place", &json!({"path": other, "replace": true})).unwrap();
let new = NodeId(r["ids"][0].as_u64().unwrap());
assert_eq!(undo_len(&s), undo + 1);
assert!(node(&s, id).is_none(), "the old image is replaced");
let n = node(&s, new).unwrap();
assert!(n.is_distorted_image());
assert_eq!(n.image_corners().unwrap(), before);
let im = image(&s, new);
assert_eq!((im.width, im.height), (60, 20));
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str()));
let want = old_xf * vectorcraft_geom::Affine::scale_non_uniform(20.0 / 60.0, 10.0 / 20.0);
assert!(im.xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{:?} against {want:?}", im.xf);
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
s.execute("edit.undo", &json!({})).unwrap();
assert!(node(&s, new).is_none());
assert_eq!(node(&s, id).unwrap().image_corners().unwrap(), before);
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// Unembed into a folder keeps a distorted image's corners, in one undo step.
#[test]
fn unembed_to_a_folder_keeps_a_distorted_images_corners() {
+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]
+48
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]
@@ -1794,6 +1825,23 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() {
assert_eq!(out, vec![json!(0)]);
}
#[test]
fn text_frames_remove_all_refuses_type_on_a_locked_artboard() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", t.0)), "{e}");
assert!(s.active().unwrap().doc.node(t).is_some());
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn move_and_duplicate_refuse_art_on_a_locked_artboard() {
let (mut s, a, b) = doc();
+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);
}
+434
View File
@@ -0,0 +1,434 @@
//! Character and paragraph styles in the script object model.
use serde_json::{Value, json};
use vectorcraft_doc::{TextObject, TextStyleDef};
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA};
use crate::script::TEST_RESULT_BYTES;
use crate::*;
fn run(s: &mut Session, source: &str) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
r["log"].as_array().cloned().unwrap_or_default()
}
/// The message of the run's failure.
fn failure(s: &mut Session, source: &str) -> String {
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
}
fn undo_steps(s: &Session) -> usize {
s.active().unwrap().history.undo.len()
}
/// A 400 × 300 pt document with point type holding `text`.
fn doc_with(text: &str) -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap();
(s, NodeId(id))
}
fn text_of(s: &Session, id: NodeId) -> TextObject {
match &s.active().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
_ => panic!("not text"),
}
}
/// Each run's text, style name, size and underline.
fn runs(s: &Session, id: NodeId) -> Vec<(String, Option<String>, f64, bool)> {
text_of(s, id).runs.iter().map(|r| (r.text.clone(), r.style.style_name.clone(), r.style.size, r.style.underline)).collect()
}
fn char_names(s: &Session) -> Vec<String> {
s.active().unwrap().doc.char_styles.iter().map(|d| d.name.clone()).collect()
}
const DOC: &str = "var d = app.activeDocument, cs = d.characterStyles, ps = d.paragraphStyles, tf = d.textFrames[0];";
#[test]
fn style_collections_list_the_normal_style_first_and_add_find_and_remove() {
let (mut s, _) = doc_with("Hello");
let before = undo_steps(&s);
let out = log(
&mut s,
&format!(
"{DOC} vc.log([cs.length, ps.length, cs[0].name, ps[0].name, cs.typename, cs[0].typename, ps[0].typename]);\
var b = cs.add('Body'); var p = ps.add('Lead');\
vc.log([cs.length, cs[1].name, cs.getByName('Body').name, cs.index(1).name, cs.index('Body').name, b.parent.typename]);\
vc.log([ps.length, ps.getByName('Lead').name, cs[5] === undefined]);\
cs.add('Other'); cs.removeAll(); ps.removeAll();\
vc.log([cs.length, ps.length, cs[0].name]);"
),
);
assert_eq!(out[0], json!([1, 1, NORMAL_CHAR, NORMAL_PARA, "CharacterStyles", "CharacterStyle", "ParagraphStyle"]));
assert_eq!(out[1], json!([2, "Body", "Body", "Body", "Body", "Document"]));
assert_eq!(out[2], json!([2, "Lead", true]));
assert_eq!(out[3], json!([1, 1, NORMAL_CHAR]));
assert_eq!(undo_steps(&s), before + 1);
let undo = undo_steps(&s);
for (src, says) in [
("cs.getByName('Nope');", "Not found"),
("cs.index(4);", "Not found"),
("cs.add('Body'); cs.add('Body');", "already exists"),
("cs[0].remove();", "cannot be removed"),
("ps[0].name = 'Mine';", "cannot be renamed"),
("cs.getByName(5);", "string"),
] {
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
}
assert_eq!((undo_steps(&s), char_names(&s)), (undo, Vec::<String>::new()));
}
/// Names are trimmed; an empty name, one past 256 characters and one with a control character
/// are refused with nothing changed.
#[test]
fn style_names_are_trimmed_and_checked() {
let (mut s, _) = doc_with("Hello");
let out = log(&mut s, &format!("{DOC} vc.log(cs.add(' Lead ').name); vc.log(cs.add('{}').name.length);", "x".repeat(256)));
assert_eq!(out, [json!("Lead"), json!(256)]);
let undo = undo_steps(&s);
let long = "x".repeat(257);
for (src, says) in [
("cs.add(' ');".to_string(), "empty"),
(format!("cs.add('{long}');"), "256 characters"),
("cs.add('a\\u0007b');".to_string(), "control characters"),
("ps.add('tab\\there');".to_string(), "control characters"),
("cs.getByName('Lead').name = 'x\\ny';".to_string(), "control characters"),
("cs.add(5);".to_string(), "string"),
(format!("cs.getByName('{}');", "y".repeat(5000)), "too long"),
] {
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
}
assert_eq!(undo_steps(&s), undo);
assert_eq!(char_names(&s).len(), 2);
// Path characters are kept as part of the name; a style name never names a file.
let out = log(&mut s, &format!("{DOC} vc.log(cs.add('../a/b\\\\c:*?').name);"));
assert_eq!(out, [json!("../a/b\\c:*?")]);
assert_eq!(char_names(&s).last().map(String::as_str), Some("../a/b\\c:*?"));
}
/// A style attribute that is not a finite number in range is refused with nothing changed.
#[test]
fn style_attributes_refuse_values_that_are_not_finite_or_in_range() {
let (mut s, _) = doc_with("Hello");
log(&mut s, &format!("{DOC} cs.add('X'); ps.add('P');"));
let undo = undo_steps(&s);
for (src, says) in [
("cs[1].characterAttributes.size = NaN;", "finite number"),
("cs[1].characterAttributes.size = Infinity;", "finite number"),
("cs[1].characterAttributes.size = 1e9;", "0.1 to 1296"),
("cs[1].characterAttributes.leading = 1e300;", "0.1 to 5000"),
("cs[1].characterAttributes.tracking = -1e9;", "tracking"),
("ps[1].paragraphAttributes.leftIndent = NaN;", "finite"),
("ps[1].paragraphAttributes.spaceBefore = 1e12;", "1296"),
] {
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
}
assert_eq!(undo_steps(&s), undo);
let attrs = |s: &Session| {
s.active().unwrap().doc.char_styles.iter().chain(s.active().unwrap().doc.para_styles.iter()).map(|d| d.attrs.len()).sum::<usize>()
};
assert_eq!(attrs(&s), 0);
}
/// A style object follows its style through a rename made with it; after the style is removed,
/// with the object or with a command, every member throws, and a new style of that name does not
/// bring it back.
#[test]
fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() {
let (mut s, id) = doc_with("Hello");
let out = log(
&mut s,
&format!(
"{DOC} var a = cs.add('A'); a.applyTo(tf.textRange); a.name = ' B '; vc.log([a.name, cs[1].name, a === cs.getByName('B')]);\
a.name = 'B'; vc.log(cs.length);"
),
);
assert_eq!(out, [json!(["B", "B", true]), json!(2)]);
assert_eq!(runs(&s, id)[0].1.as_deref(), Some("B"));
for remove in ["a.remove();", "vc.run('charStyle.delete', {name: 'B'});", "cs.removeAll();"] {
let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); {remove} cs.add('B'); a.name;"));
assert!(e.contains("Stale style"), "{remove}: {e}");
}
// A style removed and made again by commands is another style.
let e = failure(
&mut s,
&format!(
"{DOC} var a = cs.getByName('B'); vc.run('charStyle.delete', {{name: 'B'}}); vc.run('charStyle.new', {{name: 'B', attrs: {{}}}}); a.name;"
),
);
assert!(e.contains("Stale style"), "{e}");
// So is a style removed and made again by the steps of one batch.
let e = failure(
&mut s,
&format!(
"{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.delete', params: {{name: 'B'}}}}, \
{{command: 'charStyle.new', params: {{name: 'B', attrs: {{}}}}}}]}}); a.name;"
),
);
assert!(e.contains("Stale style"), "{e}");
// And a style a batch renames and then names back.
let e = failure(
&mut s,
&format!(
"{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.rename', params: {{name: 'B', to: 'C'}}}}, \
{{command: 'charStyle.rename', params: {{name: 'C', to: 'B'}}}}]}}); a.name;"
),
);
assert!(e.contains("Stale style"), "{e}");
// The attributes object of a removed style throws for its typename too.
let e =
failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;"));
assert!(e.contains("Stale style"), "{e}");
// A style renamed by a command is stale too, and its text keeps its look after a removal.
let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;"));
assert!(e.contains("Stale style"), "{e}");
let e =
failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.characterAttributes.size;"));
assert!(e.contains("Stale style"), "{e}");
let size = runs(&s, id)[0].2;
log(&mut s, &format!("{DOC} var a = cs.getByName('B'); a.characterAttributes.size = 40; a.remove();"));
assert_eq!(runs(&s, id)[0].1, None);
assert_ne!(runs(&s, id)[0].2, size);
assert_eq!(runs(&s, id)[0].2, 40.0);
}
/// The steps of one batch a script runs keep one copy of a document's style lists, however many of
/// them change the lists.
#[test]
fn the_steps_of_a_batch_keep_one_copy_of_the_style_lists() {
let (mut s, _) = doc_with("Hello");
let commands: Vec<Value> = (0..20).map(|i| json!({"command": "charStyle.new", "params": {"name": format!("S{i}"), "attrs": {}}})).collect();
s.script_in_run = true;
let r = s.execute("command.batch", &json!({"commands": commands}));
s.script_in_run = false;
r.unwrap();
assert_eq!(char_names(&s).len(), 20);
assert_eq!(crate::script::retained_style_lists(&s), 1);
}
/// A removal or rename whose result cannot cross to the script is put back, and the style's object
/// still names the style after it.
#[test]
fn a_style_change_that_is_put_back_keeps_the_style_object() {
let (mut s, _) = doc_with("Hello");
s.execute("charStyle.new", &json!({"name": "B", "attrs": {}})).unwrap();
TEST_RESULT_BYTES.with(|b| b.set(Some(1)));
let r = run(
&mut s,
&format!(
"{DOC} var a = cs.getByName('B');\
try {{ a.remove(); }} catch (e) {{ vc.log(e.name); }}\
try {{ vc.run('charStyle.delete', {{name: 'B'}}); }} catch (e) {{ vc.log(e.name); }}\
try {{ a.name = 'C'; }} catch (e) {{ vc.log(e.name); }}\
vc.log([a.name, a === cs.getByName('B'), cs.length]);"
),
);
TEST_RESULT_BYTES.with(|b| b.set(None));
let r = r.unwrap();
assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", ["B", true, 2]]), "{r}");
assert!(char_names(&s).contains(&"B".to_string()), "{:?}", char_names(&s));
}
/// A character style styles exactly the range; without clearing overrides the range keeps its
/// own underline, and with them it goes back to the Normal style first.
#[test]
fn apply_to_styles_a_range_and_clearing_overrides_resets_it() {
let (mut s, id) = doc_with("Hello world");
let before = undo_steps(&s);
log(
&mut s,
&format!("{DOC} var w = tf.words[0]; w.underline = true; var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo(w);"),
);
assert_eq!(runs(&s, id), [("Hello".into(), Some("Big".into()), 30.0, true), (" world".into(), None, 12.0, false)]);
assert_eq!(undo_steps(&s), before + 1);
log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf.words[0], true);"));
assert_eq!(runs(&s, id)[0], ("Hello".into(), Some("Big".into()), 30.0, false));
// A whole frame, and an empty range, which changes nothing.
log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf); cs[0].applyTo(tf.characters[0]);"));
assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]);
}
/// A character style applied to an empty frame styles the text set in it later.
#[test]
fn a_character_style_applied_to_an_empty_frame_styles_text_set_later() {
for target in ["tf", "tf.textRange"] {
let (mut s, id) = doc_with("");
log(&mut s, &format!("{DOC} var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo({target}); tf.contents = 'Hi';"));
assert_eq!(runs(&s, id), [("Hi".into(), Some("Big".into()), 30.0, false)], "{target}");
}
}
/// A paragraph style styles every paragraph the text touches, and only those.
#[test]
fn a_paragraph_style_styles_the_paragraphs_the_text_touches() {
let (mut s, id) = doc_with("one\ntwo\nthree");
let out = log(
&mut s,
&format!(
"{DOC} var c = ps.add('Centered'); var a = c.paragraphAttributes;\
vc.log([a.justification === undefined, a.spaceBefore === undefined, a.typename]);\
a.justification = Justification.CENTER; a.spaceBefore = 6;\
vc.log([a.justification, a.spaceBefore]); c.applyTo(tf.paragraphs[1]);\
vc.log(tf.paragraphs[1].paragraphAttributes.justification);"
),
);
assert_eq!(out, [json!([true, true, "ParagraphAttributes"]), json!(["Justification.CENTER", 6]), json!("Justification.CENTER")]);
let t = text_of(&s, id);
let names: Vec<_> = (0..3).map(|i| t.para_at(i).style_name.clone()).collect();
assert_eq!(names, [None, Some("Centered".to_string()), None]);
assert_eq!(t.para_at(1).space_before, 6.0);
assert_eq!(t.para_at(2).space_before, 0.0);
let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.justification = 'middle';"));
assert!(e.contains("Justification"), "{e}");
let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.spaceAfter = 5000;"));
assert!(e.contains("1296"), "{e}");
}
/// A style's character attributes read `undefined` until set; setting one restyles the text in
/// the style but not a value the text changed itself.
#[test]
fn style_attributes_redefine_the_text_in_the_style() {
let (mut s, id) = doc_with("ab cd");
let out = log(
&mut s,
&format!(
"{DOC} var x = cs.add('X'), a = x.characterAttributes;\
vc.log([a.size === undefined, a.autoLeading === undefined, a.textFont === undefined, a.typename]);\
a.size = 20; x.applyTo(tf.textRange); tf.words[1].size = 9; a.size = 24; a.autoLeading = true; a.underline = true;\
vc.log([a.size, a.autoLeading, a.underline]);"
),
);
assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]);
assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]);
// Turning auto leading off keeps the leading auto leading gave the style's size.
let out = log(
&mut s,
&format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);"),
);
assert_eq!(out, [json!([false, 288])]);
let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;"));
assert!(e.contains("0.1 to 1296"), "{e}");
let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.textFont = 'Arial';"));
assert!(e.contains("TextFont"), "{e}");
let e = failure(&mut s, &format!("{DOC} ps.add('P').characterAttributes;"));
assert!(e.contains("not available yet"), "{e}");
}
/// A range lists each style its text uses once, in order, with the Normal style for unstyled
/// text, and its lists cannot add or remove styles.
#[test]
fn a_range_lists_the_styles_its_text_uses() {
let (mut s, _) = doc_with("aa bb cc\ndd");
let out = log(
&mut s,
&format!(
"{DOC} var x = cs.add('X'), y = cs.add('Y'); y.applyTo(tf.words[2]); x.applyTo(tf.words[1]); x.applyTo(tf.words[3]);\
ps.add('P').applyTo(tf.paragraphs[1]);\
function names(l) {{ var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; }}\
vc.log(names(tf.textRange.characterStyles)); vc.log(names(tf.words[1].characterStyles));\
vc.log(names(tf.textRange.paragraphStyles)); vc.log(names(tf.paragraphs[0].paragraphStyles));\
vc.log([tf.words[1].characterStyles[0] === x, tf.words[1].characterStyles.getByName('X').name,\
tf.textRange.characterStyles.parent.typename]);"
),
);
assert_eq!(out[0], json!([NORMAL_CHAR, "X", "Y"]));
assert_eq!(out[1], json!(["X"]));
assert_eq!(out[2], json!([NORMAL_PARA, "P"]));
assert_eq!(out[3], json!([NORMAL_PARA]));
assert_eq!(out[4], json!([true, "X", "TextRange"]));
for src in ["tf.textRange.characterStyles.add('Z');", "tf.textRange.paragraphStyles.removeAll();"] {
assert!(failure(&mut s, &format!("{DOC} {src}")).contains("cannot be added or removed"), "{src}");
}
}
/// `applyTo` refuses what is not text, a `clearingOverrides` that is not a boolean, text of another
/// document, and a range whose text changed, with nothing changed.
#[test]
fn apply_to_refuses_bad_arguments_with_nothing_changed() {
let (mut s, id) = doc_with("Hello");
log(&mut s, &format!("{DOC} cs.add('X');"));
let runs_before = runs(&s, id);
for (src, says) in [
("cs[1].applyTo(5);".to_string(), "TextRange"),
("cs[1].applyTo(tf.textRange, 'yes');".to_string(), "clearingOverrides"),
("cs[1].applyTo(cs);".to_string(), "TextRange"),
(format!("var r = tf.textRange; vc.run('text.setText', {{id: {}, text: 'Help'}}); cs[1].applyTo(r);", id.0), "Stale text range"),
(
"var o = app.documents.add(); var t = o.textFrames.add(); t.contents = 'Other'; cs[1].applyTo(t.textRange);".to_string(),
"another document",
),
] {
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
}
assert_eq!(runs(&s, id), runs_before);
}
/// A run names at most 4,096 styles; reading past that throws instead of growing without bound.
#[test]
fn style_objects_made_before_file_revert_go_stale_even_when_the_style_is_back() {
let (mut s, _) = doc_with("Hello");
s.execute("charStyle.new", &json!({"name": "B", "attrs": {"size": 30}})).unwrap();
let path = std::env::temp_dir().join(format!("vc-styles-revert-{}.vectorcraft", std::process::id()));
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let out = log(
&mut s,
&format!(
"{DOC} var a = cs.getByName('B');\
vc.run('shape.rectangle', {{x: 1, y: 1, width: 5, height: 5}}); vc.run('file.revert', {{}});\
var cs2 = app.activeDocument.characterStyles;\
try {{ vc.log(a.name); }} catch (e) {{ vc.log(e.message); }}\
vc.log(cs2.getByName('B').name); vc.log(cs2.getByName('B') === a);"
),
);
let _ = std::fs::remove_file(&path);
assert!(out[0].as_str().is_some_and(|m| m.contains("Stale style")), "{out:?}");
assert_eq!(out[1], json!("B"), "a style object made after the revert names the reverted style");
assert_eq!(out[2], json!(false));
}
#[test]
fn a_run_names_at_most_4096_styles() {
let (mut s, _) = doc_with("Hello");
let mut d = (*s.active().unwrap().doc).clone();
let defs: Vec<TextStyleDef> = (0..4100).map(|i| TextStyleDef { name: format!("S{i}"), attrs: Default::default() }).collect();
d.char_styles = defs.into();
s.doc_mut().unwrap().doc = std::sync::Arc::new(d);
let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; vc.log(cs[0] === undefined); vc.log(cs.length);"));
assert_eq!(out, [json!(false), json!(4101)]);
let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;"));
assert!(e.contains("4096 styles"), "{e}");
// `add` with every slot taken adds no style; with one slot left it adds the style.
let out = log(
&mut s,
&format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; try {{ cs.add('New'); }} catch (e) {{ vc.log(e.message); }} vc.log(cs.length);"),
);
assert_eq!(out, [json!("a script can name at most 4096 styles in one run"), json!(4101)]);
let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4095; i++) cs[i]; vc.log(cs.add('New').name); vc.log(cs.length);"));
assert_eq!(out, [json!("New"), json!(4102)]);
}
/// A script loads styles from a file only where it may read files; a file outside that is refused.
#[test]
fn a_script_loads_styles_only_from_a_file_it_may_read() {
let (mut s, _) = doc_with("Hello");
let dir = std::env::temp_dir().join(format!("vc-script-styles-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Other.vectorcraft");
let mut other = Session::new();
other.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
other.execute("charStyle.new", &json!({"name": "Loaded", "attrs": {"size": 30}})).unwrap();
std::fs::write(&path, vectorcraft_format::save(&other.active().unwrap().doc, false)).unwrap();
let p = path.to_string_lossy().replace('\\', "/");
let e = failure(&mut s, &format!("vc.run('charStyle.load', {{path: '{p}'}});"));
std::fs::remove_dir_all(&dir).ok();
assert!(e.contains("access denied"), "{e}");
assert!(char_names(&s).is_empty());
}
+2 -1
View File
@@ -1044,9 +1044,10 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
("object.cropImage", json!({})),
("imageTrace.make", json!({})),
("object.mesh.create", json!({})),
// Vector art has no pixels to put between the corners.
(
"file.place",
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
json!({"replace": true, "name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(b"<svg xmlns='http://www.w3.org/2000/svg' width='9' height='9'><rect width='9' height='9'/></svg>")}),
),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
+1
View File
@@ -630,6 +630,7 @@ impl Session {
freeform_point: self.selected_freeform_point(),
raster_sample: self.prefs.eyedropper.sample_size,
preview_bounds: self.prefs.use_preview_bounds,
scale_strokes: self.prefs.scale_strokes,
glyph_bounds: self.prefs.type_glyph_bounds,
preview_memo: Some(&self.preview_memo),
unit,