mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 10:51:11 +01:00
Merge main into feat/scripts-doc-defaults
This commit is contained in:
commit
0bd735f53d
201 files changed
+13721
-999
No files matched your search
@@ -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()));
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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 ----------
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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]
|
||||
|
||||
Reference in new issue
Block a user