mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 10:14:46 +01:00
Merge main into feat/color-wheel-copy-color-as
This commit is contained in:
commit
288c14310d
125 files changed
+6335
-542
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# The DXF writer goldens are compared byte for byte with the writer's output (LF line endings).
|
||||
crates/cad/tests/data/*.dxf -text
|
||||
@@ -130,7 +130,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 235 KiB After Width: | Height: | Size: 121 KiB |
@@ -2,6 +2,7 @@
|
||||
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
|
||||
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
|
||||
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
|
||||
//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum.
|
||||
|
||||
/// What the content in front is, which sets the ratio it needs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -87,6 +88,82 @@ pub fn ratio_text(ratio: f64) -> String {
|
||||
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
|
||||
}
|
||||
|
||||
/// The lightnesses [`closest_passing`] tests on each side before it narrows down the first that
|
||||
/// passes.
|
||||
const LIGHTNESS_SAMPLES: usize = 16;
|
||||
/// The halvings [`closest_passing`] makes of the lightness step, which leave it within 1e-9.
|
||||
const LIGHTNESS_STEPS: usize = 32;
|
||||
/// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples,
|
||||
/// which leave it within 1e-7 of the step.
|
||||
const PEAK_STEPS: usize = 32;
|
||||
/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a
|
||||
/// single peak between them. `f` is called 34 times.
|
||||
pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 {
|
||||
let g = (5f64.sqrt() - 1.0) / 2.0;
|
||||
let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo));
|
||||
let (mut fa, mut fb) = (f(a), f(b));
|
||||
for _ in 0..PEAK_STEPS {
|
||||
if fa < fb {
|
||||
(lo, a, fa) = (a, b, fb);
|
||||
b = lo + g * (hi - lo);
|
||||
fb = f(b);
|
||||
} else {
|
||||
(hi, b, fb) = (b, a, fa);
|
||||
a = hi - g * (hi - lo);
|
||||
fa = f(a);
|
||||
}
|
||||
}
|
||||
if fa > fb { a } else { b }
|
||||
}
|
||||
|
||||
/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue
|
||||
/// (<https://bottosson.github.io/posts/oklab/>) with the lightness raised or lowered, whichever
|
||||
/// takes the smaller step, and the chroma lowered where sRGB cannot show it, to the largest chroma
|
||||
/// below it that fits ([`crate::oklab::from_oklch`]). Each side is tested at
|
||||
/// 16 even steps up to white or black, and the step before the first that passes is narrowed down.
|
||||
/// When no step passes, the highest ratio between the neighbors of the highest step is looked for,
|
||||
/// so a color that passes only in a narrow band between white and black (as under a Difference
|
||||
/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is
|
||||
/// bounded: at most 167 colors are tested. The answer is the nearest passing color when the colors
|
||||
/// that pass on each side form one stretch up to white or black, as for a plain contrast ratio.
|
||||
/// When `ratio` lets colors pass in more than one stretch, a stretch that lies between two tested
|
||||
/// steps before the first passing one is missed, and a farther color can be returned.
|
||||
pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> {
|
||||
let passes = |c: [f32; 3]| ratio(c) >= minimum;
|
||||
let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
|
||||
if passes(srgb) {
|
||||
return Some(srgb);
|
||||
}
|
||||
let [l, c, h] = crate::oklab::to_oklch(srgb);
|
||||
let mut best: Option<(f64, [f32; 3])> = None;
|
||||
for end in [1.0, 0.0] {
|
||||
let at = |t: f64| crate::oklab::from_oklch(l + (end - l) * t, c, h).0;
|
||||
let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64;
|
||||
let ratios: Vec<f64> = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect();
|
||||
// `lo` fails and `hi` passes, the step before the first sample that passes.
|
||||
let found = match ratios.iter().position(|r| *r >= minimum) {
|
||||
Some(i) => Some((step(i), step(i + 1))),
|
||||
None => {
|
||||
// Every sample fails: look for a higher ratio around the highest one.
|
||||
let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0;
|
||||
let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES)));
|
||||
let peak = peak_between(lo, hi, &|t| ratio(at(t)));
|
||||
passes(at(peak)).then_some((lo, peak))
|
||||
}
|
||||
};
|
||||
let Some((mut lo, mut hi)) = found else { continue };
|
||||
for _ in 0..LIGHTNESS_STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if passes(at(mid)) { hi = mid } else { lo = mid }
|
||||
}
|
||||
let step = (end - l).abs() * hi;
|
||||
if best.is_none_or(|(d, _)| step < d) {
|
||||
best = Some((step, at(hi)));
|
||||
}
|
||||
}
|
||||
best.map(|(_, c)| c)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -137,6 +214,80 @@ mod tests {
|
||||
assert_eq!(Category::parse("NormalText"), None);
|
||||
}
|
||||
|
||||
fn hue(srgb: [f32; 3]) -> f64 {
|
||||
let [_, a, b] = crate::libraries::srgb_to_oklab(srgb);
|
||||
b.atan2(a).to_degrees()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_color_keeps_the_hue_and_just_passes() {
|
||||
let (fg, bg) = (hex("fdc96e"), hex("355f78"));
|
||||
let fix = closest_passing(fg, 4.5, &|c| contrast_ratio(c, bg)).unwrap();
|
||||
let r = contrast_ratio(fix, bg);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((hue(fix) - hue(fg)).abs() < 1.0, "{} {}", hue(fix), hue(fg));
|
||||
// A color lighter than the background gets lighter.
|
||||
assert!(relative_luminance(fix) > relative_luminance(fg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_gray_on_white_is_a_darker_gray() {
|
||||
let white = [1.0; 3];
|
||||
let fix = closest_passing(hex("777777"), 4.5, &|c| contrast_ratio(c, white)).unwrap();
|
||||
let r = contrast_ratio(fix, white);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((fix[0] - fix[1]).abs() < 1e-4 && (fix[1] - fix[2]).abs() < 1e-4, "{fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_that_passes_only_between_white_and_black_is_found() {
|
||||
// White drawn with Difference over mid gray: white and black both draw mid gray (1:1), and
|
||||
// mid gray draws black, 5.3:1.
|
||||
let gray = [0.5; 3];
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let fix = closest_passing([1.0; 3], 4.5, &|c| contrast_ratio(difference(c), gray)).unwrap();
|
||||
let r = contrast_ratio(difference(fix), gray);
|
||||
assert!((4.5..4.51).contains(&r), "{fix:?}: {r}");
|
||||
assert!(fix[0] > 0.5, "the nearest side of mid gray from white: {fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_band_between_the_samples_is_found() {
|
||||
// Over #5A5A5A only colors within a few hundredths of it draw dark enough with Difference
|
||||
// for 3:1 (black reaches 3.04:1), and no even step from white lands there.
|
||||
let gray = hex("5a5a5a");
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(difference(c), gray);
|
||||
let fix = closest_passing([1.0; 3], 3.0, &ratio).unwrap();
|
||||
let r = ratio(fix);
|
||||
assert!((3.0..3.01).contains(&r), "{fix:?}: {r}");
|
||||
}
|
||||
|
||||
/// Just below blue's lightness the chromas sRGB holds at blue's hue come in two stretches, so a
|
||||
/// blue that needs a little more contrast keeps nearly all of its chroma.
|
||||
#[test]
|
||||
fn a_blue_that_darkens_a_little_keeps_its_chroma() {
|
||||
let gray = hex("b8b8b8");
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(c, gray);
|
||||
let blue = [0.0, 0.0, 1.0];
|
||||
assert!(ratio(blue) < 4.5, "{}", ratio(blue));
|
||||
let fix = closest_passing(blue, 4.5, &ratio).unwrap();
|
||||
let ([_, c, h], [_, blue_c, blue_h]) = (crate::oklab::to_oklch(fix), crate::oklab::to_oklch(blue));
|
||||
assert!(ratio(fix) >= 4.5 && (h - blue_h).abs() < 1.0, "{fix:?}");
|
||||
assert!(c > blue_c - 0.02, "{fix:?}: chroma {c}, blue's {blue_c}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() {
|
||||
let white = [1.0; 3];
|
||||
assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3]));
|
||||
assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None);
|
||||
// Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches.
|
||||
let mid = hex("777777");
|
||||
assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None);
|
||||
assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_opaque_black_over_white_is_mid_gray() {
|
||||
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
|
||||
|
||||
@@ -851,11 +851,12 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
|
||||
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop};
|
||||
/// Document Info's category titles, the Objects category's count labels, and how its image rows
|
||||
/// write a resolution and a number of bytes.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
|
||||
pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
|
||||
@@ -160,7 +160,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
@@ -1066,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) {
|
||||
@@ -1078,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) => {
|
||||
@@ -1130,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
|
||||
@@ -1266,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| {
|
||||
@@ -1282,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()
|
||||
@@ -1297,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 } {
|
||||
@@ -1354,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
|
||||
@@ -1432,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
|
||||
@@ -1489,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();
|
||||
@@ -1625,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 {
|
||||
@@ -1636,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()));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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), 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 types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul
Line truncated
|
||||
"{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
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -195,6 +195,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
if s.script_frames && !answers.is_empty() {
|
||||
return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"));
|
||||
}
|
||||
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 mut checked_real = None;
|
||||
@@ -241,6 +242,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
fuel,
|
||||
locale,
|
||||
answers,
|
||||
actions,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -442,6 +444,7 @@ impl Session {
|
||||
fuel,
|
||||
locale,
|
||||
answers: vec![],
|
||||
actions: vec![],
|
||||
};
|
||||
let runs = self.script_runs;
|
||||
self.script_start(request).map_err(|e| {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -127,6 +127,12 @@ impl HistoryEntry {
|
||||
self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str()))
|
||||
}
|
||||
|
||||
/// A number no other step takes ([`History::step`]). Undo and Redo make the step they move
|
||||
/// with a new number, and so does an edit merged into the newest step.
|
||||
pub fn serial(&self) -> u64 {
|
||||
self.serial
|
||||
}
|
||||
|
||||
/// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the
|
||||
/// document before the undo, whose next state is now `now` (that step's document). Its figures
|
||||
/// are that step's the other way round when `doc` is still the document they were taken
|
||||
|
||||
@@ -373,6 +373,9 @@ pub struct Session {
|
||||
pub(crate) startup_failures: Vec<(String, String)>,
|
||||
/// Each open document's highest next id a run has seen, by [`DocState::uid`].
|
||||
pub(crate) script_high_water: std::collections::HashMap<u64, u64>,
|
||||
/// The styles the steps of a batch a script runs removed or renamed and the documents they
|
||||
/// reverted ([`script::note_style_lists`]).
|
||||
pub(crate) script_style_trail: script::StyleTrail,
|
||||
/// While a slice of a script runs in this session.
|
||||
pub(crate) script_in_run: bool,
|
||||
/// The desktop app supplies each window by (document uid, runtime window identity) while a
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's
|
||||
//! run, as the VBScript reference's `DoScript` method of the Application object describes it
|
||||
//! (<https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf>).
|
||||
//!
|
||||
//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps
|
||||
//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app
|
||||
//! they are the Actions panel's.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the reference does not state:
|
||||
//! - The action and its set are matched by their exact names; a name that matches no action, or
|
||||
//! more than one, throws before any step runs.
|
||||
//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins
|
||||
//! the run's transaction and its one undo step for each changed document, it is counted as a host
|
||||
//! call, it reads and writes files only where the script may, and a step that fails is put back
|
||||
//! and throws an error that names the step and the action, while the steps before it stay done.
|
||||
//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine
|
||||
//! does not have (a View menu step, or one that plays an action), and a stop throw before any step
|
||||
//! runs, as does such a command among those an `action.batch` step plays. An action cannot play
|
||||
//! another action, so it cannot play itself.
|
||||
//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it
|
||||
//! changes nothing.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostError, HostMember};
|
||||
|
||||
use super::{Host, Link, command, current, refused_to_scripts};
|
||||
|
||||
/// The most actions a run's request may carry.
|
||||
pub const MAX_ACTIONS: usize = 4096;
|
||||
/// The most steps one action may have, after a `command.batch` step gives its own steps.
|
||||
pub const MAX_ACTION_STEPS: usize = 10_000;
|
||||
/// The most steps the actions of one request may have in all.
|
||||
pub const MAX_ALL_STEPS: usize = 100_000;
|
||||
/// The most bytes of the request's actions, as JSON.
|
||||
pub const MAX_ACTIONS_BYTES: usize = 16 << 20;
|
||||
/// The longest name of an action or a set, in bytes.
|
||||
pub const MAX_NAME_BYTES: usize = 1024;
|
||||
/// The longest command id of a step, in bytes.
|
||||
const MAX_ID_BYTES: usize = 256;
|
||||
/// The command id of a stop, which waits for the person in the Actions panel.
|
||||
pub const STOP_STEP: &str = "action.stop";
|
||||
|
||||
/// An action a run can play: its set's name, its name and the steps playback runs.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Playable {
|
||||
set: String,
|
||||
name: String,
|
||||
steps: Vec<Step>,
|
||||
}
|
||||
|
||||
/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a
|
||||
/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and
|
||||
/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Step {
|
||||
place: String,
|
||||
id: String,
|
||||
params: Value,
|
||||
bytes: u64,
|
||||
artboard: Option<u64>,
|
||||
}
|
||||
|
||||
/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the
|
||||
/// step's place in the action (1 for the first; default its place in the list), within the limits
|
||||
/// above. A `command.batch` step gives its own steps, each at the batch's place and its own.
|
||||
pub fn parse(v: Option<&Value>) -> Result<Vec<Playable>, String> {
|
||||
let Some(v) = v else { return Ok(Vec::new()) };
|
||||
let Value::Array(list) = v else { return Err("`actions` must be a list".into()) };
|
||||
if list.len() > MAX_ACTIONS {
|
||||
return Err(format!("`actions` holds more than {MAX_ACTIONS} actions"));
|
||||
}
|
||||
if let Some(place) = super::too_deep(v) {
|
||||
return Err(format!("`actions{place}` is nested more than 64 levels deep"));
|
||||
}
|
||||
if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) {
|
||||
return Err("`actions` is larger than 16 MiB".into());
|
||||
}
|
||||
let mut all = 0usize;
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for (i, a) in list.iter().enumerate() {
|
||||
let at = format!("`actions[{i}]`");
|
||||
let Value::Object(a) = a else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(a, &["set", "name", "steps"], &at)?;
|
||||
let set = name_of(a, "set", &at)?;
|
||||
let name = name_of(a, "name", &at)?;
|
||||
let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) };
|
||||
let mut steps = Vec::new();
|
||||
for (j, s) in given.iter().enumerate() {
|
||||
let at = format!("{at}.steps[{j}]");
|
||||
let Value::Object(s) = s else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(s, &["command", "params", "step"], &at)?;
|
||||
let place = match s.get("step") {
|
||||
None => (j + 1).to_string(),
|
||||
Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) {
|
||||
Some(n) => n.to_string(),
|
||||
None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")),
|
||||
},
|
||||
};
|
||||
let (id, params) = command_of(s, &at)?;
|
||||
match params.get("commands") {
|
||||
Some(Value::Array(inner)) if id == "command.batch" => {
|
||||
// The batch's `artboard`, for its steps that act on the active artboard, as
|
||||
// `command.batch` reads it.
|
||||
let artboard = params.get("artboard").and_then(Value::as_u64);
|
||||
for (k, c) in inner.iter().enumerate() {
|
||||
let at = format!("{at}.params.commands[{k}]");
|
||||
let Value::Object(c) = c else { return Err(format!("{at} must be an object")) };
|
||||
let (id, params) = command_of(c, &at)?;
|
||||
if id == "command.batch" {
|
||||
return Err(format!("{at} is a command.batch inside a command.batch"));
|
||||
}
|
||||
steps.push(step(format!("{place}.{}", k + 1), id, params, artboard));
|
||||
}
|
||||
}
|
||||
_ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")),
|
||||
_ => steps.push(step(place, id, params, None)),
|
||||
}
|
||||
if steps.len() > MAX_ACTION_STEPS {
|
||||
return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps"));
|
||||
}
|
||||
}
|
||||
all += steps.len();
|
||||
if all > MAX_ALL_STEPS {
|
||||
return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all"));
|
||||
}
|
||||
out.push(Playable { set, name, steps });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Playable {
|
||||
/// The steps the action runs.
|
||||
pub fn len(&self) -> usize {
|
||||
self.steps.len()
|
||||
}
|
||||
|
||||
/// Whether the action runs no step.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.steps.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn only_keys(o: &Map<String, Value>, keys: &[&str], at: &str) -> Result<(), String> {
|
||||
match o.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn name_of(o: &Map<String, Value>, key: &str, at: &str) -> Result<String, String> {
|
||||
match o.get(key) {
|
||||
Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()),
|
||||
Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")),
|
||||
_ => Err(format!("{at}.{key} must be a string")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A step's `command` and `params` (default `{}`).
|
||||
fn command_of(o: &Map<String, Value>, at: &str) -> Result<(String, Value), String> {
|
||||
let id = match o.get("command") {
|
||||
Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(),
|
||||
_ => return Err(format!("{at}.command must be a command id")),
|
||||
};
|
||||
let params = match o.get("params") {
|
||||
None => json!({}),
|
||||
Some(p @ Value::Object(_)) => p.clone(),
|
||||
Some(_) => return Err(format!("{at}.params must be an object")),
|
||||
};
|
||||
Ok((id, params))
|
||||
}
|
||||
|
||||
fn step(place: String, id: String, params: Value, artboard: Option<u64>) -> Step {
|
||||
let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64);
|
||||
Step { place, id, params, bytes, artboard }
|
||||
}
|
||||
|
||||
/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters
|
||||
/// as U+FFFD.
|
||||
fn shown(text: &str) -> String {
|
||||
const MAX: usize = 80;
|
||||
let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect();
|
||||
if text.chars().nth(MAX).is_some() {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The members of `app` this module adds.
|
||||
pub(super) fn app_members(link: &Link) -> Vec<super::dom::Described> {
|
||||
let l = link.clone();
|
||||
let play = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
do_script(&h, &a)
|
||||
});
|
||||
let info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]);
|
||||
let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)];
|
||||
members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name)));
|
||||
members
|
||||
}
|
||||
|
||||
fn arg(a: &[Data], i: usize) -> &Data {
|
||||
a.get(i).unwrap_or(&Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.doScript(action, set, dialogs?)`, its arguments after `this`.
|
||||
fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
if a.len() > 4 {
|
||||
return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into()));
|
||||
}
|
||||
let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else {
|
||||
return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into()));
|
||||
};
|
||||
if action.is_empty() || set.is_empty() {
|
||||
return Err(HostError::Error("doScript needs the action's name and its set's name".into()));
|
||||
}
|
||||
if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES {
|
||||
return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes")));
|
||||
}
|
||||
if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) {
|
||||
return Err(HostError::Type("doScript's dialogs must be true or false".into()));
|
||||
}
|
||||
let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
|
||||
let p = match found.as_slice() {
|
||||
[p] => *p,
|
||||
[] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
|
||||
[] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))),
|
||||
_ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))),
|
||||
};
|
||||
if p.steps.is_empty() {
|
||||
return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name))));
|
||||
}
|
||||
// Every step is checked before the first runs, so a step that cannot run leaves the documents as
|
||||
// they were.
|
||||
for s in &p.steps {
|
||||
if let Some((place, id)) = refused_step(s) {
|
||||
let name = shown(&p.name);
|
||||
return Err(HostError::Error(if id == STOP_STEP {
|
||||
format!("step {place} of “{name}” is a stop, which a script cannot wait at")
|
||||
} else {
|
||||
format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id))
|
||||
}));
|
||||
}
|
||||
}
|
||||
for s in &p.steps {
|
||||
// A run asked to stop runs no further step; the realm ends it at its next instruction and
|
||||
// puts the documents back.
|
||||
if h.session.borrow().script_stop.is_set() {
|
||||
break;
|
||||
}
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
h.session.borrow_mut().set_replaying(outer);
|
||||
if let Err(e) = r {
|
||||
let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id));
|
||||
return Err(match e {
|
||||
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)),
|
||||
other => other,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The place and command of the first command step `s` would run that a script may not run: the
|
||||
/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the
|
||||
/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the
|
||||
/// engine does not have are refused.
|
||||
fn refused_step(s: &Step) -> Option<(String, String)> {
|
||||
let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none();
|
||||
if refused(&s.id) {
|
||||
return Some((s.place.clone(), s.id.clone()));
|
||||
}
|
||||
if s.id != "action.batch" {
|
||||
return None;
|
||||
}
|
||||
let commands = s.params.get("commands").and_then(Value::as_array)?;
|
||||
commands.iter().enumerate().find_map(|(k, c)| {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned()))
|
||||
})
|
||||
}
|
||||
|
||||
/// `params` of step `id`, with the active artboard of the active document added as a
|
||||
/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for
|
||||
/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to
|
||||
/// Selected Art. The active artboard is the index `start` gives for the document (its index as the
|
||||
/// run started, which the view keeps), past the last artboard the last one, as the view shows it
|
||||
/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While
|
||||
/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its
|
||||
/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh
|
||||
/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the
|
||||
/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork
|
||||
/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the
|
||||
/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch`
|
||||
/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past
|
||||
/// the last artboard the last one, and none in a document without artboards, as `command.batch`
|
||||
/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit
|
||||
/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept.
|
||||
pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value {
|
||||
let mut params = params.clone();
|
||||
let Some(st) = s.active() else { return params };
|
||||
let n = st.doc.artboards.len();
|
||||
let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) {
|
||||
(Some(_), _) if n == 0 => return params,
|
||||
(Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)),
|
||||
(None, Some((_, i))) => (*i).min(n.saturating_sub(1)),
|
||||
(None, None) => super::dom::active_artboard(st),
|
||||
};
|
||||
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
|
||||
let fit_art = id == "artboard.fitToArt";
|
||||
let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"artboard"
|
||||
} else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"index"
|
||||
} else {
|
||||
return params;
|
||||
};
|
||||
let Some(p) = params.as_object_mut() else { return params };
|
||||
if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) {
|
||||
return params;
|
||||
}
|
||||
let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() };
|
||||
let kept: Vec<usize> = match start.picks {
|
||||
Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => {
|
||||
list.iter().copied().filter(|i| *i < n).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if kept.len() >= 2 {
|
||||
p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept));
|
||||
} else if picks.is_empty() {
|
||||
p.insert(key.into(), json!(active));
|
||||
} else if fit_art {
|
||||
p.insert("indices".into(), json!(picks));
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// What [`on_active_artboard`] reads besides the session: the index of each open document's active
|
||||
/// artboard as the run started, by document uid; the Artboard tool's selection as the run started,
|
||||
/// with its document's uid; and the `artboard` a step's recorded `command.batch` names.
|
||||
pub(crate) struct Start<'a> {
|
||||
pub active: &'a [(u64, usize)],
|
||||
pub picks: Option<&'a (u64, Vec<usize>)>,
|
||||
pub batch: Option<u64>,
|
||||
}
|
||||
@@ -196,19 +196,24 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return f(h);
|
||||
}
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let styles = text::styles::mark(h);
|
||||
let mark = h.growth_mark();
|
||||
h.dom.saving.set(true);
|
||||
let r = f(h);
|
||||
h.dom.saving.set(false);
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
} else {
|
||||
{
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
return r;
|
||||
}
|
||||
h.put_growth_back(mark);
|
||||
if !save.restore(&mut s) {
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
// Style objects are put back with the documents.
|
||||
text::styles::put_back(h, styles);
|
||||
r
|
||||
}
|
||||
|
||||
@@ -293,7 +298,7 @@ fn method(link: &Link, f: Member) -> HostMember {
|
||||
}
|
||||
|
||||
/// A member of a class with what `reflect` tells of it.
|
||||
type Described = (String, HostMember, MemberInfo);
|
||||
pub(super) type Described = (String, HostMember, MemberInfo);
|
||||
|
||||
/// A property's or a method's result's type for `reflect`.
|
||||
fn typed(data_type: &str) -> MemberInfo {
|
||||
@@ -301,7 +306,7 @@ fn typed(data_type: &str) -> MemberInfo {
|
||||
}
|
||||
|
||||
/// A method's result's type and its arguments' names and types, for `reflect`.
|
||||
fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect();
|
||||
MemberInfo { arguments, ..typed(data_type) }
|
||||
}
|
||||
@@ -309,7 +314,7 @@ fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
|
||||
/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
let message = format!("{class}.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
@@ -571,7 +576,7 @@ struct Frame {
|
||||
}
|
||||
|
||||
/// The index of the active artboard of `st`, as the view keeps it.
|
||||
fn active_artboard(st: &DocState) -> usize {
|
||||
pub(super) fn active_artboard(st: &DocState) -> usize {
|
||||
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
|
||||
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
|
||||
}
|
||||
@@ -786,6 +791,11 @@ fn on_doc<T>(
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
pub(super) fn after_kept_command(h: &Host) {
|
||||
text::styles::after_command(h);
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept.
|
||||
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
|
||||
@@ -2318,7 +2328,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
|
||||
const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
|
||||
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
|
||||
|
||||
/// The error of `move` and `duplicate` given an object of another document.
|
||||
pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available";
|
||||
@@ -2672,6 +2682,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(super::actions::app_members(l));
|
||||
let preset = {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
@@ -2745,6 +2756,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
|
||||
@@ -50,6 +50,7 @@ use super::{
|
||||
};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
|
||||
pub(super) mod styles;
|
||||
pub(super) mod threads;
|
||||
|
||||
/// The error of a text range, or of a collection of one, whose frame's text changed other than
|
||||
@@ -201,6 +202,8 @@ pub(in crate::script) struct TextState {
|
||||
made: Cell<u64>,
|
||||
/// The span of each range object, by its number, whose `length` the script set.
|
||||
resized: RefCell<HashMap<u64, (usize, usize, u64)>>,
|
||||
/// The styles the run's style objects name.
|
||||
styles: styles::StyleState,
|
||||
}
|
||||
|
||||
fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> {
|
||||
@@ -1680,14 +1683,13 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
range.extend(attr_members(l));
|
||||
range.push(threads::range_member(l));
|
||||
range.extend(para_members(l));
|
||||
range.extend(styles::range_members(l));
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"kerning",
|
||||
"characterStyles",
|
||||
"paragraphStyles",
|
||||
"textSelection",
|
||||
"changeCaseTo",
|
||||
"select",
|
||||
@@ -1786,6 +1788,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
None,
|
||||
),
|
||||
];
|
||||
out.extend(styles::classes(l));
|
||||
out.extend(stories);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,802 @@
|
||||
//! Character and paragraph styles in the script object model: `document.characterStyles` and
|
||||
//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text
|
||||
//! of a `TextRange` uses, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/> describe them.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - A document's collection lists its Normal style first, then its other styles in the order the
|
||||
//! panel lists them.
|
||||
//! - A style object names its style for the rest of the run, also after the script renames it
|
||||
//! through `name`. Once the style is removed, or renamed or removed other than through the object
|
||||
//! model, or its document is closed or reverted with File › Revert, every member throws
|
||||
//! `Stale style`; a style added later under the same name is another style.
|
||||
//! - A style name is trimmed, and must then be 1 to 256 characters long with no control
|
||||
//! characters.
|
||||
//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the
|
||||
//! style does not set. Setting one redefines the style: text in the style takes the new value
|
||||
//! where it had the style's old one and keeps its other changes.
|
||||
//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words
|
||||
//! or paragraphs of one, in the style's document. A character style styles exactly that text and
|
||||
//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches.
|
||||
//! `clearingOverrides` left out is false; true resets the text to the Normal style first.
|
||||
//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or
|
||||
//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in
|
||||
//! no other style. They do not add or remove styles.
|
||||
//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its
|
||||
//! look and is in the Normal style after.
|
||||
//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`,
|
||||
//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
|
||||
|
||||
use super::{
|
||||
ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref,
|
||||
function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text,
|
||||
text_of, this_range, typename_of, usize_of, whole_span, with_doc,
|
||||
};
|
||||
use crate::DocState;
|
||||
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs};
|
||||
use crate::script::dom::{Described, returns, typed};
|
||||
|
||||
/// The error of a style object whose style is gone.
|
||||
pub const STALE_STYLE: &str = "Stale style";
|
||||
/// The longest style name, in characters, after trimming.
|
||||
pub const MAX_STYLE_NAME: usize = 256;
|
||||
/// The most styles one run's style objects name.
|
||||
pub const MAX_HELD: usize = 4096;
|
||||
|
||||
/// A style that a run's style objects name: its document and the document's revert count then, its
|
||||
/// kind and its name now.
|
||||
struct Slot {
|
||||
uid: u64,
|
||||
reverts: u64,
|
||||
para: bool,
|
||||
name: String,
|
||||
live: bool,
|
||||
}
|
||||
|
||||
/// A document's uid and its character and paragraph style lists when the slots were last checked.
|
||||
type Seen = (u64, Shared<Vec<TextStyleDef>>, Shared<Vec<TextStyleDef>>);
|
||||
|
||||
/// The styles a run's style objects name; an object holds its slot's number.
|
||||
#[derive(Default)]
|
||||
pub(super) struct StyleState {
|
||||
slots: RefCell<Vec<Slot>>,
|
||||
seen: RefCell<Vec<Seen>>,
|
||||
}
|
||||
|
||||
/// Marks stale each style object whose style the command just run removed or renamed, so a style
|
||||
/// removed and made again under its name by later commands, or by later steps of the same batch,
|
||||
/// is another style. A document whose style lists did not change is not checked again. A live
|
||||
/// slot's style was in its document's list when the command started, so a step that removed or
|
||||
/// renamed it is in the trail's removed names.
|
||||
pub(in crate::script) fn after_command(h: &Host) {
|
||||
let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail);
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
if !slots.iter().any(|s| s.live) {
|
||||
return;
|
||||
}
|
||||
for slot in slots.iter_mut().filter(|x| x.live) {
|
||||
if trail.reverted.contains(&slot.uid)
|
||||
|| (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone())))
|
||||
{
|
||||
slot.live = false;
|
||||
}
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut seen = h.dom.text.styles.seen.borrow_mut();
|
||||
seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid));
|
||||
for st in s.documents() {
|
||||
let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles));
|
||||
if same {
|
||||
continue;
|
||||
}
|
||||
seen.retain(|(uid, ..)| *uid != st.uid);
|
||||
seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone()));
|
||||
for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) {
|
||||
slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name);
|
||||
}
|
||||
}
|
||||
for slot in slots.iter_mut().filter(|x| x.live) {
|
||||
if !s.documents().iter().any(|d| d.uid == slot.uid) {
|
||||
slot.live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The style objects' state when a savepoint was taken: each slot's name and whether it was
|
||||
/// live, and the style lists last checked.
|
||||
pub(in crate::script) struct Mark {
|
||||
slots: Vec<(String, bool)>,
|
||||
seen: Vec<Seen>,
|
||||
}
|
||||
|
||||
/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored.
|
||||
pub(in crate::script) fn mark(h: &Host) -> Mark {
|
||||
let styles = &h.dom.text.styles;
|
||||
let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect();
|
||||
Mark { slots, seen: styles.seen.borrow().clone() }
|
||||
}
|
||||
|
||||
/// Puts the style objects back as they were at `mark`, after the documents were put back to the
|
||||
/// savepoint taken with it. A slot added since then stays live only while its document has the
|
||||
/// style and no older live slot names it.
|
||||
pub(in crate::script) fn put_back(h: &Host, mark: Mark) {
|
||||
let styles = &h.dom.text.styles;
|
||||
let mut slots = styles.slots.borrow_mut();
|
||||
let kept = mark.slots.len();
|
||||
for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) {
|
||||
slot.name = name;
|
||||
slot.live = live;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
for i in kept..slots.len() {
|
||||
let (older, newer) = slots.split_at_mut(i);
|
||||
let Some(slot) = newer.first_mut() else { break };
|
||||
let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name);
|
||||
slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name));
|
||||
}
|
||||
*styles.seen.borrow_mut() = mark.seen;
|
||||
}
|
||||
|
||||
fn normal(para: bool) -> &'static str {
|
||||
if para { NORMAL_PARA } else { NORMAL_CHAR }
|
||||
}
|
||||
|
||||
fn cmd(para: bool, verb: &str) -> String {
|
||||
format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" })
|
||||
}
|
||||
|
||||
fn style_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyle" } else { "CharacterStyle" }
|
||||
}
|
||||
|
||||
fn list_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyles" } else { "CharacterStyles" }
|
||||
}
|
||||
|
||||
fn defs(st: &DocState, para: bool) -> &Vec<TextStyleDef> {
|
||||
if para { &st.doc.para_styles } else { &st.doc.char_styles }
|
||||
}
|
||||
|
||||
/// The document's style names of a kind, the Normal style first.
|
||||
fn names(st: &DocState, para: bool) -> Vec<String> {
|
||||
let mut out = vec![normal(para).to_string()];
|
||||
out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para)));
|
||||
out
|
||||
}
|
||||
|
||||
fn has_style(st: &DocState, para: bool, name: &str) -> bool {
|
||||
name == normal(para) || defs(st, para).iter().any(|d| d.name == name)
|
||||
}
|
||||
|
||||
fn stale() -> HostError {
|
||||
HostError::Error(STALE_STYLE.into())
|
||||
}
|
||||
|
||||
fn held_too_many() -> HostError {
|
||||
HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))
|
||||
}
|
||||
|
||||
/// The style object for the style `name` of the document `uid`: the same slot as every other
|
||||
/// object naming it in this run.
|
||||
fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer {
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
if slots.len() >= MAX_HELD {
|
||||
return Err(held_too_many());
|
||||
}
|
||||
slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true });
|
||||
slots.len() - 1
|
||||
}
|
||||
};
|
||||
Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)]))
|
||||
}
|
||||
|
||||
/// A style a style object names.
|
||||
struct Style {
|
||||
doc: Doc,
|
||||
para: bool,
|
||||
slot: usize,
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// The style `d` names, when it is an object of one of `classes` (with the kind each names).
|
||||
fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result<Style, HostError> {
|
||||
let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para)));
|
||||
let Some((handle, para)) = found else {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0))));
|
||||
};
|
||||
let [run, uid, slot] = handle.as_slice() else { return Err(stale()) };
|
||||
let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?;
|
||||
let slot = usize_of(*slot).ok_or_else(stale)?;
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?;
|
||||
if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) {
|
||||
s.live = false;
|
||||
return Err(stale());
|
||||
}
|
||||
Ok(Style { doc, para, slot, name: s.name.clone() })
|
||||
}
|
||||
|
||||
fn this_style(h: &Host, a: &[Data]) -> std::result::Result<Style, HostError> {
|
||||
style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)])
|
||||
}
|
||||
|
||||
/// Marks the slots of the styles `names` of the document `uid` as removed.
|
||||
fn forget(h: &Host, uid: u64, para: bool, names: &[String]) {
|
||||
for s in h.dom.text.styles.slots.borrow_mut().iter_mut() {
|
||||
if s.uid == uid && s.para == para && names.contains(&s.name) {
|
||||
s.live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A style name a script gave, trimmed.
|
||||
fn style_name(v: &Data) -> std::result::Result<String, HostError> {
|
||||
let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) };
|
||||
if s.len() > super::super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
|
||||
}
|
||||
let t = s.trim();
|
||||
if t.is_empty() {
|
||||
return Err(HostError::Range("a style name must not be empty".into()));
|
||||
}
|
||||
if t.chars().count() > MAX_STYLE_NAME {
|
||||
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
|
||||
}
|
||||
if t.chars().any(char::is_control) {
|
||||
return Err(HostError::Range("a style name must not hold control characters".into()));
|
||||
}
|
||||
Ok(t.to_string())
|
||||
}
|
||||
|
||||
/// Runs the style command `verb` of the kind on the document of `doc`.
|
||||
fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params))
|
||||
}
|
||||
|
||||
// ---- CharacterStyle and ParagraphStyle ----
|
||||
|
||||
fn style_name_get(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(this_style(h, a)?.name))
|
||||
}
|
||||
|
||||
/// `name = …`: renames the style; the Normal style keeps its name.
|
||||
fn style_name_set(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let to = style_name(arg(a, 1))?;
|
||||
if to == style.name {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
if style.name == normal(style.para) {
|
||||
return Err(HostError::Error(format!("{} cannot be renamed", style.name)));
|
||||
}
|
||||
if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) {
|
||||
return Err(HostError::Error(format!("a style named {to} already exists")));
|
||||
}
|
||||
run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?;
|
||||
forget(h, style.doc.uid, style.para, std::slice::from_ref(&to));
|
||||
if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) {
|
||||
s.name = to;
|
||||
s.live = true;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn style_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(doc_ref(h, this_style(h, a)?.doc.uid))
|
||||
}
|
||||
|
||||
fn style_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(style_class(this_style(h, a)?.para)))
|
||||
}
|
||||
|
||||
fn attributes(h: &Host, a: &[Data], class: &str) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)]))
|
||||
}
|
||||
|
||||
fn style_character_attributes(h: &Host, a: &[Data]) -> Answer {
|
||||
attributes(h, a, "CharacterStyleAttributes")
|
||||
}
|
||||
|
||||
fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer {
|
||||
attributes(h, a, "ParagraphStyleAttributes")
|
||||
}
|
||||
|
||||
/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after.
|
||||
fn style_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
if style.name == normal(style.para) {
|
||||
return Err(HostError::Error(format!("{} cannot be removed", style.name)));
|
||||
}
|
||||
run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?;
|
||||
forget(h, style.doc.uid, style.para, &[style.name]);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The text a style is applied to: a text range, a text frame, or the characters, words or
|
||||
/// paragraphs of one.
|
||||
fn target_span(h: &Host, d: &Data) -> std::result::Result<Span, HostError> {
|
||||
if handle_of(d, "TextFrame").is_some() {
|
||||
return Ok(whole_span(h, item_of(h, d)?)?.1);
|
||||
}
|
||||
const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"];
|
||||
if !TEXT.iter().any(|c| handle_of(d, c).is_some()) {
|
||||
return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into()));
|
||||
}
|
||||
span_of(h, d, &TEXT)
|
||||
}
|
||||
|
||||
/// `applyTo(textItem, clearingOverrides?)`.
|
||||
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let target = target_span(h, arg(a, 1))?;
|
||||
let clear = match arg(a, 2) {
|
||||
Data::Undefined => false,
|
||||
Data::Bool(b) => *b,
|
||||
_ => return Err(HostError::Type("clearingOverrides must be true or false".into())),
|
||||
};
|
||||
if target.item.doc.uid != style.doc.uid {
|
||||
return Err(HostError::Error("the text is in another document than the style".into()));
|
||||
}
|
||||
let (index, s, e, _) = resolve(h, target)?;
|
||||
h.charge_call(16 + (e - s) as u64)?;
|
||||
let (start, end) = if style.para {
|
||||
let (_, ba, bb) = para_range(&index, s, e);
|
||||
(ba, bb)
|
||||
} else {
|
||||
// An empty range inside text changes nothing; empty text takes the style on its runs.
|
||||
if s == e && index.len() > 0 {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
(index.byte(s, false), index.byte(e, true))
|
||||
};
|
||||
let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end});
|
||||
run(h, style.doc, style.para, "apply", &p)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- the attributes of a style ----
|
||||
|
||||
/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets.
|
||||
const CHAR_KEYS: [(&str, &str); 11] = [
|
||||
("size", "size"),
|
||||
("leading", "leading"),
|
||||
("tracking", "tracking"),
|
||||
("baselineShift", "baseline_shift"),
|
||||
("hScale", "h_scale"),
|
||||
("vScale", "v_scale"),
|
||||
("rotation", "rotation"),
|
||||
("underline", "underline"),
|
||||
("strikethrough", "strikethrough"),
|
||||
("font", "font_family"),
|
||||
("style", "font_style"),
|
||||
];
|
||||
|
||||
/// The script's `Justification` members and the alignments a paragraph style stores.
|
||||
const JUSTIFY: [(&str, &str); 7] = [
|
||||
("LEFT", "Left"),
|
||||
("CENTER", "Center"),
|
||||
("RIGHT", "Right"),
|
||||
("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"),
|
||||
("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"),
|
||||
("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"),
|
||||
("FULLJUSTIFY", "JustifyAll"),
|
||||
];
|
||||
|
||||
/// The style an attributes object belongs to and the attributes it sets.
|
||||
fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map<String, Value>), HostError> {
|
||||
let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" };
|
||||
let style = style_of(h, arg(a, 0), &[(class, para)])?;
|
||||
let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?;
|
||||
Ok((style, attrs))
|
||||
}
|
||||
|
||||
fn char_value(h: &Host, attr: Attr, m: &Map<String, Value>) -> Data {
|
||||
let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num);
|
||||
let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool);
|
||||
match attr {
|
||||
Attr::Size => n("size"),
|
||||
Attr::Leading => n("leading"),
|
||||
Attr::AutoLeading => match m.get("leading") {
|
||||
Some(Value::Null) => Data::Bool(true),
|
||||
Some(v) if v.is_number() => Data::Bool(false),
|
||||
_ => Data::Undefined,
|
||||
},
|
||||
Attr::Tracking => n("tracking"),
|
||||
Attr::BaselineShift => n("baseline_shift"),
|
||||
Attr::HorizontalScale => n("h_scale"),
|
||||
Attr::VerticalScale => n("v_scale"),
|
||||
Attr::Rotation => n("rotation"),
|
||||
Attr::Underline => b("underline"),
|
||||
Attr::StrikeThrough => b("strikethrough"),
|
||||
Attr::TextFont => match m.get("font_family").and_then(Value::as_str) {
|
||||
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `typename` of a style's `characterAttributes`, which throws once the style is gone.
|
||||
fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer {
|
||||
attrs_of(h, a, false)?;
|
||||
Ok(text("CharacterAttributes"))
|
||||
}
|
||||
|
||||
/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone.
|
||||
fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer {
|
||||
attrs_of(h, a, true)?;
|
||||
Ok(text("ParagraphAttributes"))
|
||||
}
|
||||
|
||||
fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer {
|
||||
let (_, m) = attrs_of(h, a, false)?;
|
||||
Ok(char_value(h, attr, &m))
|
||||
}
|
||||
|
||||
/// Redefines the style with `attrs`, unless they are what it has.
|
||||
fn redefine(h: &Host, style: &Style, old: &Map<String, Value>, attrs: Map<String, Value>) -> Answer {
|
||||
if attrs == *old {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
|
||||
let (style, old) = attrs_of(h, a, false)?;
|
||||
// `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph
|
||||
// with the default justification.
|
||||
let base = CharStyle::default();
|
||||
let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size);
|
||||
let leading = old.get("leading").and_then(Value::as_f64);
|
||||
let sample = CharStyle { size, leading, ..base };
|
||||
let t = TextObject::point(Point::default(), "", sample.clone());
|
||||
let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?;
|
||||
let mut attrs = old.clone();
|
||||
for (k, v) in param.as_object().into_iter().flatten() {
|
||||
let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue };
|
||||
let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() };
|
||||
attrs.insert((*key).to_string(), v);
|
||||
}
|
||||
redefine(h, &style, &old, attrs)
|
||||
}
|
||||
|
||||
fn para_key(attr: ParaAttr) -> &'static str {
|
||||
match attr {
|
||||
ParaAttr::Justification => "justify",
|
||||
ParaAttr::FirstLineIndent => "first_line_indent",
|
||||
ParaAttr::LeftIndent => "left_indent",
|
||||
ParaAttr::RightIndent => "right_indent",
|
||||
ParaAttr::SpaceBefore => "space_before",
|
||||
ParaAttr::SpaceAfter => "space_after",
|
||||
}
|
||||
}
|
||||
|
||||
fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer {
|
||||
let (_, m) = attrs_of(h, a, true)?;
|
||||
let v = m.get(para_key(attr));
|
||||
Ok(match attr {
|
||||
ParaAttr::Justification => match v.and_then(Value::as_str) {
|
||||
Some("Auto") => text("Justification.LEFT"),
|
||||
Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
_ => v.and_then(Value::as_f64).map_or(Data::Undefined, num),
|
||||
})
|
||||
}
|
||||
|
||||
fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
|
||||
let (style, old) = attrs_of(h, a, true)?;
|
||||
let (_, _, wants) = para_param(attr, name, arg(a, 1))?;
|
||||
let value = match (&wants, attr) {
|
||||
(Data::String(s), ParaAttr::Justification) => {
|
||||
let m = s.strip_prefix("Justification.").unwrap_or(s);
|
||||
let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j);
|
||||
json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?)
|
||||
}
|
||||
(Data::Number(n), _) => json!(n),
|
||||
_ => return Err(HostError::Type(format!("{name} must be a finite number"))),
|
||||
};
|
||||
let mut attrs = old.clone();
|
||||
attrs.insert(para_key(attr).to_string(), value);
|
||||
redefine(h, &style, &old, attrs)
|
||||
}
|
||||
|
||||
/// The body of a member that captures what it reads or sets.
|
||||
type Body = Rc<dyn Fn(&Host, &[Data]) -> Answer>;
|
||||
|
||||
/// Members whose getter and setter each charge the call, as [`function`] does.
|
||||
fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember {
|
||||
let wrap = |f: Body| -> HostFunction {
|
||||
let l = link.clone();
|
||||
Rc::new(move |a: Vec<Data>| {
|
||||
let h = super::super::current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::super::data_size).sum::<u64>())?;
|
||||
f(&h, &a)
|
||||
})
|
||||
};
|
||||
HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) }
|
||||
}
|
||||
|
||||
fn char_members(link: &Link) -> Vec<Described> {
|
||||
ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| {
|
||||
let data_type = match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
};
|
||||
(name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)), typed(data_type))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn para_members(link: &Link) -> Vec<Described> {
|
||||
PARA_ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| {
|
||||
let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" };
|
||||
(name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)), typed(data_type))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---- CharacterStyles and ParagraphStyles ----
|
||||
|
||||
/// What a collection of styles lists: a document's styles, or those a text range uses.
|
||||
enum Of {
|
||||
Doc(Doc),
|
||||
Range(Span),
|
||||
}
|
||||
|
||||
fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> {
|
||||
let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) {
|
||||
(Some(_), _) => false,
|
||||
(_, Some(_)) => true,
|
||||
_ => return Err(HostError::Type("this is not a CharacterStyles".into())),
|
||||
};
|
||||
let class = list_class(para);
|
||||
let len = handle_of(d, class).map_or(0, |v| v.len());
|
||||
Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para))
|
||||
}
|
||||
|
||||
/// The document and the names of the styles a collection lists.
|
||||
fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec<String>), HostError> {
|
||||
match of {
|
||||
Of::Doc(doc) => {
|
||||
let names = with_doc(h, *doc, |_, st| names(st, para));
|
||||
h.charge_call(names.len() as u64)?;
|
||||
Ok((*doc, names))
|
||||
}
|
||||
Of::Range(r) => {
|
||||
let (index, s, e, _) = resolve(h, *r)?;
|
||||
let used = with_doc(h, r.item.doc, |_, st| {
|
||||
let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
|
||||
let used: Vec<Option<String>> = if para {
|
||||
let (paras, _, _) = para_range(&index, s, e);
|
||||
paras.map(|i| t.para_at(i).style_name.clone()).collect()
|
||||
} else {
|
||||
styles_in(t, index.byte(s, false), index.byte(e, true), false)?.into_iter().map(|(c, _)| c.style_name).collect()
|
||||
};
|
||||
h.charge_call(used.len() as u64)?;
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for n in used {
|
||||
let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string());
|
||||
if !out.contains(&n) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push(normal(para).to_string());
|
||||
}
|
||||
Ok::<_, HostError>(out)
|
||||
})?;
|
||||
Ok((r.item.doc, used))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
Ok(num(float(listed(h, &of, para)?.1.len() as u64)))
|
||||
}
|
||||
|
||||
fn list_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, _) = list_of(h, arg(a, 0))?;
|
||||
match of {
|
||||
Of::Doc(doc) => Ok(doc_ref(h, doc.uid)),
|
||||
Of::Range(r) => {
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, "TextRange"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let found = match &of {
|
||||
Of::Doc(doc) => with_doc(h, *doc, |_, st| match i {
|
||||
0 => Some(normal(para).to_string()),
|
||||
_ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(),
|
||||
})
|
||||
.map(|n| (*doc, n)),
|
||||
Of::Range(_) => {
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
names.get(i).cloned().map(|n| (doc, n))
|
||||
}
|
||||
};
|
||||
match found {
|
||||
Some((doc, name)) => style_ref(h, doc.uid, para, &name),
|
||||
None => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
if name.len() > super::super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
match names.iter().find(|n| *n == name) {
|
||||
Some(n) => style_ref(h, doc.uid, para, n),
|
||||
None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => list_by_name(h, a),
|
||||
Data::Number(_) => match list_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document of a document's collection; a range's collection cannot be changed.
|
||||
fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> {
|
||||
match list_of(h, arg(a, 0))? {
|
||||
(Of::Doc(doc), para) => Ok((doc, para)),
|
||||
(Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `add(name)`: a new style that sets no attributes.
|
||||
fn list_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let name = style_name(arg(a, 1))?;
|
||||
if with_doc(h, doc, |_, st| has_style(st, para, &name)) {
|
||||
return Err(HostError::Error(format!("a style named {name} already exists")));
|
||||
}
|
||||
// The new style needs a slot of its own: a run that names as many styles as it may adds none.
|
||||
if h.dom.text.styles.slots.borrow().len() >= MAX_HELD {
|
||||
return Err(held_too_many());
|
||||
}
|
||||
run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?;
|
||||
// An object of a removed style of this name stays stale.
|
||||
forget(h, doc.uid, para, std::slice::from_ref(&name));
|
||||
style_ref(h, doc.uid, para, &name)
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every style but the Normal style, in one command.
|
||||
fn list_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let gone: Vec<String> = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect();
|
||||
if gone.is_empty() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
run(h, doc, para, "delete", &json!({"names": gone}))?;
|
||||
forget(h, doc.uid, para, &gone);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn doc_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer {
|
||||
let r = this_range(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, list_class(para)))
|
||||
}
|
||||
|
||||
fn range_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, false)
|
||||
}
|
||||
|
||||
fn range_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, true)
|
||||
}
|
||||
|
||||
/// `document.characterStyles` and `document.paragraphStyles`.
|
||||
pub(in crate::script) fn doc_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("characterStyles", get(l, doc_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
|
||||
("paragraphStyles", get(l, doc_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
|
||||
])
|
||||
}
|
||||
|
||||
/// `TextRange.characterStyles` and `TextRange.paragraphStyles`.
|
||||
pub(super) fn range_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("characterStyles", get(l, range_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
|
||||
("paragraphStyles", get(l, range_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
|
||||
])
|
||||
}
|
||||
|
||||
/// The style classes.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let style = |para: bool| {
|
||||
let mut members = named(vec![
|
||||
("typename", get(l, style_typename), typed("string")),
|
||||
("name", property(l, style_name_get, style_name_set), typed("string")),
|
||||
("parent", get(l, style_parent), typed("Document")),
|
||||
("applyTo", method(l, style_apply_to), returns("undefined", &[("textItem", "*"), ("clearingOverrides", "boolean")])),
|
||||
("remove", method(l, style_remove), returns("undefined", &[])),
|
||||
]);
|
||||
if para {
|
||||
members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes), typed("ParagraphStyleAttributes")));
|
||||
members.push(super::super::later(l, "ParagraphStyle", "characterAttributes"));
|
||||
} else {
|
||||
members.push(("characterAttributes".into(), get(l, style_character_attributes), typed("CharacterStyleAttributes")));
|
||||
}
|
||||
class(style_class(para), None, members, None)
|
||||
};
|
||||
let list = |para: bool| {
|
||||
let name = list_class(para);
|
||||
let item = style_class(para);
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![
|
||||
("typename", typename_of(name), typed("string")),
|
||||
("length", get(l, list_length), typed("number")),
|
||||
("parent", get(l, list_parent), typed("*")),
|
||||
("index", method(l, list_index), returns(item, &[("itemKey", "*")])),
|
||||
("getByName", method(l, list_by_name), returns(item, &[("name", "string")])),
|
||||
("add", method(l, list_add), returns(item, &[("name", "string")])),
|
||||
("removeAll", method(l, list_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, list_at)),
|
||||
)
|
||||
};
|
||||
let mut chars = named(vec![("typename", get(l, attrs_typename_char), typed("string"))]);
|
||||
chars.extend(char_members(l));
|
||||
let mut paras = named(vec![("typename", get(l, attrs_typename_para), typed("string"))]);
|
||||
paras.extend(para_members(l));
|
||||
vec![
|
||||
style(false),
|
||||
style(true),
|
||||
list(false),
|
||||
list(true),
|
||||
class("CharacterStyleAttributes", None, chars, None),
|
||||
class("ParagraphStyleAttributes", None, paras, None),
|
||||
]
|
||||
}
|
||||
@@ -48,6 +48,7 @@
|
||||
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
|
||||
//! documents back and keeps the engine's globals; an internal error drops the engine.
|
||||
|
||||
pub mod actions;
|
||||
pub mod console;
|
||||
pub mod dialogs;
|
||||
pub mod dollar;
|
||||
@@ -206,6 +207,8 @@ pub(crate) struct Request {
|
||||
pub locale: String,
|
||||
/// The answers to the dialogs of a run with nobody to ask, in order.
|
||||
pub answers: Vec<DialogAnswer>,
|
||||
/// The actions `app.doScript` can play.
|
||||
pub actions: Vec<actions::Playable>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -806,6 +809,15 @@ struct Host {
|
||||
args: RefCell<(Data, u64)>,
|
||||
/// The run's state of the script object model (`app`).
|
||||
dom: dom::State,
|
||||
/// The actions `app.doScript` can play.
|
||||
actions: Vec<actions::Playable>,
|
||||
/// The index of each open document's active artboard as the run starts, by document uid. The
|
||||
/// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it.
|
||||
active_artboards: Vec<(u64, usize)>,
|
||||
/// The artboards the Artboard tool had selected in the active document as the run starts (two or
|
||||
/// more), with that document's uid. The run gives the tool fresh state, which drops them, so the
|
||||
/// steps `app.doScript` plays read them here.
|
||||
artboard_picks: Option<(u64, Vec<usize>)>,
|
||||
/// The documents open when the run began as the person last left them, each with its own file
|
||||
/// and the file it was read from ([`crate::DocState::as_person_left`],
|
||||
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
|
||||
@@ -1283,6 +1295,7 @@ fn note_ids(s: &mut Session) {
|
||||
/// it, for a result that cannot cross to the script.
|
||||
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<Savepoint>)> {
|
||||
raise_ids(s);
|
||||
s.script_style_trail = StyleTrail::start(s);
|
||||
let mutating = waits_for_tool_edit(id);
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back.
|
||||
let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id));
|
||||
@@ -1330,6 +1343,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
Ok((v, objects, bytes, save))
|
||||
}
|
||||
Err(e) => {
|
||||
s.script_style_trail = StyleTrail::default();
|
||||
if let Some(save) = save
|
||||
&& !save.restore(s)
|
||||
{
|
||||
@@ -1408,9 +1422,76 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
}
|
||||
}
|
||||
dom::after_command(host, before);
|
||||
// Style objects follow only a command that is kept.
|
||||
if crossed.is_ok() {
|
||||
dom::after_kept_command(host);
|
||||
} else {
|
||||
session.borrow_mut().script_style_trail = StyleTrail::default();
|
||||
}
|
||||
crossed.map(|data| (data, value))
|
||||
}
|
||||
|
||||
/// A document's uid, revert count, and character and paragraph style lists.
|
||||
pub(crate) type StyleLists =
|
||||
(u64, u64, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>);
|
||||
|
||||
/// What the steps of a command a script runs did to the documents' style lists
|
||||
/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step
|
||||
/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the
|
||||
/// documents a step reverted.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct StyleTrail {
|
||||
lists: Vec<StyleLists>,
|
||||
pub(crate) gone: std::collections::HashSet<(u64, bool, String)>,
|
||||
pub(crate) reverted: Vec<u64>,
|
||||
}
|
||||
|
||||
impl StyleTrail {
|
||||
/// A trail that starts from the documents' style lists now.
|
||||
fn start(s: &Session) -> Self {
|
||||
let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect();
|
||||
StyleTrail { lists, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// After a step of a batch a script runs: notes the styles the step removed or renamed and the
|
||||
/// documents it reverted, so the style objects see a style the batch removed and made again under
|
||||
/// its name as another style ([`dom::after_kept_command`]). The trail keeps one copy of each open
|
||||
/// document's lists, however many steps change them.
|
||||
pub(crate) fn note_style_lists(s: &mut Session) {
|
||||
let trail = &mut s.script_style_trail;
|
||||
trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid));
|
||||
for st in &s.docs {
|
||||
let (c, p) = (&st.doc.char_styles, &st.doc.para_styles);
|
||||
let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else {
|
||||
trail.lists.push((st.uid, st.reverts, c.clone(), p.clone()));
|
||||
continue;
|
||||
};
|
||||
if last.1 != st.reverts {
|
||||
if !trail.reverted.contains(&st.uid) {
|
||||
trail.reverted.push(st.uid);
|
||||
}
|
||||
} else {
|
||||
for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] {
|
||||
if vectorcraft_doc::Shared::ptr_eq(old, new) {
|
||||
continue;
|
||||
}
|
||||
let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect();
|
||||
for d in old.iter().filter(|d| !names.contains(d.name.as_str())) {
|
||||
trail.gone.insert((st.uid, para, d.name.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
*last = (st.uid, st.reverts, c.clone(), p.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn retained_style_lists(s: &Session) -> usize {
|
||||
s.script_style_trail.lists.len()
|
||||
}
|
||||
|
||||
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
|
||||
/// of a crossing throws a `RangeError`.
|
||||
fn vc_document(host: &Host) -> std::result::Result<Data, HostError> {
|
||||
@@ -2063,6 +2144,9 @@ impl Session {
|
||||
if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() {
|
||||
return Err(EngineError::Other(NO_RECOVERY_COPY.to_string()));
|
||||
}
|
||||
// The Artboard tool's selection, which the fresh tool state below drops.
|
||||
let picks = cmd::artboard_tool_picks(self);
|
||||
let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks));
|
||||
self.reset_tool();
|
||||
let open: Vec<u64> = self.docs.iter().map(|d| d.uid).collect();
|
||||
self.script_high_water.retain(|uid, _| open.contains(uid));
|
||||
@@ -2182,6 +2266,9 @@ impl Session {
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
dom: dom::State::new(heap_bytes),
|
||||
actions: request.actions,
|
||||
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
|
||||
artboard_picks,
|
||||
run_docs: RefCell::new(
|
||||
self.docs
|
||||
.iter()
|
||||
|
||||
@@ -189,6 +189,7 @@ impl Session {
|
||||
startup_loading: None,
|
||||
startup_failures: vec![],
|
||||
script_high_water: Default::default(),
|
||||
script_style_trail: Default::default(),
|
||||
script_in_run: false,
|
||||
window_views: vec![],
|
||||
script_copy_first: cfg!(target_arch = "wasm32"),
|
||||
|
||||
@@ -129,6 +129,9 @@ impl Session {
|
||||
self.execute_spec(spec, id, params)
|
||||
};
|
||||
self.reading = outer;
|
||||
if self.script_in_run && self.depth > 0 && r.is_ok() {
|
||||
crate::script::note_style_lists(self);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ mod css;
|
||||
mod curvature_circle;
|
||||
mod cut;
|
||||
mod dashalign;
|
||||
mod dcs;
|
||||
pub(super) mod dcs;
|
||||
mod delete_keeps_joined;
|
||||
mod distort;
|
||||
mod docsetup;
|
||||
@@ -175,6 +175,7 @@ mod repeat_edit;
|
||||
mod save;
|
||||
mod saveoptions;
|
||||
mod scalestrokes;
|
||||
mod script_actions;
|
||||
mod script_console;
|
||||
mod script_dialogs;
|
||||
mod script_dollar;
|
||||
@@ -185,6 +186,7 @@ mod script_include;
|
||||
mod script_io;
|
||||
mod script_run;
|
||||
mod script_scriptui;
|
||||
mod script_styles;
|
||||
mod script_tags;
|
||||
mod script_text;
|
||||
mod script_threads;
|
||||
@@ -5169,6 +5171,36 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() {
|
||||
assert!(!s.doc().unwrap().selection.contains(b));
|
||||
}
|
||||
|
||||
/// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With
|
||||
/// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that
|
||||
/// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked
|
||||
/// adds its corner. A Ctrl/Cmd-click (the Selection tool, lent) leaves the picks as they are.
|
||||
#[test]
|
||||
fn corner_widgets_pick_corners_across_paths_through_the_session() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
|
||||
let all = json!([[0, 0], [0, 1], [0, 2], [0, 3]]);
|
||||
let start = json!({"items": [{"id": a.0, "anchors": [[0, 0]]}, {"id": b.0, "anchors": all}]});
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
let click = |s: &mut Session, x: f64, y: f64, mods: vectorcraft_tools::Mods| {
|
||||
s.execute("select.anchorsMany", &start).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, x, y).with_mods(mods), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, x, y).with_mods(mods), v).unwrap();
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert!(sel.contains(a) && sel.contains(b), "both stay selected");
|
||||
(sel.partial(a).cloned(), sel.partial(b).cloned())
|
||||
};
|
||||
let shift = vectorcraft_tools::Mods { shift: true, ..Default::default() };
|
||||
// The top-right widget of b.
|
||||
assert_eq!(click(&mut s, 390.0, 110.0, shift), (Some([(0, 0)].into()), Some([(0, 0), (0, 2), (0, 3)].into())));
|
||||
// The top-right widget of a, not picked.
|
||||
assert_eq!(click(&mut s, 190.0, 110.0, shift), (Some([(0, 0), (0, 1)].into()), None));
|
||||
let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() };
|
||||
assert_eq!(click(&mut s, 190.0, 110.0, cmd), (Some([(0, 0)].into()), None), "a Ctrl/Cmd-click leaves the picks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_commands_reject_bad_anchors_before_modifying_geometry() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -776,6 +776,33 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() {
|
||||
let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap();
|
||||
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
|
||||
assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}");
|
||||
// The fix is the color to store: the stain mixes it half way to black again, and the result
|
||||
// just meets AA against white.
|
||||
let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap();
|
||||
assert_eq!(r["normalText"]["aa"], false, "{r}");
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
let drawn = fix.lerp(&vectorcraft_color::Color::BLACK, 0.5).to_rgb_uncalibrated();
|
||||
let got = vectorcraft_color::wcag::contrast_ratio(drawn, [1.0; 3]);
|
||||
assert!((4.5..4.57).contains(&got), "{fix:?} draws {drawn:?}: {got}");
|
||||
}
|
||||
|
||||
/// A pick for a picked symbol object with a fill of None puts a solid color there, which the
|
||||
/// instance's stain mixes like any other, so the Color Wheel's contrast lines measure it stained.
|
||||
#[test]
|
||||
fn a_pick_for_a_picked_symbol_object_with_no_fill_is_measured_with_the_stain() {
|
||||
let mut s = picked_symbol_part();
|
||||
let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance;
|
||||
s.active_mut().unwrap().selection.symbol_part = None;
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap();
|
||||
s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
|
||||
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({"against": "#000000", "opacity": 100})).unwrap();
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let white = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(1.0, 1.0, 1.0)));
|
||||
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
|
||||
assert!((white - want).abs() < 1e-3, "a white pick stained half way to black: {white} against {want}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -877,3 +904,309 @@ fn a_fill_of_none_has_no_color_to_measure() {
|
||||
assert!(e.contains("has no color"), "{e}");
|
||||
assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok());
|
||||
}
|
||||
|
||||
fn fix_color(v: &Value) -> vectorcraft_color::Color {
|
||||
crate::cmd::color_value(v).unwrap_or_else(|| panic!("not a color: {v}"))
|
||||
}
|
||||
|
||||
fn oklch_hue(c: &vectorcraft_color::Color) -> f64 {
|
||||
let [_, a, b] = vectorcraft_color::libraries::to_oklab(c);
|
||||
b.atan2(a).to_degrees()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_color_answers_the_closest_passing_color_of_its_hue() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap();
|
||||
assert_eq!(r["for"], "normalText");
|
||||
let aa = fix_color(&r["fix"]["aa"]);
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
|
||||
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
|
||||
let want = oklch_hue(&vectorcraft_color::Color::from_hex("#fdc96e").unwrap());
|
||||
assert!((oklch_hue(&aa) - want).abs() < 1.0, "{} {want}", oklch_hue(&aa));
|
||||
assert!(matches!(aa, vectorcraft_color::Color::Rgb { .. }), "an RGB color answers RGB: {aa:?}");
|
||||
// White on #355F78 is 6.87:1 and black 3.05:1, so no color reaches AAA's 7:1.
|
||||
assert!(r["fix"]["aaa"].is_null(), "{r}");
|
||||
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
|
||||
let aaa = s.execute("color.contrast", &json!({"color": large["fix"]["aaa"], "against": "#355f78"})).unwrap();
|
||||
assert!((4.5..4.57).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}");
|
||||
}
|
||||
|
||||
/// The canvas paints a color with 8 bits per channel, so a fix passes once rounded that way too:
|
||||
/// #777777 on white is 4.48:1, a gray of about 118.7/255 meets 4.5:1 but paints as #777777 again,
|
||||
/// and the fix has to paint as #767676 (4.54:1) or darker.
|
||||
#[test]
|
||||
fn a_fix_passes_as_the_canvas_paints_it() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap();
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
let painted = fix.to_rgb_uncalibrated().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0);
|
||||
let got = vectorcraft_color::wcag::contrast_ratio(painted, [1.0; 3]);
|
||||
assert!(got >= 4.5, "{fix:?} paints as {painted:?}: {got}");
|
||||
// The fix is the closest one: the gray one 8-bit step lighter fails.
|
||||
let lighter = painted.map(|v| (v + 1.0 / 255.0).min(1.0));
|
||||
assert!(vectorcraft_color::wcag::contrast_ratio(lighter, [1.0; 3]) < 4.5, "{fix:?} paints as {painted:?}");
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff"})).unwrap();
|
||||
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
|
||||
}
|
||||
|
||||
/// The backdrop shows 100 % K alone as `color.contrast` measures it under each Appearance of Black,
|
||||
/// so the Color Wheel's contrast lines use the same color.
|
||||
#[test]
|
||||
fn the_backdrop_shows_black_as_the_appearance_of_black_setting_does() {
|
||||
let k = vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let mut s = Session::new();
|
||||
let p = json!({"color": serde_json::to_value(k).unwrap(), "against": "#ffffff"});
|
||||
let (accurate, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
|
||||
assert_ne!(backdrop.shown(&cms, &k), [0.0; 3]);
|
||||
s.prefs.black_on_screen = "rich".into();
|
||||
let (rich, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
|
||||
assert_eq!(backdrop.shown(&cms, &k), [0.0; 3]);
|
||||
assert!(ratio(&rich) > ratio(&accurate), "{rich} {accurate}");
|
||||
}
|
||||
|
||||
/// A translucent fix also meets the minimum with the color, the opacity, the background and the
|
||||
/// composited pixel rounded to 8 bits per channel.
|
||||
#[test]
|
||||
fn a_translucent_fix_passes_at_eight_bits() {
|
||||
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
|
||||
let at_eight_bits = |fix: &vectorcraft_color::Color, opacity: f32, against: f32| {
|
||||
let (a, b) = (eight(opacity), eight(against));
|
||||
let pixel = fix.to_rgb_uncalibrated().map(|c| eight(eight(c) * a + b * (1.0 - a)));
|
||||
vectorcraft_color::wcag::contrast_ratio(pixel, [b; 3])
|
||||
};
|
||||
let mut s = Session::new();
|
||||
// A gray can pass only before rounding: #808080 at 91.1 % over black measures 4.53:1, and at
|
||||
// 232 / 255 its pixel is #747474 (4.49:1).
|
||||
let r = s.execute("color.contrast", &json!({"color": "#707070", "against": "#000000", "opacity": 91.1})).unwrap();
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
assert!(at_eight_bits(&fix, 0.911, 0.0) >= 4.5, "{fix:?}");
|
||||
// #040404 at 195 / 255 over a gray of 137.51 / 255 measures 4.5002:1, and over 138 / 255 it is
|
||||
// 4.4965:1.
|
||||
let bg = 137.51 / 255.0;
|
||||
let p = json!({"color": "#303030", "against": [bg, bg, bg], "opacity": 19500.0 / 255.0});
|
||||
let r = s.execute("color.contrast", &p).unwrap();
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
assert!(at_eight_bits(&fix, 195.0 / 255.0, bg) >= 4.5, "{fix:?}");
|
||||
// Black at 41.7 % over white measures 3.008:1, and its pixel at 8 bits is 2.995:1, so no gray
|
||||
// at that opacity gets a fix.
|
||||
let p = json!({"color": "#202020", "against": "#ffffff", "opacity": 41.7, "for": "graphics"});
|
||||
let r = s.execute("color.contrast", &p).unwrap();
|
||||
assert_eq!(r["graphics"]["aa"], false, "{r}");
|
||||
assert!(r["fix"]["aa"].is_null(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
|
||||
assert_eq!(r["fix"], json!({"aa": null, "aaa": null}));
|
||||
let g = s.execute("color.contrast", &json!({"color": "#cccccc", "against": "#ffffff", "for": "graphics"})).unwrap();
|
||||
assert_eq!(g["for"], "graphics");
|
||||
let fix = g["fix"].as_object().unwrap();
|
||||
assert_eq!(fix.keys().collect::<Vec<_>>(), ["aa"], "{g}");
|
||||
let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap();
|
||||
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
|
||||
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
|
||||
assert!(large["fix"]["aa"].is_null(), "4.49:1 meets large text AA: {large}");
|
||||
assert!(!large["fix"]["aaa"].is_null(), "{large}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_color_answers_a_cmyk_fix() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": {"c": 0, "m": 40, "y": 70, "k": 20}, "against": "#355f78"})).unwrap();
|
||||
assert_eq!(r["normalText"]["aa"], false, "{r}");
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
assert!(matches!(fix, vectorcraft_color::Color::Cmyk { .. }), "{fix:?}");
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
|
||||
assert!(ratio(&back) >= 4.5, "{back}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() {
|
||||
let mut s = Session::new();
|
||||
// #808080 at 50 % over white draws as a light gray: black at 50 % draws 0.5 gray, 3.98:1, which
|
||||
// meets large text AA (3:1) but not AAA (4.5:1).
|
||||
let p = json!({"color": "#808080", "against": "#ffffff", "opacity": 50, "for": "largeText"});
|
||||
let r = s.execute("color.contrast", &p).unwrap();
|
||||
assert_eq!(r["largeText"]["aa"], false, "{r}");
|
||||
assert!(r["fix"]["aaa"].is_null(), "no gray at 50 % reaches 4.5:1: {r}");
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff", "opacity": 50})).unwrap();
|
||||
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
|
||||
}
|
||||
|
||||
/// A square with a 50 % top fill row over locked orange, with and without a lower fill row and in a
|
||||
/// Screen group or not: isolating the object's blending leaves what a translucent Normal row draws
|
||||
/// as it is, on the canvas and in the answer, for each blend mode of the object.
|
||||
#[test]
|
||||
fn isolation_leaves_a_translucent_normal_row_as_it_draws() {
|
||||
let id = |v: Value| v["id"].as_u64().unwrap();
|
||||
for blend in ["normal", "multiply", "screen", "difference", "overlay"] {
|
||||
for fill in ["#808080", "#ffffff", "#2040a0"] {
|
||||
for lower in [false, true] {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let n = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
|
||||
if lower {
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
}
|
||||
let st = s.active().unwrap();
|
||||
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
|
||||
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": top, "color": fill, "opacity": 50})).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
s.execute("transparency.set", &json!({"item": null, "blend": blend})).unwrap();
|
||||
if lower {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("transparency.set", &json!({"blend": "screen"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [n]})).unwrap();
|
||||
}
|
||||
let plain = s.execute("color.contrast", &json!({})).unwrap();
|
||||
let (p, drawn) = canvas_ratio(&s, &plain);
|
||||
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
|
||||
let isolated = s.execute("color.contrast", &json!({})).unwrap();
|
||||
let (q, _) = canvas_ratio(&s, &isolated);
|
||||
let case = format!("{blend} {fill} lower row and group: {lower}");
|
||||
assert_eq!(p, q, "the canvas draws the same: {case}");
|
||||
assert!((ratio(&plain) - ratio(&isolated)).abs() < 1e-6, "{case}: {plain} {isolated}");
|
||||
assert!((ratio(&plain) - drawn).abs() < 0.02, "{case}: {plain} against {drawn}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Two squares over locked orange, each with a 50 % white top fill over a blue Multiply fill, one
|
||||
/// isolating its blending: the blue multiplies with the orange in one and draws over nothing in the
|
||||
/// other, so the white draws over different rows and there is no one answer. A given background
|
||||
/// stands for the rows below and answers.
|
||||
#[test]
|
||||
fn a_translucent_row_over_a_blending_row_in_objects_of_different_isolation_has_no_one_answer() {
|
||||
let mut s = session();
|
||||
let id = |v: Value| v["id"].as_u64().unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 180, "height": 180})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let square = |s: &mut Session, x: i32, isolate: bool| {
|
||||
let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
|
||||
let top = items.iter().rposition(|i| i.is_fill()).unwrap();
|
||||
let lower = items.iter().position(|i| i.is_fill()).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": lower, "blend": "multiply"})).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
if isolate {
|
||||
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
|
||||
}
|
||||
n
|
||||
};
|
||||
let a = square(&mut s, 30, false);
|
||||
let b = square(&mut s, 120, true);
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let ra = ratio(&s.execute("color.contrast", &json!({})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
let rb = ratio(&s.execute("color.contrast", &json!({})).unwrap());
|
||||
assert!((ra - rb).abs() > 0.1, "the white draws over different rows: {ra} {rb}");
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("the selected objects' colors differ"), "{e}");
|
||||
s.execute("color.contrast", &json!({"against": "#000000"})).unwrap();
|
||||
// A blending row at no opacity does not show, so the isolation no longer changes the answer.
|
||||
for n in [a, b] {
|
||||
let st = s.active().unwrap();
|
||||
let lower = st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [n], "index": lower, "opacity": 0})).unwrap();
|
||||
}
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("color.contrast", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// A Difference square centered on the edge between locked black and white art: the art behind it
|
||||
/// is not one color where it is read, so no one color stands for it; a given background answers,
|
||||
/// and over one color the background is read as before.
|
||||
#[test]
|
||||
fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
// Without the default stroke, which would cover the edge.
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
|
||||
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("is not one color where it is read") && e.contains("give `against`"), "{e}");
|
||||
let given = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
|
||||
assert!((ratio(&given) - 21.0).abs() < 1e-6, "white minus white is black: {given}");
|
||||
// In Normal mode the color is drawn as it is, over the background read as one color.
|
||||
s.execute("transparency.set", &json!({"blend": "normal"})).unwrap();
|
||||
s.execute("color.contrast", &json!({})).unwrap();
|
||||
// Moved over the white art alone, the square blends with one color again.
|
||||
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 40, "dy": 0})).unwrap();
|
||||
let r = s.execute("color.contrast", &json!({})).unwrap();
|
||||
assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}");
|
||||
}
|
||||
|
||||
/// A Difference square over a white square in a 50 % group that isolates its blending, over the
|
||||
/// edge between black and white art: the square blends only with the white inside the group, so
|
||||
/// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer.
|
||||
#[test]
|
||||
fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() {
|
||||
let mut s = session();
|
||||
let id = |v: Value| v["id"].as_u64().unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
|
||||
s.execute("object.group", &json!({"ids": [back, square]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [square]})).unwrap();
|
||||
s.execute("color.contrast", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// With a fill of None, what a pick would be measured against is still read: the Color Wheel's
|
||||
/// contrast lines show where a solid color in its place passes.
|
||||
#[test]
|
||||
fn a_pick_for_a_fill_of_none_is_measured_against_the_background() {
|
||||
let mut s = blended_over_red("normal");
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
|
||||
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({})).unwrap();
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let black = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(0.0, 0.0, 0.0)));
|
||||
let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 0.0, 0.0]);
|
||||
assert!((black - want).abs() < 1e-3, "black over the red art: {black} against {want}");
|
||||
assert_eq!(backdrop.against_hex(), "#ff0000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_takes_only_the_three_categories() {
|
||||
let mut s = Session::new();
|
||||
for bad in [json!("NormalText"), json!("aa"), json!(1), json!(true)] {
|
||||
let e = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "for": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("`for` must be one of normalText, largeText, graphics"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// Cyan solid on the top row, PANTONE 185 C at 50% on the left column.
|
||||
fn two_plates() -> Vec<u8> {
|
||||
pub(crate) fn two_plates() -> Vec<u8> {
|
||||
single_file(
|
||||
&[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))],
|
||||
"%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n",
|
||||
@@ -267,6 +267,33 @@ fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_cor
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a DCS file puts
|
||||
/// the file's image between the corners and draws its clipping path through them.
|
||||
#[test]
|
||||
fn place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners() {
|
||||
let dir = temp_dir("replace-distorted-clip");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let mut s = session();
|
||||
let png = crate::tests_links::png(4, 4, [255, 0, 0]);
|
||||
let r = s.execute("file.place", &json!({ "name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100] })).unwrap();
|
||||
let old = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap();
|
||||
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "replace": true })).unwrap();
|
||||
let group = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let id = NodeId(r["image"].as_u64().unwrap());
|
||||
let node = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(node.is_distorted_image());
|
||||
assert_eq!(node.image_corners().unwrap(), corners);
|
||||
let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") };
|
||||
let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") };
|
||||
let anchors: Vec<_> = path.anchors().map(|(_, _, a)| a.p).collect();
|
||||
// The left half of the 2 × 2 pixels, where the corners put it.
|
||||
let map = node.image_map().unwrap();
|
||||
let want = [(0.0, 0.0), (1.0, 0.0), (1.0, 2.0), (0.0, 2.0)].map(|(x, y)| map.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
|
||||
assert!(anchors.len() == want.len() && want.iter().all(|w| anchors.iter().any(|a| a.distance(*w) < 1e-6)), "{anchors:?} vs {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_link_clips_an_image_whose_file_gained_a_clipping_path() {
|
||||
let dir = temp_dir("update-gained-clip");
|
||||
|
||||
@@ -812,6 +812,47 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() {
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Place with Replace of a distorted image by an image file keeps its corners, in one undo step:
|
||||
/// the new file's pixels fill them, the new image is linked to that file, and its transform is the
|
||||
/// old image's scaled to the new pixel size. Undo brings the old image back between the same
|
||||
/// corners.
|
||||
#[test]
|
||||
fn place_with_replace_keeps_a_distorted_images_corners() {
|
||||
let dir = Folder::new("distorted-place-replace");
|
||||
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
|
||||
write(&photo, &png(20, 10, RED));
|
||||
write(&other, &png(60, 20, BLUE));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// Around the artboard's center, where `centre_colour` looks.
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).cloned();
|
||||
let before = node(&s, id).unwrap().image_corners().unwrap();
|
||||
let old_xf = image(&s, id).xf;
|
||||
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let undo = undo_len(&s);
|
||||
|
||||
let r = s.execute("file.place", &json!({"path": other, "replace": true})).unwrap();
|
||||
let new = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert!(node(&s, id).is_none(), "the old image is replaced");
|
||||
let n = node(&s, new).unwrap();
|
||||
assert!(n.is_distorted_image());
|
||||
assert_eq!(n.image_corners().unwrap(), before);
|
||||
let im = image(&s, new);
|
||||
assert_eq!((im.width, im.height), (60, 20));
|
||||
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str()));
|
||||
let want = old_xf * vectorcraft_geom::Affine::scale_non_uniform(20.0 / 60.0, 10.0 / 20.0);
|
||||
assert!(im.xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{:?} against {want:?}", im.xf);
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, new).is_none());
|
||||
assert_eq!(node(&s, id).unwrap().image_corners().unwrap(), before);
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Unembed into a folder keeps a distorted image's corners, in one undo step.
|
||||
#[test]
|
||||
fn unembed_to_a_folder_keeps_a_distorted_images_corners() {
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
//! `app.doScript`: a script plays an action of `script.run`'s `actions`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions}))
|
||||
}
|
||||
|
||||
fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec<Value> {
|
||||
let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The error message a `try` around `call` logs, or `"ok"`.
|
||||
fn caught(s: &mut Session, call: &str, actions: &Value) -> String {
|
||||
let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}");
|
||||
log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
fn doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn objects(s: &Session) -> usize {
|
||||
s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum()
|
||||
}
|
||||
|
||||
fn undo_labels(s: &Session) -> Vec<String> {
|
||||
s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect()
|
||||
}
|
||||
|
||||
fn rect(x: i64) -> Value {
|
||||
json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}})
|
||||
}
|
||||
|
||||
/// One set, `Set`, with the actions given as (name, steps).
|
||||
fn set(actions: &[(&str, Vec<Value>)]) -> Value {
|
||||
Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_script_plays_every_step_as_one_undo_step_with_the_script() {
|
||||
let mut s = doc();
|
||||
let before = undo_labels(&s);
|
||||
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
|
||||
let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions);
|
||||
assert_eq!(out, vec![Value::Null], "doScript returns undefined");
|
||||
assert_eq!(objects(&s), 3);
|
||||
let after = undo_labels(&s);
|
||||
assert_eq!(after.len(), before.len() + 1, "{after:?}");
|
||||
assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL));
|
||||
// The steps of a recorded `command.batch` run one by one, each counted as a host call.
|
||||
let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]);
|
||||
let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap();
|
||||
assert_eq!(objects(&s), 6);
|
||||
let r0 = run_with(&mut s, "1;", &batch).unwrap();
|
||||
assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_throw_puts_back_what_the_action_did() {
|
||||
let mut s = doc();
|
||||
let before = (objects(&s), undo_labels(&s));
|
||||
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
|
||||
let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string();
|
||||
assert!(e.contains("late"), "{e}");
|
||||
assert_eq!((objects(&s), undo_labels(&s)), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_step_is_put_back_and_the_steps_before_it_stay() {
|
||||
let mut s = doc();
|
||||
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
|
||||
let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]);
|
||||
let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions);
|
||||
assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}");
|
||||
assert_eq!(objects(&s), 1, "the first step stays done and the third never runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_matched_exactly_and_must_be_one_action() {
|
||||
let mut s = doc();
|
||||
let actions = json!([
|
||||
{"set": "Set", "name": "One", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Empty", "steps": []},
|
||||
]);
|
||||
assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps");
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”");
|
||||
assert_eq!(objects(&s), 0);
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok");
|
||||
assert_eq!(objects(&s), 1);
|
||||
assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet");
|
||||
assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arguments_throw_and_change_nothing() {
|
||||
let mut s = doc();
|
||||
let actions = set(&[("One", vec![rect(0)])]);
|
||||
for (call, want) in [
|
||||
("app.doScript()", "TypeError"),
|
||||
("app.doScript(1, 'Set')", "TypeError"),
|
||||
("app.doScript('One', {})", "TypeError"),
|
||||
("app.doScript('One', 'Set', 'yes')", "TypeError"),
|
||||
("app.doScript('One', 'Set', 1)", "TypeError"),
|
||||
("app.doScript('One', 'Set', false, 4)", "TypeError"),
|
||||
("app.doScript('', 'Set')", "Error"),
|
||||
("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"),
|
||||
] {
|
||||
let m = caught(&mut s, call, &actions);
|
||||
assert!(m.starts_with(&format!("{want}:")), "{call}: {m}");
|
||||
}
|
||||
assert_eq!(objects(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_a_script_may_not_run_stop_the_action_before_any_step() {
|
||||
let mut s = doc();
|
||||
s.prefs.show_external_script_warning = true;
|
||||
let steps = [
|
||||
(json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"),
|
||||
(json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"),
|
||||
(json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"),
|
||||
(json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"),
|
||||
(json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"),
|
||||
(json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"),
|
||||
];
|
||||
for (bad, want) in steps {
|
||||
let actions = set(&[("Loop", vec![rect(0), bad.clone()])]);
|
||||
let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions);
|
||||
assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}");
|
||||
assert_eq!(objects(&s), 0, "{bad}: no step ran");
|
||||
}
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
// A refused command inside a recorded batch is refused too.
|
||||
let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]);
|
||||
let m = caught(&mut s, "app.doScript('B', 'Set')", &batch);
|
||||
assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}");
|
||||
assert_eq!(objects(&s), 0);
|
||||
// So is one among the commands a Batch step plays on each file, before the steps ahead of it run.
|
||||
let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}});
|
||||
let batch = set(&[("F", vec![rect(0), files])]);
|
||||
let m = caught(&mut s, "app.doScript('F', 'Set')", &batch);
|
||||
assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}");
|
||||
assert_eq!(objects(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_action_step_keeps_the_scripts_file_gate() {
|
||||
let mut s = doc();
|
||||
let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}});
|
||||
let actions = set(&[("Export", vec![export])]);
|
||||
let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions);
|
||||
assert!(m.contains("Script file access denied"), "{m}");
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_action_is_held_to_the_host_call_limit() {
|
||||
let mut s = doc();
|
||||
// Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the
|
||||
// steps of one call cannot pass the limit.
|
||||
let calls = |s: &mut Session, steps: usize| {
|
||||
let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]);
|
||||
run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap()
|
||||
};
|
||||
let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001));
|
||||
assert!(many >= one + 2000, "{one} {many}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_action_lists_are_refused_before_the_script_runs() {
|
||||
let mut s = doc();
|
||||
let step = || json!({"command": "select.none"});
|
||||
let cases = [
|
||||
(json!({}), "`actions` must be a list"),
|
||||
(json!([1]), "`actions[0]` must be an object"),
|
||||
(json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"),
|
||||
(json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"),
|
||||
(
|
||||
json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]),
|
||||
"a command.batch inside a command.batch",
|
||||
),
|
||||
(json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"),
|
||||
(Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"),
|
||||
(json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"),
|
||||
];
|
||||
for (actions, want) in cases {
|
||||
let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{want}: {e}");
|
||||
}
|
||||
let many: Vec<Value> = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect();
|
||||
let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string();
|
||||
assert!(e.contains("more than 100000 steps in all"), "{e}");
|
||||
assert_eq!(objects(&s), 0, "no run started");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() {
|
||||
let mut s = doc();
|
||||
let first = set(&[("One", vec![rect(0)])]);
|
||||
log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first);
|
||||
assert_eq!(objects(&s), 0);
|
||||
// The next run has no actions: the function kept from the first run finds none.
|
||||
let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }";
|
||||
assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]);
|
||||
let two = set(&[("One", vec![rect(0), rect(30)])]);
|
||||
assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]);
|
||||
assert_eq!(objects(&s), 2);
|
||||
}
|
||||
|
||||
/// Makes artboard `index` of the active document the view's active one, as the app does before each
|
||||
/// command.
|
||||
fn make_active(s: &mut Session, index: usize) {
|
||||
let id = s.active().unwrap().doc.artboards[index].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(id);
|
||||
}
|
||||
|
||||
/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected
|
||||
/// Art, acts on the active artboard's index as the run started; after the script deletes that
|
||||
/// artboard, the last one. A step that names its artboard keeps it.
|
||||
#[test]
|
||||
fn steps_act_on_the_artboard_active_as_they_run() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let was = boards(&s);
|
||||
make_active(&mut s, 2);
|
||||
let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}});
|
||||
let mut first = align(json!(0));
|
||||
first["params"].as_object_mut().unwrap().remove("artboard");
|
||||
let actions = set(&[
|
||||
("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]),
|
||||
("Align 1", vec![align(json!(0))]),
|
||||
("Fit", vec![json!({"command": "artboard.fitToSelection"})]),
|
||||
]);
|
||||
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions);
|
||||
let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
|
||||
assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was");
|
||||
assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other");
|
||||
log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it");
|
||||
}
|
||||
|
||||
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
|
||||
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
|
||||
#[test]
|
||||
fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
make_active(&mut s, 1);
|
||||
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
|
||||
let mut own = align.clone();
|
||||
own["params"]["artboard"] = json!(1);
|
||||
let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}});
|
||||
let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]);
|
||||
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
log_with(&mut s, "app.doScript('First', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[0].x0, "the batch's artboard 0");
|
||||
log_with(&mut s, "app.doScript('Past', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one");
|
||||
log_with(&mut s, "app.doScript('Own', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it");
|
||||
}
|
||||
|
||||
/// The active artboard a step gets is the index it had as the run started: after a step deletes an
|
||||
/// artboard before it, the artboard now at that index, as the view shows it.
|
||||
#[test]
|
||||
fn steps_keep_the_active_artboards_index() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
|
||||
let uid = s.active().unwrap().uid;
|
||||
let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None };
|
||||
let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({}));
|
||||
assert_eq!(add(&s), json!({"artboard": 1}));
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1");
|
||||
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
|
||||
assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one");
|
||||
}
|
||||
|
||||
/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its
|
||||
/// `indices` fits those.
|
||||
#[test]
|
||||
fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let mut art = Vec::new();
|
||||
for b in &was {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
|
||||
}
|
||||
make_active(&mut s, 1);
|
||||
let actions = set(&[
|
||||
("Fit", vec![json!({"command": "artboard.fitToArt"})]),
|
||||
("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]),
|
||||
]);
|
||||
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
|
||||
assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art");
|
||||
log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions);
|
||||
assert_eq!(boards(&s), art, "the step's own indices");
|
||||
}
|
||||
|
||||
/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it
|
||||
/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps
|
||||
/// still get the active one.
|
||||
#[test]
|
||||
fn paste_and_fit_steps_keep_the_artboard_tools_selection() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
|
||||
make_active(&mut s, 1);
|
||||
let start = script::actions::Start { active: &[], picks: None, batch: None };
|
||||
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
|
||||
assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1}));
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
|
||||
assert_eq!(add(&s, id), json!({}), "{id}");
|
||||
}
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]}));
|
||||
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
|
||||
assert_eq!(add(&s, "object.align"), json!({"artboard": 1}));
|
||||
assert_eq!(add(&s, "shape.rectangle"), json!({}));
|
||||
}
|
||||
|
||||
/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays,
|
||||
/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to
|
||||
/// Artwork Bounds step fits them.
|
||||
#[test]
|
||||
fn a_run_keeps_the_artboard_tools_selection_for_its_steps() {
|
||||
// Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2.
|
||||
let setup = || {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let mut art = Vec::new();
|
||||
for b in &was {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
|
||||
}
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
make_active(&mut s, 1);
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
(s, was, art)
|
||||
};
|
||||
let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]);
|
||||
let (mut s, ..) = setup();
|
||||
let before = objects(&s);
|
||||
log_with(&mut s, "app.doScript('Paste', 'Set');", &actions);
|
||||
assert_eq!(objects(&s), before + 2, "one copy on each selected artboard");
|
||||
let (mut s, was, art) = setup();
|
||||
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
|
||||
let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art");
|
||||
// A kept artboard past the last one is left out; with fewer than two left, the active one applies.
|
||||
let (mut s, ..) = setup();
|
||||
s.reset_tool();
|
||||
let uid = s.active().unwrap().uid;
|
||||
let kept = (uid, vec![0, 2]);
|
||||
let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None };
|
||||
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
|
||||
assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]}));
|
||||
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
|
||||
s.execute("artboard.delete", &json!({"index": 2})).unwrap();
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
|
||||
}
|
||||
@@ -1767,6 +1767,23 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() {
|
||||
assert_eq!(out, vec![json!(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_frames_remove_all_refuses_type_on_a_locked_artboard() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||||
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", t.0)), "{e}");
|
||||
assert!(s.active().unwrap().doc.node(t).is_some());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_and_duplicate_refuse_art_on_a_locked_artboard() {
|
||||
let (mut s, a, b) = doc();
|
||||
|
||||
@@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
|
||||
fuel: script::DEFAULT_FUEL,
|
||||
locale: "en_US".into(),
|
||||
answers: Vec::new(),
|
||||
actions: Vec::new(),
|
||||
};
|
||||
s.script_start(request).unwrap();
|
||||
assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1]));
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
//! Character and paragraph styles in the script object model.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{TextObject, TextStyleDef};
|
||||
|
||||
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA};
|
||||
use crate::script::TEST_RESULT_BYTES;
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// A 400 × 300 pt document with point type holding `text`.
|
||||
fn doc_with(text: &str) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
(s, NodeId(id))
|
||||
}
|
||||
|
||||
fn text_of(s: &Session, id: NodeId) -> TextObject {
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Each run's text, style name, size and underline.
|
||||
fn runs(s: &Session, id: NodeId) -> Vec<(String, Option<String>, f64, bool)> {
|
||||
text_of(s, id).runs.iter().map(|r| (r.text.clone(), r.style.style_name.clone(), r.style.size, r.style.underline)).collect()
|
||||
}
|
||||
|
||||
fn char_names(s: &Session) -> Vec<String> {
|
||||
s.active().unwrap().doc.char_styles.iter().map(|d| d.name.clone()).collect()
|
||||
}
|
||||
|
||||
const DOC: &str = "var d = app.activeDocument, cs = d.characterStyles, ps = d.paragraphStyles, tf = d.textFrames[0];";
|
||||
|
||||
#[test]
|
||||
fn style_collections_list_the_normal_style_first_and_add_find_and_remove() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} vc.log([cs.length, ps.length, cs[0].name, ps[0].name, cs.typename, cs[0].typename, ps[0].typename]);\
|
||||
var b = cs.add('Body'); var p = ps.add('Lead');\
|
||||
vc.log([cs.length, cs[1].name, cs.getByName('Body').name, cs.index(1).name, cs.index('Body').name, b.parent.typename]);\
|
||||
vc.log([ps.length, ps.getByName('Lead').name, cs[5] === undefined]);\
|
||||
cs.add('Other'); cs.removeAll(); ps.removeAll();\
|
||||
vc.log([cs.length, ps.length, cs[0].name]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!([1, 1, NORMAL_CHAR, NORMAL_PARA, "CharacterStyles", "CharacterStyle", "ParagraphStyle"]));
|
||||
assert_eq!(out[1], json!([2, "Body", "Body", "Body", "Body", "Document"]));
|
||||
assert_eq!(out[2], json!([2, "Lead", true]));
|
||||
assert_eq!(out[3], json!([1, 1, NORMAL_CHAR]));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
let undo = undo_steps(&s);
|
||||
for (src, says) in [
|
||||
("cs.getByName('Nope');", "Not found"),
|
||||
("cs.index(4);", "Not found"),
|
||||
("cs.add('Body'); cs.add('Body');", "already exists"),
|
||||
("cs[0].remove();", "cannot be removed"),
|
||||
("ps[0].name = 'Mine';", "cannot be renamed"),
|
||||
("cs.getByName(5);", "string"),
|
||||
] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
|
||||
}
|
||||
assert_eq!((undo_steps(&s), char_names(&s)), (undo, Vec::<String>::new()));
|
||||
}
|
||||
|
||||
/// Names are trimmed; an empty name, one past 256 characters and one with a control character
|
||||
/// are refused with nothing changed.
|
||||
#[test]
|
||||
fn style_names_are_trimmed_and_checked() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let out = log(&mut s, &format!("{DOC} vc.log(cs.add(' Lead ').name); vc.log(cs.add('{}').name.length);", "x".repeat(256)));
|
||||
assert_eq!(out, [json!("Lead"), json!(256)]);
|
||||
let undo = undo_steps(&s);
|
||||
let long = "x".repeat(257);
|
||||
for (src, says) in [
|
||||
("cs.add(' ');".to_string(), "empty"),
|
||||
(format!("cs.add('{long}');"), "256 characters"),
|
||||
("cs.add('a\\u0007b');".to_string(), "control characters"),
|
||||
("ps.add('tab\\there');".to_string(), "control characters"),
|
||||
("cs.getByName('Lead').name = 'x\\ny';".to_string(), "control characters"),
|
||||
("cs.add(5);".to_string(), "string"),
|
||||
(format!("cs.getByName('{}');", "y".repeat(5000)), "too long"),
|
||||
] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
assert_eq!(char_names(&s).len(), 2);
|
||||
// Path characters are kept as part of the name; a style name never names a file.
|
||||
let out = log(&mut s, &format!("{DOC} vc.log(cs.add('../a/b\\\\c:*?').name);"));
|
||||
assert_eq!(out, [json!("../a/b\\c:*?")]);
|
||||
assert_eq!(char_names(&s).last().map(String::as_str), Some("../a/b\\c:*?"));
|
||||
}
|
||||
|
||||
/// A style attribute that is not a finite number in range is refused with nothing changed.
|
||||
#[test]
|
||||
fn style_attributes_refuse_values_that_are_not_finite_or_in_range() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
log(&mut s, &format!("{DOC} cs.add('X'); ps.add('P');"));
|
||||
let undo = undo_steps(&s);
|
||||
for (src, says) in [
|
||||
("cs[1].characterAttributes.size = NaN;", "finite number"),
|
||||
("cs[1].characterAttributes.size = Infinity;", "finite number"),
|
||||
("cs[1].characterAttributes.size = 1e9;", "0.1 to 1296"),
|
||||
("cs[1].characterAttributes.leading = 1e300;", "0.1 to 5000"),
|
||||
("cs[1].characterAttributes.tracking = -1e9;", "tracking"),
|
||||
("ps[1].paragraphAttributes.leftIndent = NaN;", "finite"),
|
||||
("ps[1].paragraphAttributes.spaceBefore = 1e12;", "1296"),
|
||||
] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
let attrs = |s: &Session| {
|
||||
s.active().unwrap().doc.char_styles.iter().chain(s.active().unwrap().doc.para_styles.iter()).map(|d| d.attrs.len()).sum::<usize>()
|
||||
};
|
||||
assert_eq!(attrs(&s), 0);
|
||||
}
|
||||
|
||||
/// A style object follows its style through a rename made with it; after the style is removed,
|
||||
/// with the object or with a command, every member throws, and a new style of that name does not
|
||||
/// bring it back.
|
||||
#[test]
|
||||
fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() {
|
||||
let (mut s, id) = doc_with("Hello");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.add('A'); a.applyTo(tf.textRange); a.name = ' B '; vc.log([a.name, cs[1].name, a === cs.getByName('B')]);\
|
||||
a.name = 'B'; vc.log(cs.length);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!(["B", "B", true]), json!(2)]);
|
||||
assert_eq!(runs(&s, id)[0].1.as_deref(), Some("B"));
|
||||
for remove in ["a.remove();", "vc.run('charStyle.delete', {name: 'B'});", "cs.removeAll();"] {
|
||||
let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); {remove} cs.add('B'); a.name;"));
|
||||
assert!(e.contains("Stale style"), "{remove}: {e}");
|
||||
}
|
||||
// A style removed and made again by commands is another style.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B'); vc.run('charStyle.delete', {{name: 'B'}}); vc.run('charStyle.new', {{name: 'B', attrs: {{}}}}); a.name;"
|
||||
),
|
||||
);
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
// So is a style removed and made again by the steps of one batch.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.delete', params: {{name: 'B'}}}}, \
|
||||
{{command: 'charStyle.new', params: {{name: 'B', attrs: {{}}}}}}]}}); a.name;"
|
||||
),
|
||||
);
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
// And a style a batch renames and then names back.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.rename', params: {{name: 'B', to: 'C'}}}}, \
|
||||
{{command: 'charStyle.rename', params: {{name: 'C', to: 'B'}}}}]}}); a.name;"
|
||||
),
|
||||
);
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
// The attributes object of a removed style throws for its typename too.
|
||||
let e =
|
||||
failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;"));
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
// A style renamed by a command is stale too, and its text keeps its look after a removal.
|
||||
let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;"));
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
let e =
|
||||
failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.characterAttributes.size;"));
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
let size = runs(&s, id)[0].2;
|
||||
log(&mut s, &format!("{DOC} var a = cs.getByName('B'); a.characterAttributes.size = 40; a.remove();"));
|
||||
assert_eq!(runs(&s, id)[0].1, None);
|
||||
assert_ne!(runs(&s, id)[0].2, size);
|
||||
assert_eq!(runs(&s, id)[0].2, 40.0);
|
||||
}
|
||||
|
||||
/// The steps of one batch a script runs keep one copy of a document's style lists, however many of
|
||||
/// them change the lists.
|
||||
#[test]
|
||||
fn the_steps_of_a_batch_keep_one_copy_of_the_style_lists() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let commands: Vec<Value> = (0..20).map(|i| json!({"command": "charStyle.new", "params": {"name": format!("S{i}"), "attrs": {}}})).collect();
|
||||
s.script_in_run = true;
|
||||
let r = s.execute("command.batch", &json!({"commands": commands}));
|
||||
s.script_in_run = false;
|
||||
r.unwrap();
|
||||
assert_eq!(char_names(&s).len(), 20);
|
||||
assert_eq!(crate::script::retained_style_lists(&s), 1);
|
||||
}
|
||||
|
||||
/// A removal or rename whose result cannot cross to the script is put back, and the style's object
|
||||
/// still names the style after it.
|
||||
#[test]
|
||||
fn a_style_change_that_is_put_back_keeps_the_style_object() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
s.execute("charStyle.new", &json!({"name": "B", "attrs": {}})).unwrap();
|
||||
TEST_RESULT_BYTES.with(|b| b.set(Some(1)));
|
||||
let r = run(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B');\
|
||||
try {{ a.remove(); }} catch (e) {{ vc.log(e.name); }}\
|
||||
try {{ vc.run('charStyle.delete', {{name: 'B'}}); }} catch (e) {{ vc.log(e.name); }}\
|
||||
try {{ a.name = 'C'; }} catch (e) {{ vc.log(e.name); }}\
|
||||
vc.log([a.name, a === cs.getByName('B'), cs.length]);"
|
||||
),
|
||||
);
|
||||
TEST_RESULT_BYTES.with(|b| b.set(None));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", ["B", true, 2]]), "{r}");
|
||||
assert!(char_names(&s).contains(&"B".to_string()), "{:?}", char_names(&s));
|
||||
}
|
||||
|
||||
/// A character style styles exactly the range; without clearing overrides the range keeps its
|
||||
/// own underline, and with them it goes back to the Normal style first.
|
||||
#[test]
|
||||
fn apply_to_styles_a_range_and_clearing_overrides_resets_it() {
|
||||
let (mut s, id) = doc_with("Hello world");
|
||||
let before = undo_steps(&s);
|
||||
log(
|
||||
&mut s,
|
||||
&format!("{DOC} var w = tf.words[0]; w.underline = true; var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo(w);"),
|
||||
);
|
||||
assert_eq!(runs(&s, id), [("Hello".into(), Some("Big".into()), 30.0, true), (" world".into(), None, 12.0, false)]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf.words[0], true);"));
|
||||
assert_eq!(runs(&s, id)[0], ("Hello".into(), Some("Big".into()), 30.0, false));
|
||||
// A whole frame, and an empty range, which changes nothing.
|
||||
log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf); cs[0].applyTo(tf.characters[0]);"));
|
||||
assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]);
|
||||
}
|
||||
|
||||
/// A character style applied to an empty frame styles the text set in it later.
|
||||
#[test]
|
||||
fn a_character_style_applied_to_an_empty_frame_styles_text_set_later() {
|
||||
for target in ["tf", "tf.textRange"] {
|
||||
let (mut s, id) = doc_with("");
|
||||
log(&mut s, &format!("{DOC} var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo({target}); tf.contents = 'Hi';"));
|
||||
assert_eq!(runs(&s, id), [("Hi".into(), Some("Big".into()), 30.0, false)], "{target}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph style styles every paragraph the text touches, and only those.
|
||||
#[test]
|
||||
fn a_paragraph_style_styles_the_paragraphs_the_text_touches() {
|
||||
let (mut s, id) = doc_with("one\ntwo\nthree");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var c = ps.add('Centered'); var a = c.paragraphAttributes;\
|
||||
vc.log([a.justification === undefined, a.spaceBefore === undefined, a.typename]);\
|
||||
a.justification = Justification.CENTER; a.spaceBefore = 6;\
|
||||
vc.log([a.justification, a.spaceBefore]); c.applyTo(tf.paragraphs[1]);\
|
||||
vc.log(tf.paragraphs[1].paragraphAttributes.justification);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!([true, true, "ParagraphAttributes"]), json!(["Justification.CENTER", 6]), json!("Justification.CENTER")]);
|
||||
let t = text_of(&s, id);
|
||||
let names: Vec<_> = (0..3).map(|i| t.para_at(i).style_name.clone()).collect();
|
||||
assert_eq!(names, [None, Some("Centered".to_string()), None]);
|
||||
assert_eq!(t.para_at(1).space_before, 6.0);
|
||||
assert_eq!(t.para_at(2).space_before, 0.0);
|
||||
let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.justification = 'middle';"));
|
||||
assert!(e.contains("Justification"), "{e}");
|
||||
let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.spaceAfter = 5000;"));
|
||||
assert!(e.contains("1296"), "{e}");
|
||||
}
|
||||
|
||||
/// A style's character attributes read `undefined` until set; setting one restyles the text in
|
||||
/// the style but not a value the text changed itself.
|
||||
#[test]
|
||||
fn style_attributes_redefine_the_text_in_the_style() {
|
||||
let (mut s, id) = doc_with("ab cd");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var x = cs.add('X'), a = x.characterAttributes;\
|
||||
vc.log([a.size === undefined, a.autoLeading === undefined, a.textFont === undefined, a.typename]);\
|
||||
a.size = 20; x.applyTo(tf.textRange); tf.words[1].size = 9; a.size = 24; a.autoLeading = true; a.underline = true;\
|
||||
vc.log([a.size, a.autoLeading, a.underline]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]);
|
||||
assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]);
|
||||
// Turning auto leading off keeps the leading auto leading gave the style's size.
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);"),
|
||||
);
|
||||
assert_eq!(out, [json!([false, 288])]);
|
||||
let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;"));
|
||||
assert!(e.contains("0.1 to 1296"), "{e}");
|
||||
let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.textFont = 'Arial';"));
|
||||
assert!(e.contains("TextFont"), "{e}");
|
||||
let e = failure(&mut s, &format!("{DOC} ps.add('P').characterAttributes;"));
|
||||
assert!(e.contains("not available yet"), "{e}");
|
||||
}
|
||||
|
||||
/// A range lists each style its text uses once, in order, with the Normal style for unstyled
|
||||
/// text, and its lists cannot add or remove styles.
|
||||
#[test]
|
||||
fn a_range_lists_the_styles_its_text_uses() {
|
||||
let (mut s, _) = doc_with("aa bb cc\ndd");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var x = cs.add('X'), y = cs.add('Y'); y.applyTo(tf.words[2]); x.applyTo(tf.words[1]); x.applyTo(tf.words[3]);\
|
||||
ps.add('P').applyTo(tf.paragraphs[1]);\
|
||||
function names(l) {{ var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; }}\
|
||||
vc.log(names(tf.textRange.characterStyles)); vc.log(names(tf.words[1].characterStyles));\
|
||||
vc.log(names(tf.textRange.paragraphStyles)); vc.log(names(tf.paragraphs[0].paragraphStyles));\
|
||||
vc.log([tf.words[1].characterStyles[0] === x, tf.words[1].characterStyles.getByName('X').name,\
|
||||
tf.textRange.characterStyles.parent.typename]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!([NORMAL_CHAR, "X", "Y"]));
|
||||
assert_eq!(out[1], json!(["X"]));
|
||||
assert_eq!(out[2], json!([NORMAL_PARA, "P"]));
|
||||
assert_eq!(out[3], json!([NORMAL_PARA]));
|
||||
assert_eq!(out[4], json!([true, "X", "TextRange"]));
|
||||
for src in ["tf.textRange.characterStyles.add('Z');", "tf.textRange.paragraphStyles.removeAll();"] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains("cannot be added or removed"), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `applyTo` refuses what is not text, a `clearingOverrides` that is not a boolean, text of another
|
||||
/// document, and a range whose text changed, with nothing changed.
|
||||
#[test]
|
||||
fn apply_to_refuses_bad_arguments_with_nothing_changed() {
|
||||
let (mut s, id) = doc_with("Hello");
|
||||
log(&mut s, &format!("{DOC} cs.add('X');"));
|
||||
let runs_before = runs(&s, id);
|
||||
for (src, says) in [
|
||||
("cs[1].applyTo(5);".to_string(), "TextRange"),
|
||||
("cs[1].applyTo(tf.textRange, 'yes');".to_string(), "clearingOverrides"),
|
||||
("cs[1].applyTo(cs);".to_string(), "TextRange"),
|
||||
(format!("var r = tf.textRange; vc.run('text.setText', {{id: {}, text: 'Help'}}); cs[1].applyTo(r);", id.0), "Stale text range"),
|
||||
(
|
||||
"var o = app.documents.add(); var t = o.textFrames.add(); t.contents = 'Other'; cs[1].applyTo(t.textRange);".to_string(),
|
||||
"another document",
|
||||
),
|
||||
] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
|
||||
}
|
||||
assert_eq!(runs(&s, id), runs_before);
|
||||
}
|
||||
|
||||
/// A run names at most 4,096 styles; reading past that throws instead of growing without bound.
|
||||
#[test]
|
||||
fn style_objects_made_before_file_revert_go_stale_even_when_the_style_is_back() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
s.execute("charStyle.new", &json!({"name": "B", "attrs": {"size": 30}})).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("vc-styles-revert-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B');\
|
||||
vc.run('shape.rectangle', {{x: 1, y: 1, width: 5, height: 5}}); vc.run('file.revert', {{}});\
|
||||
var cs2 = app.activeDocument.characterStyles;\
|
||||
try {{ vc.log(a.name); }} catch (e) {{ vc.log(e.message); }}\
|
||||
vc.log(cs2.getByName('B').name); vc.log(cs2.getByName('B') === a);"
|
||||
),
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(out[0].as_str().is_some_and(|m| m.contains("Stale style")), "{out:?}");
|
||||
assert_eq!(out[1], json!("B"), "a style object made after the revert names the reverted style");
|
||||
assert_eq!(out[2], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_names_at_most_4096_styles() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let mut d = (*s.active().unwrap().doc).clone();
|
||||
let defs: Vec<TextStyleDef> = (0..4100).map(|i| TextStyleDef { name: format!("S{i}"), attrs: Default::default() }).collect();
|
||||
d.char_styles = defs.into();
|
||||
s.doc_mut().unwrap().doc = std::sync::Arc::new(d);
|
||||
let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; vc.log(cs[0] === undefined); vc.log(cs.length);"));
|
||||
assert_eq!(out, [json!(false), json!(4101)]);
|
||||
let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;"));
|
||||
assert!(e.contains("4096 styles"), "{e}");
|
||||
// `add` with every slot taken adds no style; with one slot left it adds the style.
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; try {{ cs.add('New'); }} catch (e) {{ vc.log(e.message); }} vc.log(cs.length);"),
|
||||
);
|
||||
assert_eq!(out, [json!("a script can name at most 4096 styles in one run"), json!(4101)]);
|
||||
let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4095; i++) cs[i]; vc.log(cs.add('New').name); vc.log(cs.length);"));
|
||||
assert_eq!(out, [json!("New"), json!(4102)]);
|
||||
}
|
||||
|
||||
/// A script loads styles from a file only where it may read files; a file outside that is refused.
|
||||
#[test]
|
||||
fn a_script_loads_styles_only_from_a_file_it_may_read() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-styles-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Other.vectorcraft");
|
||||
let mut other = Session::new();
|
||||
other.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
other.execute("charStyle.new", &json!({"name": "Loaded", "attrs": {"size": 30}})).unwrap();
|
||||
std::fs::write(&path, vectorcraft_format::save(&other.active().unwrap().doc, false)).unwrap();
|
||||
let p = path.to_string_lossy().replace('\\', "/");
|
||||
let e = failure(&mut s, &format!("vc.run('charStyle.load', {{path: '{p}'}});"));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(e.contains("access denied"), "{e}");
|
||||
assert!(char_names(&s).is_empty());
|
||||
}
|
||||
@@ -1044,9 +1044,10 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
|
||||
("object.cropImage", json!({})),
|
||||
("imageTrace.make", json!({})),
|
||||
("object.mesh.create", json!({})),
|
||||
// Vector art has no pixels to put between the corners.
|
||||
(
|
||||
"file.place",
|
||||
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
|
||||
json!({"replace": true, "name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(b"<svg xmlns='http://www.w3.org/2000/svg' width='9' height='9'><rect width='9' height='9'/></svg>")}),
|
||||
),
|
||||
] {
|
||||
let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
|
||||
@@ -630,6 +630,7 @@ impl Session {
|
||||
freeform_point: self.selected_freeform_point(),
|
||||
raster_sample: self.prefs.eyedropper.sample_size,
|
||||
preview_bounds: self.prefs.use_preview_bounds,
|
||||
scale_strokes: self.prefs.scale_strokes,
|
||||
glyph_bounds: self.prefs.type_glyph_bounds,
|
||||
preview_memo: Some(&self.preview_memo),
|
||||
unit,
|
||||
|
||||
@@ -944,8 +944,7 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() {
|
||||
/// behind the selection, given back, answers the same ratio.
|
||||
#[test]
|
||||
fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() {
|
||||
let _g = settings();
|
||||
let before = cms::active_settings();
|
||||
let _g = restored_settings();
|
||||
let mut s = session();
|
||||
exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB}));
|
||||
let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"}));
|
||||
@@ -957,7 +956,6 @@ fn contrast_writes_the_background_as_against_takes_it_with_another_working_space
|
||||
exec(&mut s, "paint.setFill", json!({"color": "#808080"}));
|
||||
let below = s.execute("color.contrast", &json!({}));
|
||||
let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok());
|
||||
cms::set_active(&before).unwrap();
|
||||
let given = given.unwrap();
|
||||
assert_eq!(given["against"], "#806040", "{given}");
|
||||
let (below, again) = (below.unwrap(), again.unwrap());
|
||||
|
||||
@@ -89,8 +89,9 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \
|
||||
getIsFileOpen redraw selection selection= textFonts toString typename",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \
|
||||
unloadAction unloadAction=",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
@@ -105,10 +106,10 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Document.", "prototype"),
|
||||
(
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
|
||||
groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \
|
||||
rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= tags textFrames toString \
|
||||
typename views width",
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
|
||||
documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \
|
||||
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
("Views.prototype.", "constructor index length parent toString typename"),
|
||||
@@ -154,8 +155,9 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
(
|
||||
"",
|
||||
"CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \
|
||||
TextOrientation TextRange TextType Words",
|
||||
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
|
||||
ParagraphAttributes ParagraphStyle ParagraphStyleAttributes ParagraphStyles Paragraphs TextFont TextFonts TextFrame \
|
||||
TextFrames TextOrientation TextRange TextType Words",
|
||||
),
|
||||
("TextFrames.", "prototype"),
|
||||
("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"),
|
||||
@@ -173,11 +175,11 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"TextRange.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \
|
||||
characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \
|
||||
characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \
|
||||
duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \
|
||||
getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \
|
||||
horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \
|
||||
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \
|
||||
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \
|
||||
paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \
|
||||
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \
|
||||
textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \
|
||||
@@ -202,6 +204,30 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \
|
||||
rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename",
|
||||
),
|
||||
("CharacterStyles.", "prototype"),
|
||||
("CharacterStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("CharacterStyle.", "prototype"),
|
||||
("CharacterStyle.prototype.", "applyTo characterAttributes constructor name name= parent remove typename"),
|
||||
("CharacterStyleAttributes.", "prototype"),
|
||||
(
|
||||
"CharacterStyleAttributes.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
|
||||
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
|
||||
underline= verticalScale verticalScale=",
|
||||
),
|
||||
("ParagraphStyles.", "prototype"),
|
||||
("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("ParagraphStyle.", "prototype"),
|
||||
(
|
||||
"ParagraphStyle.prototype.",
|
||||
"applyTo characterAttributes characterAttributes= constructor name name= paragraphAttributes parent remove typename",
|
||||
),
|
||||
("ParagraphStyleAttributes.", "prototype"),
|
||||
(
|
||||
"ParagraphStyleAttributes.prototype.",
|
||||
"constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \
|
||||
rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename",
|
||||
),
|
||||
("TextFonts.", "prototype"),
|
||||
("TextFonts.prototype.", "constructor getByName index length parent typename"),
|
||||
("TextFont.", "prototype"),
|
||||
|
||||
@@ -614,6 +614,9 @@ pub struct Program {
|
||||
pub(crate) lines: crate::LineTable,
|
||||
/// It was read with [`crate::Options::es2015`].
|
||||
pub(crate) es2015: bool,
|
||||
/// What `super` and `new.target` may do at its top: nothing in a script, and in eval code
|
||||
/// what they may do in the code that calls a direct `eval` (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) supers: crate::parser::SuperRules,
|
||||
}
|
||||
|
||||
impl Program {
|
||||
|
||||
@@ -591,15 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
|
||||
fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || is_host_member_pk(interp, o, &k)?))
|
||||
}
|
||||
|
||||
/// [`Interp::is_host_member`] for either kind of key: a Symbol never names a host member.
|
||||
fn is_host_member_pk(interp: &Interp, o: ObjId, k: &crate::symbol::PropKey) -> JsResult<bool> {
|
||||
match k {
|
||||
crate::symbol::PropKey::Str(name) => interp.is_host_member(o, name),
|
||||
crate::symbol::PropKey::Sym(_) => Ok(false),
|
||||
}
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
|
||||
}
|
||||
|
||||
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -618,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
|
||||
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || is_host_member_pk(interp, o, &k)?))
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
|
||||
}
|
||||
|
||||
// ---- Function ----
|
||||
|
||||
@@ -453,6 +453,10 @@ pub(crate) struct Code {
|
||||
/// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]),
|
||||
/// and it is not a constructor.
|
||||
pub(crate) generator: bool,
|
||||
/// What `super` and `new.target` may do in eval code a direct `eval` in this code runs: the
|
||||
/// rules of the function's body, of the code around an arrow function, or those eval code was
|
||||
/// read with (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) supers: crate::parser::SuperRules,
|
||||
}
|
||||
|
||||
/// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors.
|
||||
|
||||
@@ -25,6 +25,7 @@ use crate::ast::{
|
||||
use crate::bytecode::{BlockScope, Code, CodeKind, Handler, NamePrefix, Op, Source, Template, fallthrough_effect, verify};
|
||||
use crate::error::{SyntaxError, TOO_DEEP};
|
||||
use crate::heap::Key;
|
||||
use crate::parser::SuperRules;
|
||||
use crate::value::Str;
|
||||
use pattern::Mode;
|
||||
|
||||
@@ -112,6 +113,8 @@ struct FnCompiler<'a> {
|
||||
optional: Vec<(Label, u32)>,
|
||||
/// The code is a generator function's.
|
||||
generator: bool,
|
||||
/// [`Code::supers`].
|
||||
supers: SuperRules,
|
||||
}
|
||||
|
||||
/// The `var` names and function declarations a body hoists.
|
||||
@@ -162,6 +165,7 @@ impl<'a> FnCompiler<'a> {
|
||||
annex: HashSet::new(),
|
||||
optional: Vec::new(),
|
||||
generator: false,
|
||||
supers: SuperRules::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -501,7 +505,7 @@ impl<'a> FnCompiler<'a> {
|
||||
|
||||
/// Compiles a nested function and returns its index in the function table.
|
||||
fn function(&mut self, fid: FunctionId) -> CResult<u32> {
|
||||
let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015)?;
|
||||
let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015, self.supers)?;
|
||||
// An arrow function reads the `this`, `arguments` and `new.target` of the code around it.
|
||||
if code.arrow {
|
||||
self.uses_this |= code.uses_this;
|
||||
@@ -2389,6 +2393,7 @@ impl<'a> FnCompiler<'a> {
|
||||
own_name: meta.own_name,
|
||||
method: meta.method,
|
||||
generator: self.generator,
|
||||
supers: self.supers,
|
||||
};
|
||||
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
|
||||
Ok(Rc::new(code))
|
||||
@@ -2419,12 +2424,22 @@ fn len_u32(n: usize) -> u32 {
|
||||
}
|
||||
|
||||
/// Compiles function `fid` of `ast`. With `bind_name`, a function expression's name is bound
|
||||
/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in.
|
||||
pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>, recursion: u32, bind_name: bool, es2015: bool) -> CResult<Rc<Code>> {
|
||||
/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in, and `outer` the
|
||||
/// [`Code::supers`] of the code around it, which an arrow function keeps.
|
||||
pub(crate) fn compile_function(
|
||||
ast: &Ast,
|
||||
fid: FunctionId,
|
||||
source: &Rc<Source>,
|
||||
recursion: u32,
|
||||
bind_name: bool,
|
||||
es2015: bool,
|
||||
outer: SuperRules,
|
||||
) -> CResult<Rc<Code>> {
|
||||
let Some(f) = ast.function(fid) else { return internal("function out of range") };
|
||||
let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion);
|
||||
c.es2015 = es2015;
|
||||
c.generator = f.generator;
|
||||
c.supers = if f.kind == FunctionKind::Arrow { outer } else { SuperRules::function(f.home, f.kind == FunctionKind::DerivedConstructor) };
|
||||
c.at(f.span.start);
|
||||
c.enter()?;
|
||||
// A destructured parameter has a binding of its own under a name no script can write, which
|
||||
@@ -2515,6 +2530,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kind: CodeKind) -> CResult<Rc<Code>> {
|
||||
let mut c = FnCompiler::new(&program.ast, source, kind, program.strict, 0);
|
||||
c.es2015 = program.es2015;
|
||||
c.supers = program.supers;
|
||||
let hoisted = c.hoist(&program.body, &[])?;
|
||||
let top_scope = c.list_scope(&program.body, false)?;
|
||||
c.stmts(&program.body)?;
|
||||
@@ -2531,5 +2547,5 @@ pub(crate) fn compile_constructed_function(program: &crate::Program, source: &Rc
|
||||
let Some(Stmt::Expr(e)) = program.ast.stmt(*stmt) else { return Ok(None) };
|
||||
let Some(Expr::Paren(inner)) = program.ast.expr(*e) else { return Ok(None) };
|
||||
let Some(Expr::Function(fid)) = program.ast.expr(*inner) else { return Ok(None) };
|
||||
compile_function(&program.ast, *fid, source, 0, false, program.es2015).map(Some)
|
||||
compile_function(&program.ast, *fid, source, 0, false, program.es2015, program.supers).map(Some)
|
||||
}
|
||||
@@ -1639,6 +1639,56 @@ fn eval_inside_a_function_reads_its_new_target() {
|
||||
throws("function F() { return (0, eval)('new.target'); } new F()", "SyntaxError");
|
||||
}
|
||||
|
||||
/// A direct `eval` inside a method reads `super` properties of the method's home object, from an
|
||||
/// arrow function and a nested `eval` too; in a function that is not a method, at the top of a
|
||||
/// script, through an indirect `eval` and in a `Function` body it is a `SyntaxError`.
|
||||
#[test]
|
||||
fn eval_inside_a_method_reads_super_properties() {
|
||||
truth("class A { get x() { return 'a' + this.n; } } class B extends A { m() { this.n = 1; return eval('super.x'); } } new B().m() === 'a1'");
|
||||
truth("class A { f() { return 3; } } class B extends A { m() { return (() => eval('super.f()'))(); } } new B().m() === 3");
|
||||
truth("class A { f() { return 3; } } class B extends A { m() { return eval('eval(\"super[\\'f\\']()\")'); } } new B().m() === 3");
|
||||
truth("class A { f() { return 3; } } class B extends A { m() { return eval('() => super.f()')(); } } new B().m() === 3");
|
||||
truth("class A {} class B extends A { m() { eval('super.y = 5'); return this.y; } } new B().m() === 5");
|
||||
truth("class A { static s() { return 4; } } class B extends A { static s() { return eval('super.s()'); } } B.s() === 4");
|
||||
truth("class A { constructor() { this.t = eval('super.constructor'); } } new A().t === Object");
|
||||
truth("var o = { __proto__: { x: 2 }, m() { 'use strict'; return eval('super.x'); } }; o.m() === 2");
|
||||
throws("function F() { return eval('super.x'); } F()", "SyntaxError");
|
||||
throws("eval('super.x')", "SyntaxError");
|
||||
throws("class A { m() { return (function () { return eval('super.x'); })(); } } new A().m()", "SyntaxError");
|
||||
throws("class A { m() { return (0, eval)('super.x'); } } new A().m()", "SyntaxError");
|
||||
throws("class A { m() { return Function('return super.x'); } } new A().m()", "SyntaxError");
|
||||
}
|
||||
|
||||
/// A direct `eval` inside a derived class's constructor calls the superclass's constructor with
|
||||
/// `super(…)` and binds `this` once; elsewhere `super(…)` in eval code is a `SyntaxError`.
|
||||
#[test]
|
||||
fn eval_inside_a_derived_constructor_calls_super() {
|
||||
let a = "class A { constructor(v) { this.a = v; this.t = new.target; } } ";
|
||||
truth(&format!(
|
||||
"{a}class B extends A {{ constructor() {{ eval('super(1)'); this.b = 2; }} }} var b = new B(); b.a === 1 && b.b === 2 && b.t === B && b instanceof B"
|
||||
));
|
||||
truth(&format!("{a}class B extends A {{ constructor() {{ var r = eval('super(1)'); this.r = r === this; }} }} new B().r"));
|
||||
truth(&format!("{a}class B extends A {{ constructor() {{ (() => eval('super(1)'))(); }} }} new B().a === 1"));
|
||||
truth(&format!("{a}class B extends A {{ constructor() {{ 'use strict'; eval('super(1)'); }} }} new B().a === 1"));
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ super(1); eval('super(2)'); }} }} new B()"), "ReferenceError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ eval('super(1); super(2)'); }} }} new B()"), "ReferenceError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ eval('this'); super(1); }} }} new B()"), "ReferenceError");
|
||||
throws("class A { constructor() { eval('super()'); } } new A()", "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ m() {{ eval('super()'); }} }} new B(1).m()"), "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('super(1)'); }})(); }} }} new B()"), "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ (0, eval)('super(1)'); }} }} new B()"), "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ Function('super(1)'); }} }} new B()"), "SyntaxError");
|
||||
throws("function F() { eval('super()'); } F()", "SyntaxError");
|
||||
throws("eval('super()')", "SyntaxError");
|
||||
}
|
||||
|
||||
/// A `Function` body reads its own `new.target`, wherever the `Function` constructor is called.
|
||||
#[test]
|
||||
fn a_function_body_reads_its_own_new_target() {
|
||||
truth("var G = Function('return new.target'); new G() === G && G() === undefined");
|
||||
truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_class_chains_stay_within_the_limits() {
|
||||
let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();";
|
||||
|
||||
@@ -40,6 +40,7 @@ use std::rc::Rc;
|
||||
use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key};
|
||||
use crate::host::ArgRead;
|
||||
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
|
||||
use crate::symbol::PropKey;
|
||||
use crate::value::Value;
|
||||
use crate::{Data, HostError, HostFunction};
|
||||
|
||||
@@ -245,6 +246,22 @@ impl Interp {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// [`Self::is_host_member`] for a property key. A Symbol names no host member.
|
||||
pub(crate) fn is_host_member_pk(&self, id: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.is_host_member(id, name),
|
||||
PropKey::Sym(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::has_property_indexed`] for a property key. A Symbol does not go to the indexer.
|
||||
pub(crate) fn has_pk_indexed(&mut self, id: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.has_property_indexed(id, name),
|
||||
PropKey::Sym(_) => self.has_pk(id, k),
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`Data`] for the object of a host class `id`, or `None` when it is not one.
|
||||
pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult<Option<Data>> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
|
||||
|
||||
+12
-14
@@ -29,6 +29,7 @@ use crate::heap::{
|
||||
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId,
|
||||
Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
|
||||
};
|
||||
use crate::parser::SuperRules;
|
||||
use crate::string_builtins::flat_charged;
|
||||
use crate::symbol::PropKey;
|
||||
use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32};
|
||||
@@ -3545,17 +3546,16 @@ impl Interp {
|
||||
|
||||
/// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`.
|
||||
pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result<Rc<Code>, CompileError> {
|
||||
self.compile_units(units, strict, writes, kind, false)
|
||||
self.compile_units(units, strict, writes, kind, SuperRules::default())
|
||||
}
|
||||
|
||||
/// [`Interp::compile_source_writes`]; `in_function` reads eval code run inside a function,
|
||||
/// where `new.target` is allowed.
|
||||
fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, in_function: bool) -> Result<Rc<Code>, CompileError> {
|
||||
/// [`Interp::compile_source_writes`]; `supers` says what `super` and `new.target` may do at
|
||||
/// the top of the code: what they may do where a direct `eval` is called.
|
||||
fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, supers: SuperRules) -> Result<Rc<Code>, CompileError> {
|
||||
self.source_units = self.source_units.saturating_add(units.len());
|
||||
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
|
||||
let options = Options { strict, max_source_units: remaining, ..self.options.clone() };
|
||||
let parse = if in_function { crate::parse_utf16_in_function } else { crate::parse_utf16 };
|
||||
let program = parse(units, &options).map_err(CompileError::Syntax)?;
|
||||
let program = crate::parse_utf16_with_supers(units, &options, supers).map_err(CompileError::Syntax)?;
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
|
||||
compile_program(&program, &source, kind).map_err(|e| match e {
|
||||
CompileFail::Syntax(s) => CompileError::Syntax(s),
|
||||
@@ -3582,10 +3582,12 @@ impl Interp {
|
||||
self.prepare_source(s.len())?;
|
||||
let units = self.flat_reserved(s)?;
|
||||
self.observe_code(&units);
|
||||
// Inside a function the eval code reads the function's `new.target` (section 18.2.1.1).
|
||||
let new_target = self.caller_new_target()?;
|
||||
// The eval code may use `super` and `new.target` as the code that calls it may, and reads
|
||||
// the `new.target` of the function it is in (section 18.2.1.1).
|
||||
let supers = self.frame()?.code.supers;
|
||||
let new_target = if supers.new_target { self.caller_new_target()? } else { None };
|
||||
let writes = self.writes_mode();
|
||||
let code = self.compile_units(&units, strict, writes, CodeKind::Eval, new_target.is_some()).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
let code = self.compile_units(&units, strict, writes, CodeKind::Eval, supers).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
|
||||
let frame = self.frame()?;
|
||||
let (caller_env, caller_var_env, this, this_in_env) = (frame.env, frame.var_env, frame.this.clone(), frame.this_in_env);
|
||||
@@ -4191,11 +4193,7 @@ impl Interp {
|
||||
}
|
||||
let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) };
|
||||
let k = self.to_prop_key(a)?;
|
||||
match &k {
|
||||
PropKey::Str(name) => self.has_property_indexed(*o, name),
|
||||
PropKey::Sym(_) => self.has_pk(*o, &k),
|
||||
}
|
||||
.map(Value::Bool)
|
||||
self.has_pk_indexed(*o, &k).map(Value::Bool)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1048,6 +1048,7 @@ fn code(ops: Vec<Op>) -> Code {
|
||||
own_name: None,
|
||||
method: false,
|
||||
generator: false,
|
||||
supers: crate::parser::SuperRules::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -222,11 +222,11 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxE
|
||||
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// [`parse_utf16`] for code a direct `eval` runs inside a function, where `new.target` is allowed
|
||||
/// (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) fn parse_utf16_in_function(source: &[u16], options: &Options) -> Result<Program, SyntaxError> {
|
||||
/// [`parse_utf16`] for code a direct `eval` runs, which may use `super` and `new.target` as the
|
||||
/// code that calls it may (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) fn parse_utf16_with_supers(source: &[u16], options: &Options, rules: parser::SuperRules) -> Result<Program, SyntaxError> {
|
||||
check_length(source.len(), options)?;
|
||||
parser::Parser::new(source, options, false)?.with_new_target().parse_program().map(|(program, _)| program)
|
||||
parser::Parser::new(source, options, false)?.with_supers(rules).parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and
|
||||
|
||||
+30
-10
@@ -68,14 +68,23 @@ struct Scope {
|
||||
|
||||
/// What `super` and `new.target` may do where the parser is (ECMA-262 2015 sections 12.3.5.1,
|
||||
/// 12.3.8.1, 14.1.2, 14.5.1 and 15.1.1): set for each function body and kept by arrow functions.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct SuperRules {
|
||||
/// Eval code run by a direct `eval` has the rules of the code that calls it (section 18.2.1.1).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct SuperRules {
|
||||
/// `super.property` and `super[index]`: in a class's methods, accessors and constructor.
|
||||
property: bool,
|
||||
pub(crate) property: bool,
|
||||
/// `super(arguments)`: in a derived class's constructor.
|
||||
call: bool,
|
||||
pub(crate) call: bool,
|
||||
/// `new.target`: in any function other than an arrow function at the top of a script.
|
||||
new_target: bool,
|
||||
pub(crate) new_target: bool,
|
||||
}
|
||||
|
||||
impl SuperRules {
|
||||
/// The rules in the body of a function that is not an arrow function: `home` for one with a
|
||||
/// home object, `derived` for a derived class's constructor.
|
||||
pub(crate) fn function(home: bool, derived: bool) -> Self {
|
||||
Self { property: home, call: derived, new_target: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of a function as they are read: names or patterns, each one's default value,
|
||||
@@ -176,9 +185,12 @@ impl<'s> Parser<'s> {
|
||||
Ok(parser)
|
||||
}
|
||||
|
||||
/// Allows `new.target` at the top of the source: eval code run inside a function.
|
||||
pub(crate) fn with_new_target(mut self) -> Self {
|
||||
self.supers.new_target = self.es2015;
|
||||
/// Reads the top of the source with `rules`: eval code run by a direct `eval` inside a
|
||||
/// function. Without [`crate::Options::es2015`] the rules stay the default.
|
||||
pub(crate) fn with_supers(mut self, rules: SuperRules) -> Self {
|
||||
if self.es2015 {
|
||||
self.supers = rules;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -190,7 +202,15 @@ impl<'s> Parser<'s> {
|
||||
if let Some(tokens) = &mut self.tokens {
|
||||
tokens.push(self.tok.clone());
|
||||
}
|
||||
let program = Program { ast: self.ast, body, strict: self.ctx.strict, directives: self.directives, lines: self.lines, es2015: self.es2015 };
|
||||
let program = Program {
|
||||
ast: self.ast,
|
||||
body,
|
||||
strict: self.ctx.strict,
|
||||
directives: self.directives,
|
||||
lines: self.lines,
|
||||
es2015: self.es2015,
|
||||
supers: self.supers,
|
||||
};
|
||||
Ok((program, self.tokens.unwrap_or_default()))
|
||||
}
|
||||
|
||||
@@ -1149,7 +1169,7 @@ impl<'s> Parser<'s> {
|
||||
generator: bool,
|
||||
) -> Result<crate::ast::FunctionId> {
|
||||
self.enter()?;
|
||||
let rules = SuperRules { property: home, call: kind == FunctionKind::DerivedConstructor, new_target: true };
|
||||
let rules = SuperRules::function(home, kind == FunctionKind::DerivedConstructor);
|
||||
let outer = std::mem::replace(&mut self.supers, rules);
|
||||
// The parameters are read with the function's own `yield` rule, not the enclosing code's.
|
||||
let outer_generator = std::mem::replace(&mut self.ctx.generator, generator);
|
||||
|
||||
@@ -1615,7 +1615,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.colorWheel",
|
||||
"Color Wheel Options",
|
||||
"",
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing,
Line truncated
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Opacity, Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection;
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.savePdfDialog",
|
||||
|
||||
@@ -253,6 +253,8 @@ pub struct ToolContext<'a> {
|
||||
pub raster_sample: u32,
|
||||
/// General → Use Preview Bounds: the bounding box measures visual bounds (strokes included).
|
||||
pub preview_bounds: bool,
|
||||
/// General → Scale Strokes & Effects: a scale scales the strokes and effects with the art.
|
||||
pub scale_strokes: bool,
|
||||
/// Type › Measure Type by Glyph Bounds: the bounding box measures each point type object
|
||||
/// selected as an object (not inside a selected group) by the ink of its glyphs
|
||||
/// ([`vectorcraft_effects::preview::Measure`]).
|
||||
|
||||
+174
-51
@@ -1,8 +1,12 @@
|
||||
//! Live Corners: the widgets inside the corners of the selected paths. The Selection tool shows
|
||||
//! them on live rectangles and polygons, Direct Selection on any path (a star, a pen path) at each
|
||||
//! corner anchor: one that isn't smooth, where two sides, straight or curved, meet at an angle. Dragging one rounds (or
|
||||
//! sharpens) the corners whose widgets show together, on every selected path (#938): every corner
|
||||
//! of a path selected whole, those with a selected anchor when Direct Selection picked some. Alt-clicking a widget cycles their corner
|
||||
//! sharpens) the picked corners together, on every selected path (#938): every corner of a path
|
||||
//! selected whole, those with a selected anchor when Direct Selection picked some. Direct Selection
|
||||
//! also shows the widgets of the corners it did not pick, drawn apart from the picked ones, so a
|
||||
//! click or Shift-click on any of them picks it (#1232); a plain click on a picked one keeps the
|
||||
//! picks, so a double-click opens Corners for all of them; dragging or Alt-clicking one that is
|
||||
//! not picked adds its corner to the edit. Alt-clicking a widget cycles their corner
|
||||
//! kind (round, inverted round, chamfer), as the Up and Down arrows do while one is dragged
|
||||
//! (#2898); double-clicking one opens the Corners dialog with Direct Selection and shows the
|
||||
//! Transform panel with the Selection tool. The
|
||||
@@ -40,6 +44,8 @@ struct Widget {
|
||||
angle: f64,
|
||||
/// The widget's centre in the document.
|
||||
at: Point,
|
||||
/// Its corner is picked: a drag, an Alt-click and the Corners dialog edit it.
|
||||
picked: bool,
|
||||
}
|
||||
|
||||
/// The corner widgets of one selected path.
|
||||
@@ -48,16 +54,20 @@ struct PathWidgets {
|
||||
id: NodeId,
|
||||
/// Maps the corners' space into the document (a live rectangle's own; else none).
|
||||
xf: Affine,
|
||||
/// The widgets that show (and which a drag edits), in anchor order.
|
||||
/// The widgets that show, picked or not, in anchor order.
|
||||
widgets: Vec<Widget>,
|
||||
/// Every corner of the path shows its widget.
|
||||
all: bool,
|
||||
/// How many corners the path has, shown or not.
|
||||
total: usize,
|
||||
/// Every corner of the path is selected: the path selected whole, or every corner's anchor.
|
||||
whole: bool,
|
||||
}
|
||||
|
||||
impl PathWidgets {
|
||||
/// The widgets of path `id` at `zoom` (screen px per document point), if it has any: any path
|
||||
/// with Direct Selection (`any_path`), live rectangles and polygons with Selection, when
|
||||
/// `editable` ([`Document::editable`]) answers true for `id`.
|
||||
/// The widgets of path `id` at `zoom` (screen px per document point), if it has corners: any
|
||||
/// path with Direct Selection (`any_path`), every corner's, picked or not; live rectangles' and
|
||||
/// polygons' with Selection, the picked corners' alone. Corners whose sides are too short on
|
||||
/// screen show no widget, so `widgets` can be empty. Only when `editable`
|
||||
/// ([`Document::editable`]) answers true for `id`.
|
||||
fn of(doc: &Document, selection: &Selection, id: NodeId, zoom: f64, any_path: bool, editable: &impl Fn(NodeId) -> bool) -> Option<Self> {
|
||||
if selection.segments.contains_key(&id) {
|
||||
return None;
|
||||
@@ -77,33 +87,54 @@ impl PathWidgets {
|
||||
}
|
||||
// Screen pixels per unit of the corners' space (a rectangle's may be skewed).
|
||||
let scale = zoom * det.sqrt();
|
||||
let picked = lc.picked(selection.partial(id));
|
||||
let partial = selection.partial(id);
|
||||
let picked = lc.picked(partial);
|
||||
let whole = partial.is_none_or(|anchors| lc.all().is_subset(&lc.corners_of(anchors)));
|
||||
let widgets: Vec<_> = lc
|
||||
.corners
|
||||
.iter()
|
||||
.filter(|c| picked.contains(&c.index) && c.lu.min(c.lv) * scale >= MIN_SIDE_PX)
|
||||
.filter(|c| (any_path || picked.contains(&c.index)) && c.lu.min(c.lv) * scale >= MIN_SIDE_PX)
|
||||
.map(|c| {
|
||||
// On the bisector at the centre of the arc as drawn, at least the minimum inset
|
||||
// in and at most half the shorter side.
|
||||
let (radius, drawn) = (lc.radius(c.index), lc.drawn_radius(c.index));
|
||||
let k = (drawn / c.sin()).max(MIN_INSET_PX / (scale * (1.0 + c.cos()).sqrt())).min(c.lu.min(c.lv) / 2.0);
|
||||
Widget { corner: *c, radius, drawn, kind: lc.kind(c.index), angle: angle_in(lc.xf, c), at: lc.xf * c.on_bisector(k) }
|
||||
let at = lc.xf * c.on_bisector(k);
|
||||
Widget { corner: *c, radius, drawn, kind: lc.kind(c.index), angle: angle_in(lc.xf, c), at, picked: picked.contains(&c.index) }
|
||||
})
|
||||
.collect();
|
||||
let all = widgets.len() == lc.corners.len();
|
||||
(!widgets.is_empty()).then_some(Self { id, xf: lc.xf, widgets, all })
|
||||
Some(Self { id, xf: lc.xf, widgets, total: lc.corners.len(), whole })
|
||||
}
|
||||
|
||||
/// The corners whose widgets show: anchor indices of the path's uncut outline.
|
||||
fn corners(&self) -> Vec<usize> {
|
||||
self.widgets.iter().map(|w| w.corner.index).collect()
|
||||
}
|
||||
|
||||
/// The shown corners that are picked, which an edit changes.
|
||||
fn edited(&self) -> Vec<usize> {
|
||||
self.widgets.iter().filter(|w| w.picked).map(|w| w.corner.index).collect()
|
||||
}
|
||||
|
||||
/// An edit changes every corner of the path, which the selection already selects: each one
|
||||
/// shows and is picked, and none was picked by the press alone.
|
||||
fn edits_every(&self) -> bool {
|
||||
self.whole && self.widgets.len() == self.total && self.widgets.iter().all(|w| w.picked)
|
||||
}
|
||||
|
||||
/// Is shown corner `index` edited?
|
||||
fn edits(&self, index: usize) -> bool {
|
||||
self.widgets.iter().any(|w| w.picked && w.corner.index == index)
|
||||
}
|
||||
}
|
||||
|
||||
/// The corner widgets of the selected paths that have some.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CornerWidgets {
|
||||
paths: Vec<PathWidgets>,
|
||||
/// Every corner of every selected path with corners is selected, those whose widgets are
|
||||
/// hidden included.
|
||||
every: bool,
|
||||
}
|
||||
|
||||
impl CornerWidgets {
|
||||
@@ -113,17 +144,17 @@ impl CornerWidgets {
|
||||
// Made for the first path, then shared: the art on the locked artboards is measured once.
|
||||
let locks = std::cell::OnceCell::new();
|
||||
let editable = |id| locks.get_or_init(|| doc.editable())(id);
|
||||
let paths: Vec<_> = selection.objects.iter().filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path, &editable)).collect();
|
||||
(!paths.is_empty()).then_some(Self { paths })
|
||||
let mut paths: Vec<_> = selection.objects.iter().filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path, &editable)).collect();
|
||||
let every = paths.iter().all(|p| p.whole);
|
||||
paths.retain(|p| !p.widgets.is_empty());
|
||||
(!paths.is_empty()).then_some(Self { paths, every })
|
||||
}
|
||||
|
||||
/// Selection & Anchor Display → Hide Corner Widget for angles greater than: the widgets of
|
||||
/// corners wider than `max` degrees (in the document) hide; none if all do.
|
||||
pub fn within_angle(mut self, max: f64) -> Option<Self> {
|
||||
for p in &mut self.paths {
|
||||
let n = p.widgets.len();
|
||||
p.widgets.retain(|w| w.angle <= max + 1e-9);
|
||||
p.all &= p.widgets.len() == n;
|
||||
}
|
||||
self.paths.retain(|p| !p.widgets.is_empty());
|
||||
(!self.paths.is_empty()).then_some(self)
|
||||
@@ -147,12 +178,13 @@ impl CornerWidgets {
|
||||
|
||||
/// The centres of the widgets that show.
|
||||
pub fn visible(&self) -> impl Iterator<Item = Point> + '_ {
|
||||
self.visible_on().map(|(_, at)| at)
|
||||
self.visible_on().map(|(_, at, _)| at)
|
||||
}
|
||||
|
||||
/// The centres of the widgets that show, each with the object it belongs to.
|
||||
pub fn visible_on(&self) -> impl Iterator<Item = (NodeId, Point)> + '_ {
|
||||
self.paths.iter().flat_map(|p| p.widgets.iter().map(move |w| (p.id, w.at)))
|
||||
/// The centers of the widgets that show, each with the object it belongs to and whether its
|
||||
/// corner is picked.
|
||||
pub fn visible_on(&self) -> impl Iterator<Item = (NodeId, Point, bool)> + '_ {
|
||||
self.paths.iter().flat_map(|p| p.widgets.iter().map(move |w| (p.id, w.at, w.picked)))
|
||||
}
|
||||
|
||||
/// The corners whose widgets show, path after path: anchor indices of each path's uncut
|
||||
@@ -161,28 +193,37 @@ impl CornerWidgets {
|
||||
self.paths.iter().flat_map(PathWidgets::corners).collect()
|
||||
}
|
||||
|
||||
/// The widget nearest to `p` within `tol` (document units): its path's and its own index.
|
||||
/// The shown corners that are picked, path after path, which a drag, an Alt-click or the
|
||||
/// Corners dialog edit.
|
||||
pub fn picked(&self) -> Vec<usize> {
|
||||
self.paths.iter().flat_map(PathWidgets::edited).collect()
|
||||
}
|
||||
|
||||
/// The widget nearest to `p` within `tol` (document units): its path's and its own index. Of
|
||||
/// widgets at the same spot, a picked one.
|
||||
fn hit(&self, p: Point, tol: f64) -> Option<(usize, usize)> {
|
||||
let d = |&(i, k): &(usize, usize)| self.widget(i, k).map_or(f64::INFINITY, |w| w.at.distance(p));
|
||||
let unpicked = |&(i, k): &(usize, usize)| self.widget(i, k).is_none_or(|w| !w.picked);
|
||||
self.paths
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, path)| (0..path.widgets.len()).map(move |k| (i, k)))
|
||||
.filter(|ik| d(ik) <= tol)
|
||||
.min_by(|a, b| d(a).total_cmp(&d(b)))
|
||||
.min_by(|a, b| d(a).total_cmp(&d(b)).then(unpicked(a).cmp(&unpicked(b))))
|
||||
}
|
||||
|
||||
fn widget(&self, path: usize, k: usize) -> Option<&Widget> {
|
||||
self.paths.get(path).and_then(|p| p.widgets.get(k))
|
||||
}
|
||||
|
||||
/// `object.setLiveShape` params setting `key` on the shown corners (every corner of a path
|
||||
/// unless some are hidden, which `corners` then leaves out): one path by its `id`, several as
|
||||
/// `items`.
|
||||
/// `object.setLiveShape` params setting `key` on the picked corners that show (every corner of
|
||||
/// a path when all are, which `corners` then leaves out): one path by its `id`, several as
|
||||
/// `items`. Paths with no picked corner whose widget shows are left out.
|
||||
fn command(&self, key: &str, value: Value) -> Value {
|
||||
let corners = |p: &PathWidgets| (!p.all).then(|| p.corners());
|
||||
let corners = |p: &PathWidgets| (!p.edits_every()).then(|| p.edited());
|
||||
let paths: Vec<&PathWidgets> = self.paths.iter().filter(|p| p.widgets.iter().any(|w| w.picked)).collect();
|
||||
let mut out = Map::new();
|
||||
match self.paths.as_slice() {
|
||||
match paths.as_slice() {
|
||||
[p] => {
|
||||
out.insert("id".into(), json!(p.id.0));
|
||||
if let Some(c) = corners(p) {
|
||||
@@ -244,16 +285,38 @@ fn angle_in(xf: Affine, c: &Corner) -> f64 {
|
||||
|
||||
/// Is `p` over a corner widget the active tool would drag (Direct Selection: `any_path`)?
|
||||
pub fn over_widget(cx: &ToolContext, p: Point, any_path: bool) -> bool {
|
||||
CornerWidgets::for_tool(cx, any_path).and_then(|w| w.hit(p, cx.tol(5.0))).is_some()
|
||||
widget_at(cx, p, any_path).is_some()
|
||||
}
|
||||
|
||||
/// A double-click on a corner widget opens the Corners dialog for the shown corners of its path
|
||||
/// (Direct Selection; the Selection tool shows the Transform panel instead).
|
||||
pub fn double_click(cx: &ToolContext, p: Point, any_path: bool) -> Option<Action> {
|
||||
/// The corner widget at `p` the active tool would drag (Direct Selection: `any_path`): whether its
|
||||
/// corner is picked, and its center.
|
||||
pub fn widget_at(cx: &ToolContext, p: Point, any_path: bool) -> Option<(bool, Point)> {
|
||||
let w = CornerWidgets::for_tool(cx, any_path)?;
|
||||
let (i, _) = w.hit(p, cx.tol(5.0))?;
|
||||
let (i, k) = w.hit(p, cx.tol(5.0))?;
|
||||
w.widget(i, k).map(|w| (w.picked, w.at))
|
||||
}
|
||||
|
||||
/// A double-click on a corner widget opens the Corners dialog for the picked corners of its path
|
||||
/// that show, or for the clicked widget's corner alone when it is not picked (Direct Selection;
|
||||
/// the Selection tool shows the Transform panel instead). With Direct Selection the
|
||||
/// double-click's first click has left the picks as they are on a picked widget,
|
||||
/// and picked that corner alone on one that is not (`CornerDrag::finish`).
|
||||
pub fn double_click(cx: &ToolContext, p: Point, any_path: bool) -> Option<Action> {
|
||||
double_click_unless(cx, p, any_path, |_| false)
|
||||
}
|
||||
|
||||
/// [`double_click`], except that a widget whose corner is not picked does nothing when `yields`
|
||||
/// for its center (something else under the pointer takes the double-click).
|
||||
pub fn double_click_unless(cx: &ToolContext, p: Point, any_path: bool, yields: impl FnOnce(Point) -> bool) -> Option<Action> {
|
||||
let w = CornerWidgets::for_tool(cx, any_path)?;
|
||||
let (i, k) = w.hit(p, cx.tol(5.0))?;
|
||||
let path = w.paths.get(i)?;
|
||||
Some(Action::Dialog(DIALOG.into(), json!({ "id": path.id.0, "corners": path.corners() })))
|
||||
let clicked = path.widgets.get(k)?;
|
||||
if !clicked.picked && yields(clicked.at) {
|
||||
return None;
|
||||
}
|
||||
let corners: Vec<usize> = if clicked.picked { path.edited() } else { vec![clicked.corner.index] };
|
||||
Some(Action::Dialog(DIALOG.into(), json!({ "id": path.id.0, "corners": corners })))
|
||||
}
|
||||
|
||||
/// A path's uncut outline with its corners' radii and kinds, and the corners' space (to outline
|
||||
@@ -289,6 +352,8 @@ pub struct CornerDrag {
|
||||
at: Point,
|
||||
/// Direct Selection: what a click (no drag) on the pressed widget selects.
|
||||
click: Option<CornerClick>,
|
||||
/// The pressed widget's corner was not picked: the press adds it to the edit.
|
||||
unpicked: bool,
|
||||
/// The corner kind the Up and Down arrows picked during the drag, which it sets with the
|
||||
/// radius (#2898); None: the corners keep theirs.
|
||||
kind: Option<CornerKind>,
|
||||
@@ -300,7 +365,21 @@ pub struct CornerDrag {
|
||||
struct CornerClick {
|
||||
id: NodeId,
|
||||
anchors: Vec<(usize, usize)>,
|
||||
shift: bool,
|
||||
mode: ClickMode,
|
||||
}
|
||||
|
||||
/// How a click on a widget changes the selected anchors.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum ClickMode {
|
||||
/// The corner alone is selected.
|
||||
Set,
|
||||
/// The selection stays as it is: a plain click on a picked widget while some corners are not
|
||||
/// picked, as a plain click on one of several selected anchors keeps them.
|
||||
Keep,
|
||||
/// The corner's anchors are toggled on a path with some anchors selected.
|
||||
Toggle,
|
||||
/// The corner's anchors are toggled on a path selected whole, starting from all of them.
|
||||
ToggleWhole,
|
||||
}
|
||||
|
||||
impl CornerDrag {
|
||||
@@ -309,26 +388,63 @@ impl CornerDrag {
|
||||
self.began
|
||||
}
|
||||
|
||||
/// The pressed widget's corner is not picked.
|
||||
pub fn on_unpicked(&self) -> bool {
|
||||
self.unpicked
|
||||
}
|
||||
|
||||
/// The pressed widget's center.
|
||||
pub fn widget_center(&self) -> Option<Point> {
|
||||
self.widgets.widget(self.widget.0, self.widget.1).map(|w| w.at)
|
||||
}
|
||||
|
||||
/// Start a drag when the press `ev` is on a widget of the selection (Direct Selection:
|
||||
/// `any_path`).
|
||||
pub fn hit(cx: &ToolContext, ev: &PointerEvent, any_path: bool) -> Option<Self> {
|
||||
let (widgets, p) = (CornerWidgets::for_tool(cx, any_path)?, ev.pos);
|
||||
let (mut widgets, p) = (CornerWidgets::for_tool(cx, any_path)?, ev.pos);
|
||||
let widget = widgets.hit(p, cx.tol(5.0))?;
|
||||
let radius = widgets.widget(widget.0, widget.1)?.radius;
|
||||
let (radius, unpicked) = widgets.widget(widget.0, widget.1).map(|w| (w.radius, !w.picked))?;
|
||||
let click = any_path
|
||||
.then(|| {
|
||||
let path = widgets.paths.get(widget.0)?;
|
||||
let corner = path.widgets.get(widget.1)?.corner.index;
|
||||
let lc = cx.doc.node(path.id).and_then(LiveCorners::of)?;
|
||||
// While every corner is selected (the path selected whole), a Shift-click picks
|
||||
// this corner alone, as the first click of "click one widget, then Shift-click the
|
||||
// others" does: toggling it would deselect it and leave the rest (#5188). Selected
|
||||
// anchors that are no corner show every widget too, but select no corner: there a
|
||||
// Shift-click adds the corner.
|
||||
let every = cx.selection.partial(path.id).is_none_or(|anchors| lc.all().is_subset(&lc.corners_of(anchors)));
|
||||
Some(CornerClick { id: path.id, anchors: lc.anchors_of(&[corner].into()).into_iter().collect(), shift: ev.mods.shift && !every })
|
||||
// While every corner of every selected path is selected (the paths selected
|
||||
// whole), a Shift-click picks this corner alone, as the first click of "click one
|
||||
// widget, then Shift-click the others" does: toggling it would deselect it and
|
||||
// leave the rest (#5188). A path whose widgets are all hidden counts too, so its
|
||||
// picks are kept. Selected anchors that are no corner show every widget too, but
|
||||
// select no corner: there a Shift-click adds the corner.
|
||||
let every = widgets.every;
|
||||
// A plain click on a widget whose corner is selected keeps the picks, so the second
|
||||
// click of a double-click opens Corners for all of them. Anchors that are no corner
|
||||
// pick every widget but select no corner.
|
||||
let selected = cx.selection.partial(path.id).is_none_or(|anchors| lc.corners_of(anchors).contains(&corner));
|
||||
let mode = match (ev.mods.shift && !every, cx.selection.partial(path.id).is_some()) {
|
||||
(false, _) if !every && !unpicked && selected => ClickMode::Keep,
|
||||
(false, _) => ClickMode::Set,
|
||||
(true, true) => ClickMode::Toggle,
|
||||
// A path selected whole beside others with corners picked: the Shift-click
|
||||
// deselects this corner and keeps the rest of the path selected.
|
||||
(true, false) => ClickMode::ToggleWhole,
|
||||
};
|
||||
// A toggle takes the corner out or puts it in whole: of a corner drawn with two
|
||||
// anchors, it flips only the selected ones of a selected corner and only the others
|
||||
// of a corner not selected, so one selected anchor does not swap for the other.
|
||||
let partial = cx.selection.partial(path.id);
|
||||
let anchors = lc
|
||||
.anchors_of(&[corner].into())
|
||||
.into_iter()
|
||||
.filter(|a| mode != ClickMode::Toggle || partial.is_some_and(|s| s.contains(a)) == selected)
|
||||
.collect();
|
||||
Some(CornerClick { id: path.id, anchors, mode })
|
||||
})
|
||||
.flatten();
|
||||
// Pressing a widget whose corner is not picked adds that corner to what the press edits;
|
||||
// the press does not pick it.
|
||||
if let Some(w) = widgets.paths.get_mut(widget.0).and_then(|path| path.widgets.get_mut(widget.1)) {
|
||||
w.picked = true;
|
||||
}
|
||||
let outlines = widgets
|
||||
.paths
|
||||
.iter()
|
||||
@@ -351,6 +467,7 @@ impl CornerDrag {
|
||||
at_limit: false,
|
||||
at: p,
|
||||
click,
|
||||
unpicked,
|
||||
kind: None,
|
||||
})
|
||||
}
|
||||
@@ -369,21 +486,21 @@ impl CornerDrag {
|
||||
(r.min(max).max(0.0), max > 0.0 && r >= max)
|
||||
}
|
||||
|
||||
/// The largest radius `corner` of shown path `path` draws while the drag sets every shown
|
||||
/// The largest radius `corner` of shown path `path` draws while the drag sets every edited
|
||||
/// corner of that path to one radius: up to the cuts of its neighbours, as far as its own
|
||||
/// sides when they are square (#2332).
|
||||
fn max_radius(&self, path: usize, corner: &Corner) -> f64 {
|
||||
let (Some(shown), Some(o)) = (self.widgets.paths.get(path), self.outlines.get(path)) else { return corner.max_radius() };
|
||||
corner.max_shared_radius(&o.corners, &o.radii, |k| shown.widgets.iter().any(|w| w.corner.index == k))
|
||||
corner.max_shared_radius(&o.corners, &o.radii, |k| shown.edits(k))
|
||||
}
|
||||
|
||||
/// The cuts of the edited corners that are at their largest radius, in document coordinates.
|
||||
fn corners_at_limit(&self) -> BezPath {
|
||||
let mut out = BezPath::new();
|
||||
for (n, (shown, o)) in self.widgets.paths.iter().zip(&self.outlines).enumerate() {
|
||||
let shown = &shown.widgets;
|
||||
let shown: Vec<&Widget> = shown.widgets.iter().filter(|w| w.picked).collect();
|
||||
let mut radii = o.radii.clone();
|
||||
for w in shown {
|
||||
for w in &shown {
|
||||
if let Some(r) = radii.get_mut(w.corner.index) {
|
||||
*r = self.radius;
|
||||
}
|
||||
@@ -466,9 +583,15 @@ impl CornerDrag {
|
||||
vec![Action::Exec("object.setLiveShape".into(), self.widgets.command("kind", json!(w.kind.next())))]
|
||||
} else if let Some(c) = self.click {
|
||||
// Direct Selection: the click selects the widget's corner, so the next drag on this
|
||||
// widget rounds that corner alone (its widget is then the only one showing).
|
||||
let mode = if c.shift { "toggle" } else { "set" };
|
||||
vec![Action::Exec("select.anchors".into(), json!({"id": c.id.0, "anchors": c.anchors, "mode": mode}))]
|
||||
// widget rounds that corner alone; the other corners' widgets show as not picked.
|
||||
match c.mode {
|
||||
ClickMode::Keep => vec![],
|
||||
ClickMode::Set => vec![Action::Exec("select.anchors".into(), json!({"id": c.id.0, "anchors": c.anchors, "mode": "set"}))],
|
||||
ClickMode::Toggle => vec![Action::Exec("select.anchors".into(), json!({"id": c.id.0, "anchors": c.anchors, "mode": "toggle"}))],
|
||||
ClickMode::ToggleWhole => {
|
||||
vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": c.id.0, "anchors": c.anchors}], "mode": "toggle"}))]
|
||||
}
|
||||
}
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
|
||||
@@ -119,10 +119,12 @@ fn widgets_of_several_selected_paths_drag_together() {
|
||||
assert!((radius(&preview[1]) - 15.0).abs() < 1e-9);
|
||||
let Action::Preview(_, v) = &preview[1] else { panic!() };
|
||||
assert_eq!(v["items"], json!([{"id": a.0}, {"id": b.0}]));
|
||||
// Direct Selection with one anchor of the first: its corner, and the whole second.
|
||||
// Direct Selection with one anchor of the first: every widget shows, and a drag edits its
|
||||
// corner and the whole second.
|
||||
s.anchors.insert(a, [(0, 2)].into());
|
||||
let w = CornerWidgets::of(&d, &s, 1.0, true).unwrap();
|
||||
assert_eq!(w.corners(), [2, 0, 1, 2, 3]);
|
||||
assert_eq!(w.corners(), [0, 1, 2, 3, 0, 1, 2, 3]);
|
||||
assert_eq!(w.picked(), [2, 0, 1, 2, 3]);
|
||||
assert_eq!(w.command("radius", json!(5.0)), json!({"items": [{"id": a.0, "corners": [2]}, {"id": b.0}], "radius": 5.0}));
|
||||
}
|
||||
|
||||
@@ -213,11 +215,11 @@ fn a_click_on_a_widget_with_direct_selection_selects_its_corner() {
|
||||
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y)).is_empty());
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
|
||||
assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": anchors, "mode": "set"}))]);
|
||||
// With that corner selected, its widget alone shows, and a drag rounds it alone
|
||||
// (`direct_selected_corners_show_their_widgets_alone_and_round_alone`).
|
||||
// With that corner selected, its widget alone is picked, and a drag on it rounds it alone
|
||||
// (`direct_selected_corners_are_picked_and_round_alone`).
|
||||
let mut part = selected(id);
|
||||
part.anchors.insert(id, anchors.iter().copied().collect());
|
||||
assert_eq!(CornerWidgets::of(&d, &part, 1.0, true).unwrap().corners(), [2]);
|
||||
assert_eq!(CornerWidgets::of(&d, &part, 1.0, true).unwrap().picked(), [2]);
|
||||
// A Shift-click on it then deselects it.
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let one = crate::testutil::cx(&d, &part, &p);
|
||||
@@ -256,12 +258,40 @@ fn a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner() {
|
||||
let mut every = selected(id);
|
||||
every.anchors.insert(id, (0..4).flat_map(anchors).collect());
|
||||
assert_eq!(click(&every, w[1]), pick(1, "set"));
|
||||
// Two corners picked: a Shift-click on either widget deselects that corner.
|
||||
// Two corners picked: every widget still shows; a Shift-click on a picked one deselects that
|
||||
// corner, and on one not picked adds it (#1232).
|
||||
let mut two = selected(id);
|
||||
two.anchors.insert(id, [0, 2].into_iter().flat_map(anchors).collect());
|
||||
let shown = pts(&CornerWidgets::of(&d, &two, 1.0, true).unwrap());
|
||||
assert_eq!(shown, [w[0], w[2]]);
|
||||
assert_eq!(shown, w);
|
||||
assert_eq!(click(&two, w[0]), pick(0, "toggle"));
|
||||
assert_eq!(click(&two, w[1]), pick(1, "toggle"));
|
||||
}
|
||||
|
||||
/// #1232: a Shift-click on the widget of a rounded corner picked by one of its two anchors takes
|
||||
/// the corner out whole (that anchor), and on a corner not picked puts both anchors in, so it never
|
||||
/// swaps one anchor for the other and leaves the corner picked.
|
||||
#[test]
|
||||
fn a_shift_click_toggles_a_rounded_corner_whole() {
|
||||
let (d, id) = live_rect(10.0, Affine::translate((100.0, 100.0)));
|
||||
let p = paint();
|
||||
let lc = LiveCorners::of(d.node(id).unwrap()).unwrap();
|
||||
let anchors = |k: usize| -> Vec<(usize, usize)> { lc.anchors_of(&[k].into()).into_iter().collect() };
|
||||
// One anchor of corner 0 and one of corner 2.
|
||||
let (first, second) = (anchors(0)[0], anchors(2)[1]);
|
||||
let mut s = selected(id);
|
||||
s.anchors.insert(id, [first, second].into());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let w = pts(&CornerWidgets::for_tool(&cx, true).unwrap());
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let click = |at: Point| {
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(shift))
|
||||
};
|
||||
let toggle = |a: Vec<(usize, usize)>| vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": a, "mode": "toggle"}))];
|
||||
assert_eq!(click(w[2]), toggle(vec![second]));
|
||||
assert_eq!(click(w[1]), toggle(anchors(1)));
|
||||
}
|
||||
|
||||
/// #5188: an anchor selected that is no corner (here half way along a side) shows every widget
|
||||
@@ -285,10 +315,274 @@ fn a_shift_click_on_a_widget_adds_to_anchors_that_are_no_corner() {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(shift));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(shift));
|
||||
assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": anchors, "mode": "toggle"}))]);
|
||||
// A plain click picks the corner alone: no corner was selected to keep (#1232).
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y));
|
||||
assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": anchors, "mode": "set"}))]);
|
||||
}
|
||||
|
||||
/// Two live 100 × 100 rectangles with square corners, at (100, 100) and (300, 100).
|
||||
fn two_rects() -> (Document, NodeId, NodeId) {
|
||||
let (mut d, a) = live_rect(0.0, Affine::translate((100.0, 100.0)));
|
||||
let live = LiveShape::Rectangle {
|
||||
w: 100.0,
|
||||
h: 100.0,
|
||||
radii: [0.0; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: Affine::translate((300.0, 100.0)),
|
||||
};
|
||||
let b = d.alloc_id();
|
||||
let mut n = Node::path(b, live.to_path(), Appearance::default_art());
|
||||
if let NodeKind::Path { live: slot, .. } = &mut n.kind {
|
||||
*slot = Some(Box::new(live));
|
||||
}
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 1, n).unwrap();
|
||||
(d, a, b)
|
||||
}
|
||||
|
||||
/// #1232: with some corners picked, a press on a widget that is not picked adds its corner to what
|
||||
/// the press edits: a drag rounds it with the picked ones and an Alt-click cycles their kind, and
|
||||
/// the press picks nothing. A drag on a picked widget edits the picked corners alone. A plain
|
||||
/// click on a widget not picked picks its corner alone, and on a picked one keeps the picks, so a
|
||||
/// double-click on a picked widget opens Corners for every picked corner.
|
||||
#[test]
|
||||
fn a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners() {
|
||||
let (d, id) = live_rect(0.0, Affine::translate((100.0, 100.0)));
|
||||
// The top-left and bottom-right corners picked.
|
||||
let mut s = selected(id);
|
||||
s.anchors.insert(id, [(0, 0), (0, 2)].into());
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let preview = |at: (f64, f64), to: (f64, f64)| {
|
||||
let mut t = crate::create("directSelection");
|
||||
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.0, at.1)).is_empty());
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1));
|
||||
assert_eq!(a[0], Action::Begin("Corner Radius".into()));
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1)), vec![Action::Commit], "one undo step");
|
||||
a[1].clone()
|
||||
};
|
||||
// The top-right widget (not picked) dragged in: corners 0, 1 and 2 round.
|
||||
assert_eq!(
|
||||
preview((190.0, 110.0), (175.0, 125.0)),
|
||||
Action::Preview("object.setLiveShape".into(), json!({"id": id.0, "radius": 15.0, "corners": [0, 1, 2]}))
|
||||
);
|
||||
// The top-left widget (picked) dragged in: corners 0 and 2 alone.
|
||||
assert_eq!(
|
||||
preview((110.0, 110.0), (125.0, 125.0)),
|
||||
Action::Preview("object.setLiveShape".into(), json!({"id": id.0, "radius": 15.0, "corners": [0, 2]}))
|
||||
);
|
||||
// With three picked, the fourth widget's drag edits every corner, named one by one: without
|
||||
// `corners`, the command would edit the three the selection picks.
|
||||
let mut three = selected(id);
|
||||
three.anchors.insert(id, [(0, 0), (0, 1), (0, 2)].into());
|
||||
let cx3 = crate::testutil::cx(&d, &three, &p);
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx3, &PointerEvent::new(PointerKind::Down, 110.0, 190.0));
|
||||
let a = t.pointer(&cx3, &PointerEvent::new(PointerKind::Drag, 125.0, 175.0));
|
||||
assert_eq!(a[1], Action::Preview("object.setLiveShape".into(), json!({"id": id.0, "radius": 15.0, "corners": [0, 1, 2, 3]})));
|
||||
// An Alt-click on the bottom-left widget (not picked) cycles the kind of 0, 2 and 3.
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 190.0).with_mods(alt));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 110.0, 190.0).with_mods(alt));
|
||||
assert_eq!(a, vec![Action::Exec("object.setLiveShape".into(), json!({"id": id.0, "kind": "invertedRound", "corners": [0, 2, 3]}))]);
|
||||
// A double-click on it opens Corners for its corner alone, which its first click picks.
|
||||
let a = crate::create("directSelection").pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 110.0, 190.0));
|
||||
assert_eq!(a, vec![Action::Dialog(DIALOG.into(), json!({"id": id.0, "corners": [3]}))]);
|
||||
// A plain click on it (no drag) picks its corner alone.
|
||||
let bottom_left: Vec<(usize, usize)> = LiveCorners::of(d.node(id).unwrap()).unwrap().anchors_of(&[3].into()).into_iter().collect();
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 190.0));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 110.0, 190.0));
|
||||
assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": bottom_left, "mode": "set"}))]);
|
||||
// A plain click on the picked top-left widget keeps both picks, so a double-click there, whose
|
||||
// first click is such a click, opens Corners for both.
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 110.0));
|
||||
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 110.0, 110.0)).is_empty());
|
||||
let a = crate::create("directSelection").pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 110.0, 110.0));
|
||||
assert_eq!(a, vec![Action::Dialog(DIALOG.into(), json!({"id": id.0, "corners": [0, 2]}))]);
|
||||
}
|
||||
|
||||
/// #1232: over a widget whose corner is not picked, the end of a selected anchor's direction
|
||||
/// handle takes the press, the cursor and the double-click; here the handle of a curve's first
|
||||
/// anchor ends on the rectangle's top-left widget. A picked widget there still takes them.
|
||||
#[test]
|
||||
fn a_handle_end_over_a_widget_not_picked_takes_the_press() {
|
||||
let (mut d, id) = live_rect(0.0, Affine::translate((100.0, 100.0)));
|
||||
let line = d.alloc_id();
|
||||
let (a, b) = (Point::new(150.0, 150.0), Point::new(250.0, 150.0));
|
||||
let anchors = vec![vectorcraft_geom::Anchor::with_handles(a, a, Point::new(110.0, 110.0)), vectorcraft_geom::Anchor::with_handles(b, b, b)];
|
||||
let path = PathData::single(vectorcraft_geom::SubPath::new(anchors, false));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 1, Node::path(line, path, Appearance::default_art())).unwrap();
|
||||
let p = paint();
|
||||
let pressed = |s: &Selection| {
|
||||
let cx = crate::testutil::cx(&d, s, &p);
|
||||
let mut t = crate::create("directSelection");
|
||||
let cursor = t.cursor(&cx, Point::new(110.0, 110.0), Mods::default());
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 110.0));
|
||||
let corner = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 125.0, 125.0)).contains(&Action::Begin("Corner Radius".into()));
|
||||
let double = crate::create("directSelection").pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 110.0, 110.0));
|
||||
(corner, cursor == crate::Cursor::CornerRadius, double.iter().any(|a| matches!(a, Action::Dialog(k, _) if k == DIALOG)))
|
||||
};
|
||||
// The bottom-right corner picked and the curve's first anchor selected: the top-left widget is
|
||||
// not picked, and the handle end takes the press, the cursor and the double-click.
|
||||
let mut s = selected(id);
|
||||
s.add(line);
|
||||
s.anchors.insert(id, [(0, 2)].into());
|
||||
s.anchors.insert(line, [(0, 0)].into());
|
||||
assert_eq!(pressed(&s), (false, false, false));
|
||||
// The top-left corner picked: its widget takes them.
|
||||
s.anchors.insert(id, [(0, 0)].into());
|
||||
assert_eq!(pressed(&s), (true, true, true));
|
||||
}
|
||||
|
||||
/// #1232: over a widget whose corner is not picked, an anchor no farther from the pointer than the
|
||||
/// widget's center takes the press, the cursor and the double-click; here the end of a line that is
|
||||
/// not selected, pressed off the widget's center or on it. One farther than the center, though
|
||||
/// within point tolerance, leaves them to the widget.
|
||||
#[test]
|
||||
fn a_nearer_anchor_over_a_widget_not_picked_takes_the_press() {
|
||||
for (end, at, widget) in
|
||||
[((113.0, 113.0), (112.0, 112.0), false), ((110.0, 110.0), (110.0, 110.0), false), ((109.0, 109.0), (112.0, 112.0), true)]
|
||||
{
|
||||
let (mut d, id) = live_rect(0.0, Affine::translate((100.0, 100.0)));
|
||||
let line = d.alloc_id();
|
||||
let path = PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(end.0, end.1), Point::new(150.0, 160.0)], false));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 1, Node::path(line, path, Appearance::default_art())).unwrap();
|
||||
let p = paint();
|
||||
let mut s = selected(id);
|
||||
s.anchors.insert(id, [(0, 2)].into());
|
||||
let cx = crate::testutil::cx(&d, &s, &p);
|
||||
let at = Point::new(at.0, at.1);
|
||||
let mut t = crate::create("directSelection");
|
||||
let cursor = t.cursor(&cx, at, Mods::default()) == crate::Cursor::CornerRadius;
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y));
|
||||
let corner = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 125.0, 125.0)).contains(&Action::Begin("Corner Radius".into()));
|
||||
let double = crate::create("directSelection").pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y));
|
||||
let dialog = double.iter().any(|a| matches!(a, Action::Dialog(k, _) if k == DIALOG));
|
||||
assert_eq!((corner, cursor, dialog), (widget, widget, widget), "line end at {end:?}, pressed at {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #1232: corners are picked across paths. With a corner of one rectangle picked and the other
|
||||
/// rectangle selected whole, a Shift-click on a widget of either toggles that corner and keeps the
|
||||
/// rest of the selection: on the whole rectangle it deselects the corner and leaves the other
|
||||
/// three selected. A drag on a widget not picked edits it with every picked corner of both.
|
||||
#[test]
|
||||
fn widgets_are_picked_across_paths() {
|
||||
let (d, a, b) = two_rects();
|
||||
let mut s = selected(a);
|
||||
s.add(b);
|
||||
s.anchors.insert(a, [(0, 0)].into());
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let w = CornerWidgets::for_tool(&cx, true).unwrap();
|
||||
assert_eq!(w.corners(), [0, 1, 2, 3, 0, 1, 2, 3]);
|
||||
assert_eq!(w.picked(), [0, 0, 1, 2, 3]);
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let click = |at: Point| {
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(shift))
|
||||
};
|
||||
// The second rectangle's top-right widget (picked, the rectangle selected whole).
|
||||
assert_eq!(
|
||||
click(Point::new(390.0, 110.0)),
|
||||
vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": b.0, "anchors": [[0, 1]]}], "mode": "toggle"}))]
|
||||
);
|
||||
// The first rectangle's top-right widget (not picked).
|
||||
assert_eq!(
|
||||
click(Point::new(190.0, 110.0)),
|
||||
vec![Action::Exec("select.anchors".into(), json!({"id": a.0, "anchors": [[0, 1]], "mode": "toggle"}))]
|
||||
);
|
||||
// Dragging the first rectangle's bottom-left widget (not picked).
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 190.0));
|
||||
let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 125.0, 175.0));
|
||||
assert_eq!(
|
||||
out[1],
|
||||
Action::Preview("object.setLiveShape".into(), json!({"items": [{"id": a.0, "corners": [0, 3]}, {"id": b.0}], "radius": 15.0}))
|
||||
);
|
||||
// Both selected whole: a Shift-click still picks that corner alone (#5188).
|
||||
let both = {
|
||||
let mut s = selected(a);
|
||||
s.add(b);
|
||||
s
|
||||
};
|
||||
let cxb = crate::testutil::cx(&d, &both, &p);
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cxb, &PointerEvent::new(PointerKind::Down, 390.0, 110.0).with_mods(shift));
|
||||
let out = t.pointer(&cxb, &PointerEvent::new(PointerKind::Up, 390.0, 110.0).with_mods(shift));
|
||||
assert_eq!(out, vec![Action::Exec("select.anchors".into(), json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"}))]);
|
||||
}
|
||||
|
||||
/// #1232: a selected path whose widgets are all hidden (its sides too short on screen) still counts
|
||||
/// when deciding whether every corner is picked. With one corner of a small rectangle picked and a
|
||||
/// larger one selected whole, a click on the larger one's widget keeps the picks and a Shift-click
|
||||
/// deselects that corner, so the small rectangle's pick stays.
|
||||
#[test]
|
||||
fn a_path_with_hidden_widgets_keeps_its_picks() {
|
||||
let (mut d, big) = live_rect(0.0, Affine::translate((100.0, 100.0)));
|
||||
let live = LiveShape::Rectangle {
|
||||
w: 20.0,
|
||||
h: 20.0,
|
||||
radii: [0.0; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: Affine::translate((300.0, 100.0)),
|
||||
};
|
||||
let small = d.alloc_id();
|
||||
let mut n = Node::path(small, live.to_path(), Appearance::default_art());
|
||||
if let NodeKind::Path { live: slot, .. } = &mut n.kind {
|
||||
*slot = Some(Box::new(live));
|
||||
}
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 1, n).unwrap();
|
||||
let mut s = selected(big);
|
||||
s.add(small);
|
||||
s.anchors.insert(small, [(0, 0)].into());
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let w = CornerWidgets::for_tool(&cx, true).unwrap();
|
||||
assert_eq!(w.paths.len(), 1, "the small rectangle shows no widget");
|
||||
let press = |mods: Mods| {
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 190.0, 110.0).with_mods(mods));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 190.0, 110.0).with_mods(mods))
|
||||
};
|
||||
assert!(press(Mods::default()).is_empty());
|
||||
assert_eq!(
|
||||
press(Mods { shift: true, ..Mods::default() }),
|
||||
vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": big.0, "anchors": [[0, 1]]}], "mode": "toggle"}))]
|
||||
);
|
||||
}
|
||||
|
||||
/// #1232: a path whose picked corners are all hidden (wider than the angle preference) is left
|
||||
/// out of a drag that starts on another path; the drag edits only corners that are picked or
|
||||
/// pressed.
|
||||
#[test]
|
||||
fn a_path_with_no_picked_widget_showing_is_left_out_of_a_drag() {
|
||||
let (d, a, b) = two_rects();
|
||||
let mut s = selected(a);
|
||||
s.add(b);
|
||||
// One anchor of a picked; b selected whole.
|
||||
s.anchors.insert(a, [(0, 0)].into());
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut w = CornerWidgets::for_tool(&cx, true).unwrap();
|
||||
// Drop the picked flag of a's widgets as if they were all hidden, keeping one unpicked shown.
|
||||
w.paths[0].widgets.retain(|w| !w.picked);
|
||||
assert_eq!(w.command("radius", json!(5.0)), json!({"id": b.0, "radius": 5.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_selected_corners_show_their_widgets_alone_and_round_alone() {
|
||||
fn direct_selected_corners_are_picked_and_round_alone() {
|
||||
let (d, id) = live_rect(0.0, Affine::translate((100.0, 100.0)));
|
||||
// Direct Selection picked the bottom-right anchor.
|
||||
let mut s = selected(id);
|
||||
@@ -296,9 +590,15 @@ fn direct_selected_corners_show_their_widgets_alone_and_round_alone() {
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let w = CornerWidgets::of(&d, &s, 1.0, true).unwrap();
|
||||
assert_eq!(w.corners(), [2]);
|
||||
assert_eq!(pts(&w), [Point::new(190.0, 190.0)]);
|
||||
assert!(!over_widget(&cx, Point::new(110.0, 110.0), true), "the other corners hide theirs");
|
||||
assert_eq!(w.picked(), [2]);
|
||||
let states: Vec<_> = w.visible_on().map(|(_, at, picked)| (at, picked)).collect();
|
||||
let at = |x, y| Point::new(x, y);
|
||||
assert_eq!(states, [(at(110.0, 110.0), false), (at(190.0, 110.0), false), (at(190.0, 190.0), true), (at(110.0, 190.0), false)]);
|
||||
assert!(over_widget(&cx, Point::new(110.0, 110.0), true), "the other corners' widgets show and can be pressed (#1232)");
|
||||
// The Selection tool still shows the picked corners' widgets alone.
|
||||
let selection = CornerWidgets::of(&d, &s, 1.0, false).unwrap();
|
||||
assert_eq!(pts(&selection), [Point::new(190.0, 190.0)]);
|
||||
assert!(!over_widget(&cx, Point::new(110.0, 110.0), false));
|
||||
let mut t = crate::create("directSelection");
|
||||
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 190.0, 191.0)).is_empty());
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 175.0, 176.0));
|
||||
@@ -326,7 +626,7 @@ fn a_corner_rounded_alone_rounds_up_to_its_neighbours() {
|
||||
s.anchors.insert(id, [(0, if top_right > 0.0 { 3 } else { 2 })].into());
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
assert_eq!(CornerWidgets::of(&d, &s, 1.0, true).unwrap().corners(), [2]);
|
||||
assert_eq!(CornerWidgets::of(&d, &s, 1.0, true).unwrap().picked(), [2]);
|
||||
let mut t = crate::create("directSelection");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 190.0, 190.0));
|
||||
assert!((radius(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 130.0))[1]) - 60.0).abs() < 1e-9);
|
||||
@@ -473,7 +773,7 @@ fn star_path(d: &Document, id: NodeId) -> PathData {
|
||||
path.clone()
|
||||
}
|
||||
|
||||
/// #511: a Direct-Selected anchor of the star shows its corner's widget alone, and the
|
||||
/// #511: a Direct-Selected anchor of the star picks its corner's widget alone, and the
|
||||
/// preference hides the star's wide inner corners (about 125°) below their angle.
|
||||
#[test]
|
||||
fn star_corners_follow_the_anchors_and_the_angle_preference() {
|
||||
@@ -483,9 +783,9 @@ fn star_corners_follow_the_anchors_and_the_angle_preference() {
|
||||
let p = paint();
|
||||
let c = cx(&d, &s, &p);
|
||||
let w = CornerWidgets::for_tool(&c, true).unwrap();
|
||||
assert_eq!(w.corners(), [3]);
|
||||
assert_eq!(w.picked(), [3]);
|
||||
let mut t = crate::create("directSelection");
|
||||
let at = pts(&w)[0];
|
||||
let at = pts(&w)[3];
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y));
|
||||
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, at.x + 20.0, at.y + 20.0));
|
||||
assert!(matches!(&a[1], Action::Preview(_, v) if v["corners"] == json!([3])), "{a:?}");
|
||||
|
||||
@@ -67,7 +67,7 @@ use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection, symbol_overr
|
||||
use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2};
|
||||
|
||||
use crate::bbox::move_delta;
|
||||
use crate::corners::{self, CornerDrag, over_widget};
|
||||
use crate::corners::{self, CornerDrag};
|
||||
use crate::guides::{HandleSnap, Leave, PointSnap, Targets};
|
||||
use crate::meshedit::{MeshEdit, grid_of};
|
||||
use crate::pathtype::{self, BracketDrag, near_bracket};
|
||||
@@ -835,6 +835,13 @@ fn type_path_handles(cx: &ToolContext) -> Vec<Overlay> {
|
||||
/// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and
|
||||
/// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path,
|
||||
/// subpath, anchor, is_out).
|
||||
/// A press at `p` on a corner widget centered at `widget` whose corner is not picked goes to a
|
||||
/// direction handle end within point tolerance, or to an anchor no farther from `p` than the
|
||||
/// widget's center, instead; so do the cursor and a double-click (#1232).
|
||||
fn yields_to_point(cx: &ToolContext, p: Point, widget: Point) -> bool {
|
||||
hit_handle(cx, p, cx.point_tol()).is_some() || hit_anchor(cx, p, cx.point_tol().min(widget.distance(p))).is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn hit_handle(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, bool)> {
|
||||
let mut best: Option<((NodeId, usize, usize, bool), f64)> = None;
|
||||
for (id, si, ai, a) in handle_anchors(cx) {
|
||||
@@ -1135,7 +1142,9 @@ impl Tool for DirectSelectionTool {
|
||||
self.click_segment = None;
|
||||
self.click_group = None;
|
||||
self.frame_click = None;
|
||||
if let Some(c) = CornerDrag::hit(cx, ev, true) {
|
||||
if let Some(c) = CornerDrag::hit(cx, ev, true)
|
||||
&& !(c.on_unpicked() && c.widget_center().is_some_and(|w| yields_to_point(cx, p, w)))
|
||||
{
|
||||
self.state = State::Corner(c);
|
||||
return vec![];
|
||||
}
|
||||
@@ -1387,7 +1396,10 @@ impl Tool for DirectSelectionTool {
|
||||
}
|
||||
}
|
||||
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
|
||||
if !self.group && (matches!(self.state, State::Corner(_)) || over_widget(cx, p, true)) {
|
||||
if !self.group
|
||||
&& (matches!(self.state, State::Corner(_))
|
||||
|| corners::widget_at(cx, p, true).is_some_and(|(picked, w)| picked || !yields_to_point(cx, p, w)))
|
||||
{
|
||||
return Cursor::CornerRadius;
|
||||
}
|
||||
if !self.group && (matches!(self.state, State::Bracket(_)) || near_bracket(cx, p) && !over_path_type_anchor(cx, p)) {
|
||||
@@ -1650,7 +1662,9 @@ impl DirectSelectionTool {
|
||||
}
|
||||
fn double_click(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point) -> Vec<Action> {
|
||||
self.state = State::Idle;
|
||||
if let Some(a) = corners::double_click(cx, p, true) {
|
||||
// As with a press, a handle end or a nearer anchor takes the double-click from a widget that
|
||||
// is not picked.
|
||||
if let Some(a) = corners::double_click_unless(cx, p, true, |w| yields_to_point(cx, p, w)) {
|
||||
return vec![a];
|
||||
}
|
||||
if let Some(a) = release_guide_at(cx, p, ev.mods) {
|
||||
|
||||
@@ -116,6 +116,10 @@ pub struct PointSnap {
|
||||
/// The kind of edit the point serves: whether Snap to Pixel rounds it
|
||||
/// ([`ToolContext::snaps_to_pixel`]).
|
||||
op: PixelOp,
|
||||
/// For a scale with Smart Guides and Use Preview Bounds on: the selection's geometric bounds,
|
||||
/// whose edges line up with the other art's geometric bounds while the handle drags the visual
|
||||
/// box ([`Self::snap_scale`]).
|
||||
edges: Option<OrientedBox>,
|
||||
}
|
||||
|
||||
impl PointSnap {
|
||||
@@ -134,6 +138,17 @@ impl PointSnap {
|
||||
Self::for_op(cx, PixelOp::Scaling, targets)
|
||||
}
|
||||
|
||||
/// [`Self::scaling`] for the selection's bounding box: with Smart Guides and Use Preview
|
||||
/// Bounds on, the selection's geometric bounds are the edges that line up.
|
||||
pub fn scaling_selection(cx: &ToolContext) -> Self {
|
||||
let mut snap = Self::scaling(cx, || Targets::for_scale(cx));
|
||||
if snap.targets.is_some() && cx.smart_guides && cx.preview_bounds {
|
||||
let geometric = vectorcraft_effects::preview::Measure { preview: false, ..cx.bounds_measure() };
|
||||
snap.edges = vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, geometric);
|
||||
}
|
||||
snap
|
||||
}
|
||||
|
||||
fn for_op(cx: &ToolContext, op: PixelOp, targets: impl FnOnce() -> Targets) -> Self {
|
||||
let targets = if cx.snaps_to_pixel(op) || cx.snap_to_grid {
|
||||
None
|
||||
@@ -147,7 +162,7 @@ impl PointSnap {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Self { targets, op }
|
||||
Self { targets, op, edges: None }
|
||||
}
|
||||
|
||||
/// Snapping for a point placed anywhere, as a drawing tool's ([`DrawSnap`]) is: the art in the
|
||||
@@ -182,7 +197,10 @@ impl PointSnap {
|
||||
/// Snap to Pixel on for scaling, the corner or side the handle moves lines up with whole
|
||||
/// pixels, and with Snap to Grid on it lines up with the nearest gridline, however far that
|
||||
/// is; neither shows guides. Otherwise the handle snaps to the targets [`Self::scaling`]
|
||||
/// gathered.
|
||||
/// gathered. With Smart Guides and Use Preview Bounds on, the edges of the selection's
|
||||
/// geometric bounds line up with the targets, which are the other art's geometric bounds, while
|
||||
/// the handle stays on the visual box (#6436). The margins between the two boxes keep their
|
||||
/// size unless Scale Strokes & Effects is on.
|
||||
pub fn snap_scale(
|
||||
&self,
|
||||
cx: &ToolContext,
|
||||
@@ -205,8 +223,10 @@ impl PointSnap {
|
||||
// one step always finds one.
|
||||
return (Targets::grid_lines(moved, step).snap_scale(bx, handle, a, proportional, from_center, step).0, vec![]);
|
||||
}
|
||||
// The geometric box lines up when it turns with the box the handle drags.
|
||||
let edges = self.edges.filter(|g| (g.angle - bx.angle).abs() <= 1e-9).map(|g| (g.rect, !cx.scale_strokes));
|
||||
match &self.targets {
|
||||
Some((t, tol)) => t.snap_scale(bx, handle, a, proportional, from_center, cx.tol(*tol)),
|
||||
Some((t, tol)) => t.snap_scale_edges(bx, edges, handle, a, proportional, from_center, cx.tol(*tol)),
|
||||
None => (a, vec![]),
|
||||
}
|
||||
}
|
||||
@@ -448,7 +468,7 @@ impl DrawSnap {
|
||||
/// Guides snapping tolerance (the Knife's straight cut). The targets serve this press only.
|
||||
pub fn press_on_paths(&mut self, cx: &ToolContext, p: Point) -> Point {
|
||||
let targets = Targets::for_drawing(cx.doc, &[], visible(cx), None).styled(cx).anchors_and_paths();
|
||||
self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing }));
|
||||
self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing, edges: None }));
|
||||
self.snap(cx, p, None)
|
||||
}
|
||||
|
||||
@@ -467,7 +487,7 @@ impl DrawSnap {
|
||||
/// again on every move, as [`PointSnap::snap_from`] reads pixels and the grid), nothing in
|
||||
/// reach, or an anchor, center or crossing in reach of `p` or at `corner`.
|
||||
pub fn circle_radius(&mut self, cx: &ToolContext, center: Point, p: Point, corner: Point, r: f64) -> Option<f64> {
|
||||
let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return None };
|
||||
let Some((_, PointSnap { targets: Some((t, tol)), op, .. })) = &self.targets else { return None };
|
||||
if !cx.smart_guides || !cx.snap_tangent || cx.snaps_to_pixel(*op) || cx.snap_to_grid {
|
||||
return None;
|
||||
}
|
||||
@@ -517,7 +537,7 @@ impl DrawSnap {
|
||||
/// gathered ([`Targets::snap_hit`]), whether or not its guides show. False with Smart Guides
|
||||
/// off, with no targets, and while pixels or the grid snap instead.
|
||||
pub(crate) fn lands_on_target(&self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> bool {
|
||||
let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return false };
|
||||
let Some((_, PointSnap { targets: Some((t, tol)), op, .. })) = &self.targets else { return false };
|
||||
cx.smart_guides && !cx.snaps_to_pixel(*op) && !cx.snap_to_grid && t.snap_hit(p, from, cx.tol(*tol)).2
|
||||
}
|
||||
|
||||
|
||||
@@ -1583,12 +1583,39 @@ impl Targets {
|
||||
/// the nearest target or ruler guide ("align"), whatever the box's angle. A handle with one way
|
||||
/// to go (a side, or a proportional corner) slides along it until one of them is on a target.
|
||||
pub fn snap_scale(&self, bx: &OrientedBox, handle: Handle, a: Affine, proportional: bool, from_center: bool, tol: f64) -> (Affine, Vec<Overlay>) {
|
||||
self.snap_scale_edges(bx, None, handle, a, proportional, from_center, tol)
|
||||
}
|
||||
|
||||
/// [`Self::snap_scale`], with the edges of `edges` landing on the targets in place of the
|
||||
/// edges of `bx`. `edges` is a box in `bx`'s frame, such as the selection's geometric bounds
|
||||
/// inside the visual bounds that Use Preview Bounds shows. With its `true`, the margins between
|
||||
/// the two boxes keep their size as `bx` scales, as `object.setBounds` keeps them; with `false`
|
||||
/// they scale with it, as `object.transform` scales them. The scale stays one of `bx`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn snap_scale_edges(
|
||||
&self,
|
||||
bx: &OrientedBox,
|
||||
edges: Option<(Rect, bool)>,
|
||||
handle: Handle,
|
||||
a: Affine,
|
||||
proportional: bool,
|
||||
from_center: bool,
|
||||
tol: f64,
|
||||
) -> (Affine, Vec<Overlay>) {
|
||||
type Hit = Option<(f64, Point)>;
|
||||
// Where a snap lands: in line with a target's x and/or y, or on an anchor or centre.
|
||||
type Snap = (Hit, Hit, Option<(Point, Kind)>);
|
||||
let r = bx.rect;
|
||||
let origin = if from_center { r.center() } else { handle.opposite().pos(r) };
|
||||
let (d0, [sx, _, _, sy, _, _]) = (handle.pos(r) - origin, a.as_coeffs());
|
||||
// Margins that keep their size are only measured on a box that does not flip.
|
||||
let edges = edges.filter(|(g, keep)| g.is_finite() && (!keep || (sx > 0.0 && sy > 0.0)));
|
||||
let lands = |h: Handle| scale_lands(r, edges, origin, h);
|
||||
let at = |nx: f64, ny: f64, h: Handle| {
|
||||
let (v, off) = lands(h);
|
||||
origin + Vec2::new(nx * v.x, ny * v.y) + off
|
||||
};
|
||||
let landed = |out: Affine| scale_landed(bx, edges, out);
|
||||
let (to_doc, to_local) = (bx.to_doc(), bx.to_doc().inverse());
|
||||
// A scale that collapses or flips the box is no snap.
|
||||
let valid = |n: f64, s: f64| n.is_finite() && n * s > 0.0;
|
||||
@@ -1610,7 +1637,8 @@ impl Targets {
|
||||
if handle.is_corner() && !proportional {
|
||||
// The corner goes anywhere: onto an anchor or centre, else it takes the target's x, its
|
||||
// y, or both.
|
||||
let p = to_doc * (a * handle.pos(r));
|
||||
let (v, off) = lands(handle);
|
||||
let p = to_doc * at(sx, sy, handle);
|
||||
let (hx, hy) = (nearest(p, true), nearest(p, false));
|
||||
let on = self.nearest_point(p, tol).map(|(q, k)| (Some((q.x, q)), Some((q.y, q)), Some((q, k))));
|
||||
for (tx, ty, at) in on.into_iter().chain([(hx, hy, None), (hx, None, None), (None, hy, None)]) {
|
||||
@@ -1618,7 +1646,7 @@ impl Targets {
|
||||
continue;
|
||||
}
|
||||
let q = to_local * Point::new(tx.map_or(p.x, |h| h.0), ty.map_or(p.y, |h| h.0));
|
||||
let (mut cx, mut cy) = ((q.x - origin.x) / d0.x, (q.y - origin.y) / d0.y);
|
||||
let (mut cx, mut cy) = ((q.x - off.x - origin.x) / v.x, (q.y - off.y - origin.y) / v.y);
|
||||
// Square to the page, the axis without a target stays exactly where it was.
|
||||
if bx.angle == 0.0 {
|
||||
(cx, cy) = (if tx.is_some() { cx } else { sx }, if ty.is_some() { cy } else { sy });
|
||||
@@ -1654,8 +1682,8 @@ impl Targets {
|
||||
}
|
||||
};
|
||||
for h in std::iter::once(handle).chain(ends.into_iter().flatten().copied()) {
|
||||
let v = h.pos(r) - origin;
|
||||
let base = to_doc * (origin + Vec2::new(c.0 * v.x, c.1 * v.y));
|
||||
let (v, off) = lands(h);
|
||||
let base = to_doc * (origin + Vec2::new(c.0 * v.x, c.1 * v.y) + off);
|
||||
let dir = (to_doc * Point::new(e.0 * v.x, e.1 * v.y)).to_vec2();
|
||||
let p = base + dir * s0;
|
||||
// An anchor or centre beside its way: it stops at the nearest point of the way.
|
||||
@@ -1683,7 +1711,7 @@ impl Targets {
|
||||
return (out, self.label(q, k.label()).into_iter().collect());
|
||||
}
|
||||
// The lines run from the target's own point across the resized box, on the page.
|
||||
let mut nr = (to_doc * out).transform_rect_bbox(r);
|
||||
let mut nr = landed(out);
|
||||
let mut ov = vec![];
|
||||
if let Some((x, from)) = hit_x {
|
||||
ov.extend(self.line(Point::new(x, from.y.min(nr.y0)), Point::new(x, from.y.max(nr.y1))));
|
||||
@@ -1692,7 +1720,7 @@ impl Targets {
|
||||
ov.extend(self.line(Point::new(from.x.min(nr.x0), y), Point::new(from.x.max(nr.x1), y)));
|
||||
}
|
||||
if hit_x.is_some() || hit_y.is_some() {
|
||||
ov.extend(self.label(to_doc * (out * handle.pos(r)), "align"));
|
||||
ov.extend(self.label(to_doc * at(nx, ny, handle), "align"));
|
||||
}
|
||||
if !self.boxes.is_empty() && !from_center {
|
||||
let aligned = [hit_x.is_some(), hit_y.is_some()];
|
||||
@@ -1705,8 +1733,7 @@ impl Targets {
|
||||
let (lo, hi) = span(&nr, is_x);
|
||||
let len = hi - lo;
|
||||
let new_len = if moves_min { hi - (lo + shift) } else { hi + shift - lo };
|
||||
if len > 1e-9 && new_len > 1e-9 {
|
||||
let f = new_len / len;
|
||||
if let Some(f) = spacing_factor(bx, edges, out, is_x, len, new_len) {
|
||||
let (ax, ay) = handle.axes();
|
||||
if is_x {
|
||||
nx *= f;
|
||||
@@ -1720,7 +1747,7 @@ impl Targets {
|
||||
}
|
||||
}
|
||||
out = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(nx, ny) * Affine::translate(-origin.to_vec2());
|
||||
nr = (to_doc * out).transform_rect_bbox(r);
|
||||
nr = landed(out);
|
||||
ov.extend(gaps.into_iter().flat_map(|g| self.gap_marks(g, is_x, tol)));
|
||||
}
|
||||
}
|
||||
@@ -1729,3 +1756,42 @@ impl Targets {
|
||||
(out, ov)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a point `h` of the box `r` scaled about `origin` goes when the box `edges` lines up in
|
||||
/// its place ([`Targets::snap_scale_edges`]): to `origin + scale·v + off` for the `(v, off)` given.
|
||||
fn scale_lands(r: Rect, edges: Option<(Rect, bool)>, origin: Point, h: Handle) -> (Vec2, Vec2) {
|
||||
match edges {
|
||||
Some((g, true)) => (h.pos(r) - origin, h.pos(g) - h.pos(r)),
|
||||
Some((g, false)) => (h.pos(g) - origin, Vec2::ZERO),
|
||||
None => (h.pos(r) - origin, Vec2::ZERO),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the scale `out` of `bx` is multiplied by along x (`is_x`) or y for the box whose edges
|
||||
/// line up to go from length `len` to `new_len` ([`Targets::snap_scale_edges`]). When the margins
|
||||
/// between `bx` and those edges keep their size, the scale multiplies `bx`'s own length, which
|
||||
/// changes by as much. None for a length that would collapse.
|
||||
fn spacing_factor(bx: &OrientedBox, edges: Option<(Rect, bool)>, out: Affine, is_x: bool, len: f64, new_len: f64) -> Option<f64> {
|
||||
let scaled = if matches!(edges, Some((_, true))) {
|
||||
let (lo, hi) = span(&(bx.to_doc() * out).transform_rect_bbox(bx.rect), is_x);
|
||||
hi - lo
|
||||
} else {
|
||||
len
|
||||
};
|
||||
let grown = scaled + new_len - len;
|
||||
(len > 1e-9 && new_len > 1e-9 && scaled > 1e-9 && grown > 1e-9).then(|| grown / scaled)
|
||||
}
|
||||
|
||||
/// The box whose edges line up ([`Targets::snap_scale_edges`]), on the page, after the scale `out`
|
||||
/// of `bx`.
|
||||
fn scale_landed(bx: &OrientedBox, edges: Option<(Rect, bool)>, out: Affine) -> Rect {
|
||||
let r = bx.rect;
|
||||
match edges {
|
||||
Some((g, true)) => {
|
||||
let n = out.transform_rect_bbox(r);
|
||||
bx.to_doc().transform_rect_bbox(Rect::new(n.x0 + g.x0 - r.x0, n.y0 + g.y0 - r.y0, n.x1 - (r.x1 - g.x1), n.y1 - (r.y1 - g.y1)))
|
||||
}
|
||||
Some((g, false)) => (bx.to_doc() * out).transform_rect_bbox(g),
|
||||
None => (bx.to_doc() * out).transform_rect_bbox(r),
|
||||
}
|
||||
}
|
||||
@@ -652,6 +652,7 @@ pub(crate) mod testutil {
|
||||
freeform_point: None,
|
||||
raster_sample: 1,
|
||||
preview_bounds: false,
|
||||
scale_strokes: false,
|
||||
glyph_bounds: false,
|
||||
preview_memo: None,
|
||||
unit: Unit::Points,
|
||||
|
||||
@@ -1985,7 +1985,7 @@ impl SelectionTool {
|
||||
// What the handle moves snaps as a dragged point does: to pixels or the
|
||||
// grid, else with Smart Guides to the other objects, else with Snap to
|
||||
// Point to their anchors; the ruler guides with Snap to Point.
|
||||
self.targets = Some(PointSnap::scaling(cx, || Targets::for_scale(cx)));
|
||||
self.targets = Some(PointSnap::scaling_selection(cx));
|
||||
self.last_backquote = false;
|
||||
self.last_box_pos = None;
|
||||
self.state = State::Scaling { handle, bx, areas };
|
||||
|
||||
@@ -1291,6 +1291,48 @@ fn a_move_lines_up_geometric_edges_with_use_preview_bounds_on() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, a scale handle drags the visual box, and Smart Guides line up the
|
||||
/// selection's geometric edge with the other art's geometric edge, as a move does.
|
||||
#[test]
|
||||
fn a_scale_lines_up_geometric_edges_with_use_preview_bounds_on() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Node};
|
||||
// An artboard whose edges and center are out of reach, and two rectangles stroked 20 pt.
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut add = |r: Rect| {
|
||||
let id = d.alloc_id();
|
||||
let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0);
|
||||
d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap();
|
||||
id
|
||||
};
|
||||
let a = add(Rect::new(100.0, 100.0, 200.0, 200.0));
|
||||
add(Rect::new(300.0, 100.0, 400.0, 200.0));
|
||||
let s = Selection { objects: vec![a], ..Default::default() };
|
||||
let p = paint();
|
||||
// The right edge of the box the right-middle handle leaves: the geometric edge with the option
|
||||
// off, the visual edge 10 pt outside it with the option on.
|
||||
let right = |preview: bool, from: f64, to: f64| {
|
||||
let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) };
|
||||
let mut t = SelectionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, from, 150.0));
|
||||
let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0));
|
||||
match a.last() {
|
||||
Some(Action::Preview(cmd, v)) if cmd == "object.setBounds" => 90.0 + v["width"].as_f64().unwrap(),
|
||||
Some(Action::Preview(_, v)) => v["matrix"][0].as_f64().unwrap() * 200.0 + v["matrix"][4].as_f64().unwrap(),
|
||||
_ => panic!("{a:?}"),
|
||||
}
|
||||
};
|
||||
let near = |got: f64, want: f64| (got - want).abs() < 1e-9;
|
||||
// Option off: the edge 1 pt short of the other rectangle's left edge (x = 300) lands on it.
|
||||
assert!(near(right(false, 200.0, 299.0), 300.0), "{}", right(false, 200.0, 299.0));
|
||||
assert!(near(right(false, 200.0, 291.0), 291.0), "{}", right(false, 200.0, 291.0));
|
||||
// Option on: the geometric edge 1 pt short lands on it, which leaves the visual edge at 310.
|
||||
assert!(near(right(true, 210.0, 309.0), 310.0), "{}", right(true, 210.0, 309.0));
|
||||
// The visual edge 1 pt past it does not pull the box there: the geometric edge is 9 pt short.
|
||||
assert!(near(right(true, 210.0, 301.0), 301.0), "{}", right(true, 210.0, 301.0));
|
||||
}
|
||||
|
||||
/// Smart Guides › Snap to Last Location: a move that comes within Snapping Tolerance of where it
|
||||
/// began goes back there, labeled "last location", a Shift move too; farther out, with the option
|
||||
/// or Smart Guides off, it stays where it is dragged, and an Alt copy snaps as it does with the
|
||||
|
||||
@@ -41,7 +41,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
use crate::bbox::{Handle, move_delta, rotate_for_drag, scale_for_drag};
|
||||
use crate::corners::{self, CornerDrag};
|
||||
use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square};
|
||||
use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, square};
|
||||
use crate::pie::{self, PieDrag};
|
||||
use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box};
|
||||
use crate::sidewidget::{self, SideDrag};
|
||||
@@ -363,7 +363,7 @@ impl ShapeTool {
|
||||
self.selection = if let Some((handle, bx)) = self.over_handle(cx, ev.pos) {
|
||||
let is_area = |id: &vectorcraft_doc::NodeId| cx.doc.node(*id).is_some_and(is_area_type);
|
||||
let areas = cx.selection.objects.iter().any(is_area);
|
||||
Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling(cx, || Targets::for_scale(cx))), last: None })
|
||||
Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling_selection(cx)), last: None })
|
||||
} else {
|
||||
match hit_center(cx, ev.pos, cx.point_tol()) {
|
||||
Some((_, hold)) => Some(SelectionDrag::Move { start: ev.pos, hold, began: false, snap: Box::new(MoveSnap::new(cx)) }),
|
||||
|
||||
@@ -14,7 +14,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
use super::{BLUE, polygon, rect_corners};
|
||||
use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag};
|
||||
use crate::guides::{PointSnap, Targets};
|
||||
use crate::guides::PointSnap;
|
||||
use crate::select::{handle_cursor, matrix_json, screen_handle, selection_box};
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
|
||||
@@ -273,7 +273,7 @@ impl Tool for FreeTransformTool {
|
||||
self.drag = None;
|
||||
let Some(bx) = selection_box(cx) else { return vec![] };
|
||||
if let Some(op) = self.classify(cx, &bx, p, ev.mods) {
|
||||
self.targets = op.handle().is_some().then(|| PointSnap::scaling(cx, || Targets::for_scale(cx)));
|
||||
self.targets = op.handle().is_some().then(|| PointSnap::scaling_selection(cx));
|
||||
self.drag = Some(Drag { op, bx, start: p, began: false });
|
||||
}
|
||||
vec![]
|
||||
@@ -454,6 +454,38 @@ mod tests {
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 213.0, 150.0)), vec![Action::Commit]);
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, a handle drags the visual box, and Smart Guides line up the
|
||||
/// selection's geometric edge with the other art's geometric edge.
|
||||
#[test]
|
||||
fn handle_drag_lines_up_geometric_edges_with_use_preview_bounds_on() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node};
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut add = |r: Rect| {
|
||||
let id = d.alloc_id();
|
||||
let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0);
|
||||
d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap();
|
||||
id
|
||||
};
|
||||
let a = add(Rect::new(100.0, 100.0, 200.0, 200.0));
|
||||
add(Rect::new(300.0, 100.0, 400.0, 200.0));
|
||||
let s = Selection { objects: vec![a], ..Default::default() };
|
||||
let p = paint();
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
// The right edge of the visual box (90 to 210) after a drag of its right-middle handle.
|
||||
let right = |to: f64| {
|
||||
let mut t = FreeTransformTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, 210.0, 150.0));
|
||||
let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0));
|
||||
let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") };
|
||||
v["matrix"][0].as_f64().unwrap() * 210.0 + v["matrix"][4].as_f64().unwrap()
|
||||
};
|
||||
// The geometric edge 1 pt short of x = 300 lands on it; the visual edge 1 pt past does not.
|
||||
assert!((right(309.0) - 310.0).abs() < 1e-9, "{}", right(309.0));
|
||||
assert!((right(301.0) - 301.0).abs() < 1e-9, "{}", right(301.0));
|
||||
}
|
||||
|
||||
/// In a view turned 90° the handles' cursors turn with the view.
|
||||
#[test]
|
||||
fn handle_cursors_turn_with_the_view() {
|
||||
|
||||
@@ -1111,6 +1111,41 @@ fn a_soft_gray_band_along_black_traces_as_black_and_white() {
|
||||
assert!((36..=42).contains(&blur_three), "bands 4 px wide blurred by 3 px: {blur_three} of 192 samples traced gray");
|
||||
}
|
||||
|
||||
/// A gray band 3 or 4 pixels wide along a black disc, with edges blurred by 0.6 pixels and a flat
|
||||
/// square of the same gray elsewhere, keeps at least 4 of every 5 samples gray when the gray is named
|
||||
/// 6 or 12 levels lighter or darker than the band's color, as it does when the gray is named exactly:
|
||||
/// the pixels of the square's color count as pixels of the gray.
|
||||
#[test]
|
||||
fn a_gray_band_along_black_keeps_its_gray_when_named_some_levels_off_its_flat_areas() {
|
||||
const INK: [u8; 3] = [4, 4, 3];
|
||||
for gray in [230u8, 200, 128] {
|
||||
for off in [-12i16, -6, 6, 12] {
|
||||
let Ok(named) = u8::try_from(i16::from(gray) + off) else { continue };
|
||||
for wide in [3u8, 4] {
|
||||
let img = render(120, 60, 0.6, |x, y| {
|
||||
let band = (40.0..43.0 + f64::from(wide)).contains(&x) && (20.0..36.0).contains(&y);
|
||||
let square = (80.0..110.0).contains(&x) && (15.0..45.0).contains(&y);
|
||||
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
|
||||
INK
|
||||
} else if band || square {
|
||||
[gray; 3]
|
||||
} else {
|
||||
WHITE
|
||||
})
|
||||
});
|
||||
let res = trace(&img, &black_gray_white([named; 3]));
|
||||
let kept = (0..wide)
|
||||
.flat_map(|c| (20..36).map(move |y| Point::new(43.5 + f64::from(c), f64::from(y) + 0.5)))
|
||||
.filter(|&at| top_color(&res, at) == Some([named; 3]))
|
||||
.count();
|
||||
let all = 16 * usize::from(wide);
|
||||
assert!(5 * kept >= 4 * all, "gray {gray} named {named}, {wide} px band: {kept} of {all} samples traced gray");
|
||||
assert_eq!(top_color(&res, Point::new(95.0, 30.0)), Some([named; 3]), "gray {gray} named {named}: the square");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A soft-edged gray spoke two or three pixels wide running straight out of a black disc, blurred
|
||||
/// by 1 or 1.5 pixels, loses 3 or 4 of its 16 samples nearest the disc and keeps the rest. Blurred
|
||||
/// by 2 pixels, a spoke three pixels wide loses 2 or 3 of them, and one two pixels wide traces as
|
||||
|
||||
+215
-17
@@ -27,12 +27,12 @@ const NEARBY: usize = 6;
|
||||
const WALK: usize = 5;
|
||||
/// A pixel whose neighbors are all this close to it (in 0..1 premultiplied RGBA) lies in a flat area.
|
||||
const FLAT: f64 = 1.5 / 255.0;
|
||||
/// How many joined pixels within [`PURE`] of one class are taken as art of that class, such as a
|
||||
/// one-pixel line. The edge pixels of a curve that come within `PURE` of a class join in far fewer.
|
||||
/// A straight edge whose anti-aliased pixels come within `PURE` of
|
||||
/// a class gives the same pixels as a line of that class, and keeps the class too. A one-pixel line
|
||||
/// between two classes that is shorter, falls between pixels or is blurred is read as a blend of
|
||||
/// those two classes.
|
||||
/// How many joined pixels within [`PURE`] of one class (or of the colors of its flat areas, for a
|
||||
/// class named some levels off them, [`area_colors`]) are taken as art of that class, such as a
|
||||
/// one-pixel line. The edge pixels of a curve that come within `PURE` of a class join in far fewer. A
|
||||
/// straight edge whose anti-aliased pixels come within `PURE` of a class gives the same pixels as a
|
||||
/// line of that class, and keeps the class too. A one-pixel line between two classes that is shorter,
|
||||
/// falls between pixels or is blurred is read as a blend of those two classes.
|
||||
const LINE: usize = 2 * NEARBY + 1;
|
||||
|
||||
struct Subset {
|
||||
@@ -209,24 +209,33 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
|
||||
// ([`flat_classes`], [`RowDistances::around`]); the other mix lies as near as the steps that
|
||||
// `across_edge` counts when those are fewer. For the best mix,
|
||||
// the classes held by flat areas between two classes count as well ([`between_classes`]). A
|
||||
// pixel within `PURE` of a class that is joined to at least [`LINE`] such pixels of that class
|
||||
// pixel of a class (within `PURE` of it, or of the colors of its flat areas when it is named some
|
||||
// levels off them, [`area_colors`]) that is joined to at least [`LINE`] such pixels of that class
|
||||
// (itself included) keeps it ([`pure_runs`]), as a one-pixel line of gray between black and white.
|
||||
let flat = flat_classes(pix, &stands_for, width, height);
|
||||
let between = between_classes(pix, &flat, &mixed, width, height);
|
||||
let runs = pure_runs(&pure, width, height);
|
||||
let colors = area_colors(pix, classes, &flat, &between);
|
||||
let of_class = (!colors.iter().all(FlatColors::is_empty)).then(|| {
|
||||
pure.iter()
|
||||
.zip(pix)
|
||||
.map(|(&q, px)| q.or_else(|| (0..k).find(|&c| colors.get(c).is_some_and(|cs| near_area_color(px, cs)))))
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
let of_class = of_class.as_deref().unwrap_or(&pure);
|
||||
let runs = pure_runs(of_class, width, height);
|
||||
let mut flat_rows = RowDistances::new(|j| [flat.get(j).copied().flatten(), None], width, height, k);
|
||||
let mut between_rows = (!between.is_empty()).then(|| RowDistances::new(|j| between.get(j).copied().unwrap_or([None; 2]), width, height, k));
|
||||
let mut dist = vec![NEARBY + 1; k];
|
||||
let mut kept = vec![NEARBY + 1; k];
|
||||
for (i, key) in tied {
|
||||
if pure.get(i).copied().flatten().is_some() && runs.get(i).is_some_and(|&r| r >= LINE) {
|
||||
if of_class.get(i).copied().flatten().is_some() && runs.get(i).is_some_and(|&r| r >= LINE) {
|
||||
continue;
|
||||
}
|
||||
let Some(mixes) = mixed.get(&key) else { continue };
|
||||
let edges: Vec<(&Weights, usize)> = mixes
|
||||
.tied
|
||||
.iter()
|
||||
.filter_map(|m| across_edge(pix, (&flat, &stands_for), (width, height), i, classes, &mixes.best, m).map(|r| (m, r)))
|
||||
.filter_map(|m| across_edge(pix, (&flat, &stands_for, &colors), (width, height), i, classes, &mixes.best, m).map(|r| (m, r)))
|
||||
.collect();
|
||||
if edges.is_empty() {
|
||||
continue;
|
||||
@@ -258,7 +267,10 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
|
||||
/// `other` gets past the class left out within [`WALK`] steps through the eight neighbors, and so
|
||||
/// does one that keeps going toward the other. When the first step of one path comes to a pixel
|
||||
/// that stands for its class of `other` (the edge on that side is sharp), the other path stops at
|
||||
/// a pixel within [`PURE`] of the class left out that it comes to before it gets past that class.
|
||||
/// a pixel of the class left out that it comes to before it gets past that class: a pixel within
|
||||
/// [`PURE`] of it, or, for a class named some levels off the colors of its flat areas
|
||||
/// ([`area_colors`]), within `PURE` of one of those colors, or within `PURE` of the class as named
|
||||
/// together with the pixel before it.
|
||||
/// For a class left out that lies beyond both classes of `other` on that line, the pixel has a
|
||||
/// neighbor on each side of that class, or a neighbor on each side of the pixel itself, none past
|
||||
/// the class of `other` nearer the class left out, and a chain of neighbors from the pixel to that
|
||||
@@ -279,7 +291,7 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
|
||||
/// path does not come to such a pixel, and when a class left out lies beyond both classes of `other`.
|
||||
fn across_edge(
|
||||
pix: &[Px],
|
||||
(flat, stands_for): (&[Option<usize>], &[Option<usize>]),
|
||||
(flat, stands_for, colors): (&[Option<usize>], &[Option<usize>], &AreaColors),
|
||||
(width, height): (usize, usize),
|
||||
i: usize,
|
||||
classes: &[[f64; 4]],
|
||||
@@ -356,11 +368,19 @@ fn across_edge(
|
||||
}
|
||||
false
|
||||
};
|
||||
// Whether pixel `j` comes within `PURE` of class `c`.
|
||||
let within = |j: usize, c: usize| {
|
||||
// Whether pixel `j` comes within `PURE` of class `c` as named.
|
||||
let named = |j: usize, c: usize| {
|
||||
let (Some(q), Some(cv)) = (pix.get(j), classes.get(c)) else { return false };
|
||||
(0..4).map(|k| (f64::from(q[k]) - cv[k]).powi(2)).sum::<f64>().sqrt() < PURE
|
||||
};
|
||||
// Whether pixel `j`, reached from pixel `prev`, is a pixel of class `c`: within `PURE` of it, or,
|
||||
// for a class named some levels off the colors of its flat areas ([`area_colors`]), within `PURE`
|
||||
// of one of those colors, or within `PURE` of the class as named with `prev` too (the class as
|
||||
// named lies across at least two pixels there, which the pixels of a black-to-white edge do not).
|
||||
let within = |prev: usize, j: usize, c: usize| match colors.get(c) {
|
||||
Some(cs) if !cs.is_empty() => pix.get(j).is_some_and(|q| near_area_color(q, cs)) || (named(prev, c) && named(j, c)),
|
||||
_ => named(j, c),
|
||||
};
|
||||
// The neighbor of pixel `j` near the line that lies farthest toward `a` (`toward` -1) or `b`
|
||||
// (`toward` 1), with its place.
|
||||
let next = |j: usize, toward: f64| around(j).filter_map(|n| at(n).map(|tn| (n, tn))).max_by(|p, q| (p.1 * toward).total_cmp(&(q.1 * toward)));
|
||||
@@ -368,19 +388,22 @@ fn across_edge(
|
||||
// pixel before (the first step is taken whatever `i` itself is). `None` when it does not get more
|
||||
// than `PURE` past `tc` in [`WALK`] steps; otherwise the steps to the first pixel past it that
|
||||
// stands for `class` (`stands_for`), or `NEARBY + 1`. With `halt`, the path also ends at a pixel
|
||||
// within `PURE` of that class that it comes to before it gets past `tc`.
|
||||
// of that class ([`within`]) that it comes to before it gets past `tc`.
|
||||
let walk = |toward: f64, tc: f64, class: usize, halt: Option<usize>| {
|
||||
let (mut cur, mut t) = (i, f64::NEG_INFINITY * toward);
|
||||
let mut past = false;
|
||||
for step in 1..=WALK {
|
||||
let prev = cur;
|
||||
match next(cur, toward) {
|
||||
Some((j, tj)) if (tj - t) * toward > 0.0 => (cur, t) = (j, tj),
|
||||
_ => break,
|
||||
}
|
||||
past = past || (t - tc) * toward * len > PURE;
|
||||
if !past && halt.is_some_and(|h| within(cur, h)) {
|
||||
// (A pixel of a flat area's color can lie past `tc` itself, when the class is named some
|
||||
// levels off that color: the path stops there when it was not past `tc` before.)
|
||||
if !past && halt.is_some_and(|h| within(prev, cur, h)) {
|
||||
break;
|
||||
}
|
||||
past = past || (t - tc) * toward * len > PURE;
|
||||
if past && stands_for.get(cur).copied().flatten() == Some(class) {
|
||||
return Some(step);
|
||||
}
|
||||
@@ -484,6 +507,88 @@ fn between_classes(pix: &[Px], flat: &[Option<usize>], mixed: &HashMap<[u32; 4],
|
||||
held
|
||||
}
|
||||
|
||||
/// For each class with a flat area [`PURE`] or more from it (as when it is named some levels off its
|
||||
/// color), the distinct colors of its flat areas: the flat areas that
|
||||
/// stand for it (`flat`) and those whose mix holds it most (`between`, [`between_classes`]). Empty for
|
||||
/// a class whose flat areas all come within `PURE` of it.
|
||||
fn area_colors(pix: &[Px], classes: &[[f64; 4]], flat: &[Option<usize>], between: &[[Option<usize>; 2]]) -> Vec<FlatColors> {
|
||||
let mut colors: Vec<FlatColors> = vec![FlatColors::default(); classes.len()];
|
||||
let mut off_named = vec![false; classes.len()];
|
||||
let mut kept: HashSet<(usize, [u32; 4])> = HashSet::new();
|
||||
for (i, px) in pix.iter().enumerate() {
|
||||
let Some(c) = flat.get(i).copied().flatten().or_else(|| between.get(i).and_then(|b| b[0])) else { continue };
|
||||
let (Some(cv), Some(seen), Some(off)) = (classes.get(c), colors.get_mut(c), off_named.get_mut(c)) else { continue };
|
||||
*off = *off || (0..4).map(|j| (f64::from(px[j]) - cv[j]).powi(2)).sum::<f64>().sqrt() >= PURE;
|
||||
if kept.insert((c, px.map(f32::to_bits))) {
|
||||
seen.push(*px);
|
||||
}
|
||||
}
|
||||
for (seen, off) in colors.iter_mut().zip(off_named) {
|
||||
if !off {
|
||||
seen.clear();
|
||||
}
|
||||
}
|
||||
colors
|
||||
}
|
||||
|
||||
/// Whether `px` comes within [`PURE`] of one of `colors`.
|
||||
fn near_area_color(px: &Px, colors: &FlatColors) -> bool {
|
||||
colors.near(px)
|
||||
}
|
||||
|
||||
/// The colors of one class's flat areas, kept in cells `2 * PURE` wide on each channel, so a color
|
||||
/// within [`PURE`] of a pixel lies in the pixel's cell or, on each channel, the next cell on the side
|
||||
/// the pixel lies nearer: 16 cells in all.
|
||||
#[derive(Clone, Default)]
|
||||
struct FlatColors {
|
||||
cells: HashMap<[i32; 4], Vec<Px>>,
|
||||
}
|
||||
|
||||
impl FlatColors {
|
||||
fn cell(px: &Px) -> [i32; 4] {
|
||||
px.map(|v| (f64::from(v) / (2.0 * PURE)).floor() as i32)
|
||||
}
|
||||
|
||||
fn push(&mut self, px: Px) {
|
||||
self.cells.entry(Self::cell(&px)).or_default().push(px);
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.cells.is_empty()
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.cells.clear();
|
||||
}
|
||||
|
||||
/// Whether one of the colors lies within [`PURE`] of `px`.
|
||||
fn near(&self, px: &Px) -> bool {
|
||||
if self.cells.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let at = Self::cell(px);
|
||||
// On each channel, -1 or +1: the neighboring cell on the side of the cell's middle the pixel lies.
|
||||
let side = [0, 1, 2, 3].map(|j| {
|
||||
let pos = f64::from(px[j]) / (2.0 * PURE) - f64::from(at[j]);
|
||||
if pos < 0.5 { -1 } else { 1 }
|
||||
});
|
||||
(0..16usize).any(|n| {
|
||||
let mut key = at;
|
||||
for (j, k) in key.iter_mut().enumerate() {
|
||||
if (n >> j) & 1 == 1 {
|
||||
*k = k.saturating_add(side[j]);
|
||||
}
|
||||
}
|
||||
self.cells.get(&key).is_some_and(|qs| qs.iter().any(|q| distance(px, q) < PURE))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// How far apart two pixels are (in 0..1 premultiplied RGBA).
|
||||
fn distance(a: &Px, b: &Px) -> f64 {
|
||||
(0..4).map(|j| (f64::from(a[j]) - f64::from(b[j])).powi(2)).sum::<f64>().sqrt()
|
||||
}
|
||||
|
||||
/// For each of `k` classes, how far along each row the nearest pixel holding that class (`at`, the
|
||||
/// classes pixel `j` holds) lies from each pixel, up to `NEARBY + 1` when none lies within
|
||||
/// [`NEARBY`]. A row is worked out when it is first asked for, so a few pixels cost a few rows.
|
||||
@@ -612,6 +717,9 @@ fn in_flat_area(pix: &[Px], width: usize, height: usize, x: usize, y: usize) ->
|
||||
/// Each class's weight in a pixel's mix.
|
||||
type Weights = Vec<(usize, f32)>;
|
||||
|
||||
/// For each class, the colors of its flat areas that lie [`PURE`] or more from it ([`area_colors`]).
|
||||
type AreaColors = [FlatColors];
|
||||
|
||||
/// A mix tried for a pixel: its squared error with its penalty, the penalty, and its classes with
|
||||
/// their weights (the first `n`).
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -803,6 +911,59 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_as_light_as_a_class_keeps_it_beside_a_flat_area_some_levels_off_it() {
|
||||
// As above, with a flat area of the gray some levels darker than it is named to the right of
|
||||
// the white: a column of `LINE` rows at the named value is still gray art.
|
||||
let classes = vec![[0.9, 0.9, 0.9, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]];
|
||||
let mut pix = Vec::new();
|
||||
for _ in 0..LINE {
|
||||
pix.extend([[0.0f32, 0.0, 0.0, 1.0]; 5]);
|
||||
pix.push([0.9, 0.9, 0.9, 1.0]);
|
||||
pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 5]);
|
||||
pix.extend([[0.87f32, 0.87, 0.87, 1.0]; 5]);
|
||||
}
|
||||
let (pl, _, _) = unmix(&pix, 16, LINE, &classes);
|
||||
for y in 0..LINE {
|
||||
assert_eq!(pl[0][y * 16 + 5], 1.0, "gray in row {y}");
|
||||
assert!(pl[0][y * 16 + 13] > 0.9, "the flat area in row {y}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_strip_as_light_as_a_class_traces_the_same_beside_a_flat_area_some_levels_off_it() {
|
||||
// Three rows of flat black, a strip 1 to 3 pixels wide at the gray's value and flat white: with
|
||||
// a flat area of the gray some levels darker than it is named to the right of the white, the
|
||||
// strip's pixels take the same mixes as without it (a strip 2 or 3 pixels wide stays gray).
|
||||
let classes = vec![[0.9, 0.9, 0.9, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]];
|
||||
for wide in [1usize, 2, 3] {
|
||||
let rows = |area: bool| {
|
||||
let mut pix = Vec::new();
|
||||
for _ in 0..3 {
|
||||
pix.extend([[0.0f32, 0.0, 0.0, 1.0]; 5]);
|
||||
pix.extend(vec![[0.9f32, 0.9, 0.9, 1.0]; wide]);
|
||||
pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 5]);
|
||||
if area {
|
||||
pix.extend([[0.87f32, 0.87, 0.87, 1.0]; 5]);
|
||||
}
|
||||
}
|
||||
pix
|
||||
};
|
||||
let w = 10 + wide;
|
||||
let (alone, _, _) = unmix(&rows(false), w, 3, &classes);
|
||||
let (beside, _, _) = unmix(&rows(true), w + 5, 3, &classes);
|
||||
for y in 0..3 {
|
||||
for x in 0..w {
|
||||
let mix = |pl: &[Vec<f32>], w: usize| pl.iter().take(3).map(|p| p[y * w + x]).collect::<Vec<_>>();
|
||||
assert_eq!(mix(&beside, w + 5), mix(&alone, w), "{wide} px strip: the mix at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
if wide > 1 {
|
||||
assert_eq!(beside[0][w + 5 + 5], 1.0, "{wide} px strip: gray");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edge_pixel_takes_no_class_beyond_both_classes_beside_it() {
|
||||
// A pale ground, a gray and a charcoal on one line: a row of flat gray, one edge pixel halfway
|
||||
@@ -906,6 +1067,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_flat_area_color_keeps_its_whole_neighborhood() {
|
||||
// A class named 228, 228, 227 and flat areas of 222 then 223: a pixel of 225 lies within
|
||||
// `PURE` of 223 but not of 222, so it counts as art of the class only when 223 is kept.
|
||||
let level = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0];
|
||||
let classes = vec![[228.0 / 255.0, 228.0 / 255.0, 227.0 / 255.0, 1.0], [0.0, 0.0, 0.0, 1.0]];
|
||||
let pix = vec![level(222.0), level(222.0), level(223.0), level(223.0)];
|
||||
let flat = vec![Some(0); pix.len()];
|
||||
let between = vec![[None; 2]; pix.len()];
|
||||
let colors = area_colors(&pix, &classes, &flat, &between);
|
||||
assert_eq!(colors[0].cells.values().map(Vec::len).sum::<usize>(), 2);
|
||||
assert!(near_area_color(&level(225.0), &colors[0]));
|
||||
let mut only_222 = FlatColors::default();
|
||||
only_222.push(level(222.0));
|
||||
assert!(!near_area_color(&level(225.0), &only_222));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_colors_find_what_a_scan_of_every_color_finds() {
|
||||
let at = |r: f32, g: f32, b: f32, a: f32| [r / 255.0, g / 255.0, b / 255.0, a / 255.0];
|
||||
let stored: Vec<Px> = (0..40u8).map(|n| at(f32::from(n) * 6.3, 255.0 - f32::from(n) * 2.9, f32::from(n % 7) * 3.1, 255.0)).collect();
|
||||
let mut index = FlatColors::default();
|
||||
for &q in &stored {
|
||||
index.push(q);
|
||||
}
|
||||
assert!(stored.iter().all(|q| index.near(q)));
|
||||
for r in (0..=255u8).step_by(3) {
|
||||
for g in [0.0f32, 100.0, 140.0, 200.0, 254.0] {
|
||||
for b in [0.0f32, 2.0, 5.0, 9.0, 18.0] {
|
||||
let px = at(f32::from(r), g, b, 255.0);
|
||||
let scan = stored.iter().any(|q| distance(&px, q) < PURE);
|
||||
assert_eq!(index.near(&px), scan, "{px:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weights_sum_to_one() {
|
||||
let pix = vec![[0.2, 0.1, 0.5, 0.8], [0.9, 0.0, 0.05, 0.95]];
|
||||
|
||||
@@ -166,6 +166,8 @@ impl VectorcraftApp {
|
||||
}
|
||||
let mut params = params;
|
||||
self.add_active_artboard(id, &mut params);
|
||||
// A script's `app.doScript` plays the Actions panel's actions.
|
||||
panels::actions::add_script_actions(self, id, &mut params);
|
||||
// Edit Symbol from the Symbols panel in a document without artboards centers the symbol's
|
||||
// art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit
|
||||
// steps too.
|
||||
@@ -272,8 +274,10 @@ impl VectorcraftApp {
|
||||
}
|
||||
// A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link.
|
||||
panels::color_guide::after_command(self, id, ¶ms, v, spot_base);
|
||||
// A renamed color group stays selected in the Swatches panel.
|
||||
// A renamed color group stays selected in the Swatches panel, and the rows dragged
|
||||
// from its list are checked against what the command left.
|
||||
panels::swatches::after_command(self, id, ¶ms, v);
|
||||
panels::swatches::follow_drag(self);
|
||||
if id == "file.new" {
|
||||
self.status("");
|
||||
// New Document's Pixel preview mode (Overprint Preview is the engine's).
|
||||
|
||||
@@ -299,6 +299,7 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
|
||||
crate::dialogs::simplify_slider::show(app, ui, &space.view);
|
||||
}
|
||||
guides::show(app, ui, space, win, kind);
|
||||
widgets::show_hollow_corners(app, ui, space, kind);
|
||||
// The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this
|
||||
// frame's pointer event, from the document as the event leaves it.
|
||||
let marks = PaintSlot::reserve(ui.painter());
|
||||
|
||||
@@ -233,7 +233,14 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() {
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let document = app.session.active().unwrap().uid;
|
||||
let swatch = |name: &str, paint: Paint| {
|
||||
let rows = SwatchRows { document, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false };
|
||||
let rows = SwatchRows {
|
||||
document,
|
||||
grabbed: name.into(),
|
||||
names: vec![name.into()],
|
||||
groups: false,
|
||||
unlinked_process_color: false,
|
||||
held: Default::default(),
|
||||
};
|
||||
Payload::Panel(PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None })
|
||||
};
|
||||
let pattern = swatch("Checks", vectorcraft_doc::pattern::pattern_paint("Checks"));
|
||||
@@ -329,7 +336,14 @@ fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() {
|
||||
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
|
||||
let source = app.session.active().unwrap();
|
||||
let paint = source.doc.swatch(name).unwrap().paint.clone();
|
||||
let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true };
|
||||
let rows = SwatchRows {
|
||||
document: source.uid,
|
||||
grabbed: name.into(),
|
||||
names: vec![name.into()],
|
||||
groups: false,
|
||||
unlinked_process_color: true,
|
||||
held: Default::default(),
|
||||
};
|
||||
let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None };
|
||||
|
||||
let local_target = add_target(&mut app);
|
||||
|
||||
@@ -119,7 +119,7 @@ fn corner_target(doc: &Document, id: NodeId, indices: &[usize]) -> Option<Corner
|
||||
(!corners.is_empty()).then(|| CornerTarget::new(id.0, corners, individual))
|
||||
}
|
||||
|
||||
/// The Live Corners widgets `tool` shows at `zoom`: Selection and the shape tools on a live rectangle or polygon
|
||||
/// The tool's Live Corners widgets `tool` shows at `zoom`: Selection and the shape tools on a live rectangle or polygon
|
||||
/// while Show Shape Widgets is on, Direct Selection on any path, within the Hide Corner Widget angle. `tool` is the
|
||||
/// tool whose widgets the canvas shows ([`super::shown_tool`]).
|
||||
fn shown_corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option<vectorcraft_tools::corners::CornerWidgets> {
|
||||
@@ -132,10 +132,10 @@ fn shown_corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option<vectorcr
|
||||
vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, zoom, direct, on, app.session.prefs.hide_corner_widget_above)
|
||||
}
|
||||
|
||||
/// The Live Corners widgets on show, one group per layer colour so each draws in its object's colour: Selection
|
||||
/// and the shape tools on a live rectangle or polygon while Show Shape Widgets is on, Direct Selection on any
|
||||
/// path. Only the corners the tool hit-tests are listed, those within the Hide Corner Widget angle. `tool` is the tool
|
||||
/// whose widgets the canvas shows ([`super::shown_tool`]).
|
||||
/// The Live Corners widgets of the picked corners on show, one group per layer color so each draws in its
|
||||
/// object's color, with a dot at its center. Every corner on show is picked, except with Direct Selection while
|
||||
/// some corners are picked: the widgets of the others are [`hollow_corners`]. `tool` is the tool whose widgets the
|
||||
/// canvas shows ([`super::shown_tool`]).
|
||||
// PLAN: the decision's `(.., f64)` is dropped: the corners listed are already those within the angle, so no
|
||||
// angle is left to hand on.
|
||||
pub(super) fn corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option<Vec<(DataColor, Vec<CornerTarget>)>> {
|
||||
@@ -143,7 +143,10 @@ pub(super) fn corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option<Vec
|
||||
let st = app.session.active()?;
|
||||
// `visible_on` and `corners` list the same corners in the same order: path after path.
|
||||
let mut per_path: Vec<(NodeId, Vec<usize>)> = vec![];
|
||||
for ((id, _), index) in shown.visible_on().zip(shown.corners()) {
|
||||
for ((id, _, picked), index) in shown.visible_on().zip(shown.corners()) {
|
||||
if !picked {
|
||||
continue;
|
||||
}
|
||||
match per_path.last_mut() {
|
||||
Some((last, indices)) if *last == id => indices.push(index),
|
||||
_ => per_path.push((id, vec![index])),
|
||||
@@ -181,6 +184,78 @@ pub(super) fn corner_hover(
|
||||
Some((data_color(st.doc.layer_color(id)), cut))
|
||||
}
|
||||
|
||||
/// The Live Corners widgets of the corners on show that are not picked: with Direct Selection while some corners
|
||||
/// are picked, every other corner's widget shows too, so a click or a Shift-click on it picks its corner. Each is
|
||||
/// listed with its place and its object's layer color.
|
||||
pub(super) fn hollow_corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Vec<(Point, DataColor)> {
|
||||
let (Some(shown), Some(st)) = (shown_corners(app, tool, zoom), app.session.active()) else { return vec![] };
|
||||
shown.visible_on().filter(|&(_, _, picked)| !picked).map(|(id, at, _)| (doc_point(at), data_color(st.doc.layer_color(id)))).collect()
|
||||
}
|
||||
|
||||
/// The widgets of [`hollow_corners`]: each a disc in the handle fill ringed in its layer color, the look of the
|
||||
/// picked corners' widgets without their dot. Display only: the tool takes the presses.
|
||||
#[derive(craft::ui::contract::Component, craft::ui::contract::Props)]
|
||||
#[component(canvas_control)]
|
||||
pub struct HollowCorners {
|
||||
#[common]
|
||||
common: Common,
|
||||
widgets: Vec<(Point, DataColor)>,
|
||||
}
|
||||
|
||||
impl HollowCorners {
|
||||
fn new(widgets: Vec<(Point, DataColor)>) -> Self {
|
||||
HollowCorners { common: Common::new(), widgets }.label("Live Corners not picked")
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of the hollow corner widgets.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct HollowCornersStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
/// A widget's diameter: `size.handle.md`, as the picked corners' widgets.
|
||||
widget: f32,
|
||||
/// A widget's inside: `overlay.handle_fill`.
|
||||
fill: StyleColor,
|
||||
}
|
||||
|
||||
impl Component for HollowCorners {
|
||||
const ROLE: Role = Role::GRAPHICS_OBJECT;
|
||||
const INPUT: Input = Input::Display;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = HollowCornersStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: HollowCornersStyleKey) -> HollowCornersStyle {
|
||||
HollowCornersStyle { metrics: Metrics::new(), widget: cx.tokens.size.handle.md, fill: cx.color(cx.tokens.color.overlay.handle_fill) }
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> egui::Vec2 {
|
||||
egui::Vec2::ZERO
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let Some(space) = canvas_space(&cx.env) else { return };
|
||||
let draw = ui.draw();
|
||||
for &(at, color) in &self.widgets {
|
||||
let ring = PaintShape::Circle(space.view.to_screen(at), cx.style.widget / 2.0);
|
||||
draw.fill(&ring, cx.style.fill);
|
||||
draw.stroke(&ring, StrokeWidth::Medium, StrokeColor::Data(color));
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
access.description("Live Corners not picked");
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn corner_kind(kind: DocCornerKind) -> CornerKind {
|
||||
match kind {
|
||||
DocCornerKind::Round => CornerKind::Round,
|
||||
@@ -469,6 +544,19 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &craft::u
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the widgets of [`hollow_corners`] over the live document, with View › Show Edges on. The canvas shows
|
||||
/// them before the selection's anchors and handles, so the anchors and handles draw over them. Nothing here is
|
||||
/// shown while a revolve is edited.
|
||||
pub(super) fn show_hollow_corners(app: &VectorcraftApp, ui: &mut egui::Ui, space: &craft::ui::canvas::CanvasSpace, kind: BodyKind) {
|
||||
if kind != BodyKind::Live || super::revolve_editing(app) || !app.ui.view.edges {
|
||||
return;
|
||||
}
|
||||
let widgets = hollow_corners(app, super::shown_tool(app, ui.ctx()), space.view.zoom);
|
||||
if !widgets.is_empty() {
|
||||
HollowCorners::new(widgets).show_at(ui, ui.max_rect());
|
||||
}
|
||||
}
|
||||
|
||||
/// The box and its eight handles, drawn in the layer colour and answering nothing.
|
||||
fn show_box(ui: &mut egui::Ui, rect: egui::Rect, b: &ShownBox) {
|
||||
let state = BoxState::new(b.obox.corners().map(doc_point), doc_point(b.obox.center()));
|
||||
|
||||
@@ -309,6 +309,22 @@ fn a_star_shows_corner_widgets_with_direct_selection() {
|
||||
assert_eq!(corner_count(&app), 0);
|
||||
}
|
||||
|
||||
/// #1232: with two of a star's corners picked, Direct Selection still shows all ten widgets: the two picked ones
|
||||
/// with their dot, the other eight hollow in the layer color. With the star selected whole, every widget is picked.
|
||||
#[test]
|
||||
fn direct_selection_shows_the_widgets_of_corners_not_picked_hollow() {
|
||||
let mut app = new_app(&[]);
|
||||
let id = make(&mut app, "shape.star", json!({"cx": 200, "cy": 150, "radius1": 80, "radius2": 40}));
|
||||
app.session.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap();
|
||||
app.select_tool("directSelection");
|
||||
let zoom = app.view_info().zoom;
|
||||
let hollow = hollow_corners(&app, app.session.tool_id(), zoom);
|
||||
assert_eq!((corner_count(&app), hollow.len()), (2, 8));
|
||||
assert!(hollow.iter().all(|&(_, color)| color == layer(&app, id)));
|
||||
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
assert_eq!((corner_count(&app), hollow_corners(&app, app.session.tool_id(), zoom).len()), (10, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_type_widget_shows_which_kind_the_type_is() {
|
||||
let mut app = new_app(&[]);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Corners: double-clicking a Live Corners widget (or `ui.corners`) sets the corner kind and
|
||||
//! radius of a path's corners: those whose widgets show (the Direct-Selected ones, else every
|
||||
//! corner). OK runs `object.setLiveShape` for them, one undo step.
|
||||
//! radius of a path's corners: the picked ones (the Direct-Selected ones, else every corner), or
|
||||
//! the double-clicked widget's corner alone when Direct Selection did not pick it. OK runs
|
||||
//! `object.setLiveShape` for them, one undo step.
|
||||
//!
|
||||
//! Fields: `id`, `corners` (anchor indices of the path with its corners uncut: a rectangle's 0–3
|
||||
//! from the top-left clockwise), `kind` ("round", "invertedRound" or "chamfer"), `radii`
|
||||
@@ -253,12 +254,12 @@ mod tests {
|
||||
#[test]
|
||||
fn double_clicking_a_direct_selected_corner_edits_it_alone() {
|
||||
let (mut app, id) = app();
|
||||
// Direct Selection picks the bottom-right anchor: only its widget shows.
|
||||
// Direct Selection picks the bottom-right anchor: its widget alone is picked.
|
||||
app.run("select.anchors", json!({"id": id, "anchors": [[0, 2]], "mode": "set"})).unwrap();
|
||||
app.select_tool("directSelection");
|
||||
let view = app.view_info();
|
||||
let st = app.session.active().unwrap();
|
||||
let at: Vec<_> = CornerWidgets::of(&st.doc, &st.selection, view.zoom, true).unwrap().visible().collect();
|
||||
let at: Vec<_> = CornerWidgets::of(&st.doc, &st.selection, view.zoom, true).unwrap().visible_on().filter(|w| w.2).map(|w| w.1).collect();
|
||||
assert_eq!(at.len(), 1);
|
||||
crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::DoubleClick, at[0].x, at[0].y), view);
|
||||
assert!(is_open(&app), "Corners opened");
|
||||
|
||||
@@ -194,11 +194,12 @@ impl Rows<'_> {
|
||||
self.range(key, label, range, 1, UnitKind::Percent)
|
||||
}
|
||||
|
||||
/// A length in points, shown in the general unit.
|
||||
/// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says.
|
||||
fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param {
|
||||
// Stored in points; a pixel is a point, as the rulers count it.
|
||||
let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0);
|
||||
self.range(key, label, range, 1, UnitKind::Pixels).length(crate::fields::bare_points(lengths, self.bare_points))
|
||||
let shown = super::three_d_classic::length_unit(self.unit);
|
||||
self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points))
|
||||
}
|
||||
|
||||
fn flag(&self, key: &str, label: &'static str) -> Param {
|
||||
|
||||
@@ -494,6 +494,41 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() {
|
||||
assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent)));
|
||||
}
|
||||
|
||||
/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their
|
||||
/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit.
|
||||
#[test]
|
||||
fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
|
||||
use craft::ui::patterns::form_dialogs::DialogFields;
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use vectorcraft_doc::Unit;
|
||||
let app = VectorcraftApp::new(Session::new(), crate::Services::default());
|
||||
let unit = |general: Unit, effect: &str, page: &str, key: &str| {
|
||||
let mut data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new());
|
||||
data.unit = general;
|
||||
let mut fields = DialogFields::new();
|
||||
fields.set("__page", FieldValue::Text(page.into()));
|
||||
super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit)
|
||||
};
|
||||
let mut checked = 0;
|
||||
for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] {
|
||||
for key in ["depth", "bevelWidth", "bevelHeight"] {
|
||||
assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}");
|
||||
checked += 1;
|
||||
}
|
||||
let others = [
|
||||
(REVOLVE, "rotation", "offset"),
|
||||
(CLASSIC_EXTRUDE, "object", "depth"),
|
||||
(CLASSIC_EXTRUDE, "object", "bevelHeight"),
|
||||
(CLASSIC_REVOLVE, "object", "offset"),
|
||||
];
|
||||
for (effect, page, key) in others {
|
||||
assert_eq!(unit(general, effect, page, key), Some(Some(shown)), "{effect} {key} in {general:?}");
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, 21);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_all_keeps_map_art_and_its_options() {
|
||||
let mut h = drawn(SQUARE, CLASSIC_EXTRUDE);
|
||||
|
||||
@@ -50,9 +50,13 @@ const MAP_SYMBOL: &str = "mapSymbol";
|
||||
/// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters.
|
||||
pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]];
|
||||
|
||||
/// The unit of the general-unit length rows.
|
||||
fn length_unit(unit: Unit) -> UnitKind {
|
||||
crate::canvas::rulers::unit_kind(unit)
|
||||
/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when
|
||||
/// that counts the same number (points, or pixels at 72 per inch), and points otherwise.
|
||||
pub(super) fn length_unit(unit: Unit) -> UnitKind {
|
||||
match crate::canvas::rulers::unit_kind(unit) {
|
||||
UnitKind::Pixels => UnitKind::Pixels,
|
||||
_ => UnitKind::Points,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the rows show: the 3D and Materials panel marks its fields with `__panel`.
|
||||
|
||||
@@ -164,8 +164,10 @@ impl StackDialog for Manager {
|
||||
// PLAN: the rows components take no `enabled` prop; the scope's `Ui` is disabled for them.
|
||||
ui.scope(|ui| {
|
||||
ui.disable();
|
||||
rows::main_rows(ui, &mut params, data, RowsHost::Dialog);
|
||||
rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None);
|
||||
rows::settings_group(ui, |ui| {
|
||||
rows::main_rows(ui, &mut params, data, RowsHost::Dialog);
|
||||
rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None);
|
||||
});
|
||||
});
|
||||
if builtin {
|
||||
Text::new(tl!("Built-in presets don't change: New makes a copy you can edit."))
|
||||
@@ -472,9 +474,11 @@ fn build(data: Arc<RowsData>) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamD
|
||||
_ => json!({}),
|
||||
};
|
||||
let shown = ui.scope(|ui| {
|
||||
let main = rows::main_rows(ui, &mut params, &data, RowsHost::Dialog);
|
||||
let advanced = rows::advanced_rows(ui, &mut params, &data, RowsHost::Dialog, None);
|
||||
main.changed || advanced.changed
|
||||
rows::settings_group(ui, |ui| {
|
||||
let main = rows::main_rows(ui, &mut params, &data, RowsHost::Dialog);
|
||||
let advanced = rows::advanced_rows(ui, &mut params, &data, RowsHost::Dialog, None);
|
||||
main.changed || advanced.changed
|
||||
})
|
||||
});
|
||||
if shown.inner {
|
||||
fields.set("params", FieldValue::Json(params));
|
||||
|
||||
@@ -1752,6 +1752,7 @@ font-technology Variable Променливи
|
||||
Fail Не покрива
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимален контраст по WCAG 2.2: нормален текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), голям текст AA 3:1 и AAA 4.5:1, графики и контроли AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Фонът се отчита в центъра на селекцията.
|
||||
The closest color that passes {level}: click to apply it. Най-близкият цвят, който покрива {level}: щракнете, за да го приложите.
|
||||
Graphics Processor Графичен процесор
|
||||
Graphics: {adapter} Графика: {adapter}
|
||||
Gravity Гравитация
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2121,6 +2121,7 @@ digits Malayalam Malajalam
|
||||
Fail Ne prolazi
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalni kontrast po WCAG 2.2: normalni tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), veliki tekst AA 3:1 i AAA 4.5:1, grafike i kontrole AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Pozadina se očitava u sredini odabira.
|
||||
The closest color that passes {level}: click to apply it. Najbliža boja koja zadovoljava {level}: kliknite da je primijenite.
|
||||
Local Libraries Lokalne biblioteke
|
||||
Add Content Dodaj sadržaj
|
||||
Click to apply to the selected type Kliknite da primijenite na odabrani tekst
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2155,6 +2155,7 @@ digits Malayalam Malaiàlam
|
||||
Fail No supera
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrast mínim de les WCAG 2.2: text normal AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), text gran AA 3:1 i AAA 4.5:1, gràfics i controls AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. El fons es llegeix al centre de la selecció.
|
||||
The closest color that passes {level}: click to apply it. El color més proper que compleix {level}: feu clic per aplicar-lo.
|
||||
Graphics Processor Processador gràfic
|
||||
Graphics: {adapter} Gràfics: {adapter}
|
||||
Gravity Gravetat
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2193,6 +2193,7 @@ digits Malayalam Malajálamské
|
||||
Fail Nevyhovuje
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimální kontrast podle WCAG 2.2: normální text AA 4.5:1 (1.4.3) a AAA 7:1 (1.4.6), velký text AA 3:1 a AAA 4.5:1, grafika a ovládací prvky AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Pozadí se čte uprostřed výběru.
|
||||
The closest color that passes {level}: click to apply it. Nejbližší barva, která splňuje {level}: kliknutím ji použijete.
|
||||
Local Libraries Místní knihovny
|
||||
Add Content Přidat obsah
|
||||
Click to apply to the selected type Kliknutím použijete na vybraný text
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4860,6 +4860,7 @@ digits Malayalam Malayalam
|
||||
Fail Ikke bestået
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindstekontrast efter WCAG 2.2: normal tekst AA 4.5:1 (1.4.3) og AAA 7:1 (1.4.6), stor tekst AA 3:1 og AAA 4.5:1, grafik og kontrolelementer AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Baggrunden aflæses i midten af markeringen.
|
||||
The closest color that passes {level}: click to apply it. Den nærmeste farve, der består {level}: klik for at anvende den.
|
||||
Local Libraries Lokale biblioteker
|
||||
Add Content Tilføj indhold
|
||||
Click to apply to the selected type Klik for at anvende på den markerede tekst
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1679,6 +1679,7 @@ file-filter Templates Vorlagen
|
||||
Fail Nicht bestanden
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindestkontrast nach WCAG 2.2: normaler Text AA 4.5:1 (1.4.3) und AAA 7:1 (1.4.6), großer Text AA 3:1 und AAA 4.5:1, Grafiken und Bedienelemente AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Der Hintergrund wird in der Mitte der Auswahl gemessen.
|
||||
The closest color that passes {level}: click to apply it. Die nächste Farbe, die {level} besteht: Klicken Sie, um sie anzuwenden.
|
||||
Graphics Processor Grafikprozessor
|
||||
Graphics: {adapter} Grafik: {adapter}
|
||||
Gravity Schwerkraft
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1598,6 +1598,7 @@ font-technology Variable Μεταβλητές
|
||||
Fail Αποτυχία
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Ελάχιστη αντίθεση κατά WCAG 2.2: κανονικό κείμενο AA 4.5:1 (1.4.3) και AAA 7:1 (1.4.6), μεγάλο κείμενο AA 3:1 και AAA 4.5:1, γραφικά και στοιχεία ελέγχου AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Το φόντο διαβάζεται στο κέντρο της επιλογής.
|
||||
The closest color that passes {level}: click to apply it. Το πλησιέστερο χρώμα που περνά το {level}: κάντε κλικ για να το εφαρμόσετε.
|
||||
Graphics Processor Επεξεργαστής γραφικών
|
||||
Graphics: {adapter} Γραφικά: {adapter}
|
||||
Gravity Βαρύτητα
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1688,6 +1688,7 @@ font-technology Variable Variables
|
||||
Fail No cumple
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo de WCAG 2.2: texto normal AA 4.5:1 (1.4.3) y AAA 7:1 (1.4.6), texto grande AA 3:1 y AAA 4.5:1, gráficos y controles AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. El fondo se lee en el centro de la selección.
|
||||
The closest color that passes {level}: click to apply it. El color más cercano que cumple {level}: haga clic para aplicarlo.
|
||||
Graphics Processor Procesador gráfico
|
||||
Graphics: {adapter} Gráficos: {adapter}
|
||||
Gravity Gravedad
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2152,6 +2152,7 @@ digits Malayalam Malajalam
|
||||
Fail Ei läpäise
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2:n vähimmäiskontrastit: tavallinen teksti AA 4.5:1 (1.4.3) ja AAA 7:1 (1.4.6), suuri teksti AA 3:1 ja AAA 4.5:1, grafiikka ja säätimet AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Tausta luetaan valinnan keskeltä.
|
||||
The closest color that passes {level}: click to apply it. Lähin väri, joka läpäisee tason {level}: käytä sitä napsauttamalla.
|
||||
Local Libraries Paikalliset kirjastot
|
||||
Add Content Lisää sisältöä
|
||||
Click to apply to the selected type Käytä valittuun tekstiin napsauttamalla
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1678,6 +1678,7 @@ font-technology Variable Variables
|
||||
Fail Échec
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste minimal WCAG 2.2 : texte normal AA 4.5:1 (1.4.3) et AAA 7:1 (1.4.6), grand texte AA 3:1 et AAA 4.5:1, graphiques et commandes AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. L’arrière-plan est lu au centre de la sélection.
|
||||
The closest color that passes {level}: click to apply it. La couleur la plus proche qui satisfait {level}. Cliquez pour l’appliquer.
|
||||
Graphics Processor Processeur graphique
|
||||
Graphics: {adapter} Carte graphique : {adapter}
|
||||
Gravity Gravité
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1742,6 +1742,7 @@
|
||||
Fail નાપાસ
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 લઘુત્તમ કોન્ટ્રાસ્ટ: સામાન્ય ટેક્સ્ટ AA 4.5:1 (1.4.3) અને AAA 7:1 (1.4.6), મોટું ટેક્સ્ટ AA 3:1 અને AAA 4.5:1, ગ્રાફિક્સ અને નિયંત્રણો AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. પૃષ્ઠભૂમિ પસંદગીના કેન્દ્રમાં વાંચવામાં આવે છે.
|
||||
The closest color that passes {level}: click to apply it. {level} પાસ કરતો સૌથી નજીકનો રંગ: તેને લાગુ કરવા ક્લિક કરો.
|
||||
Graphics Processor ગ્રાફિક્સ પ્રોસેસર
|
||||
Graphics: {adapter} ગ્રાફિક્સ: {adapter}
|
||||
Gravity ગ્રેવિટી
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
@@ -2629,6 +2629,7 @@ arrowhead Feather पंख
|
||||
Fail फ़ेल
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 न्यूनतम कंट्रास्ट: सामान्य टेक्स्ट AA 4.5:1 (1.4.3) और AAA 7:1 (1.4.6), बड़ा टेक्स्ट AA 3:1 और AAA 4.5:1, ग्राफ़िक्स और कंट्रोल AA 3:1 (1.4.11)।
|
||||
The background is read at the center of the selection. पृष्ठभूमि सिलेक्शन के केंद्र पर पढ़ी जाती है।
|
||||
The closest color that passes {level}: click to apply it. {level} पास करने वाला सबसे नज़दीकी रंग: लागू करने के लिए क्लिक करें।
|
||||
Graphics Processor ग्राफिक्स प्रोसेसर
|
||||
Graphics: {adapter} ग्राफिक्स: {adapter}
|
||||
Gravity ग्रेविटी
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2082,6 +2082,7 @@ file-filter Templates Sablonok
|
||||
Fail Nem felel meg
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 szerinti minimális kontraszt: normál szöveg AA 4.5:1 (1.4.3) és AAA 7:1 (1.4.6), nagy szöveg AA 3:1 és AAA 4.5:1, grafikák és vezérlők AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. A háttér színét a kijelölés közepén olvassa le a program.
|
||||
The closest color that passes {level}: click to apply it. A legközelebbi szín, amely megfelel a(z) {level} szintnek: kattintson az alkalmazásához.
|
||||
Graphics Processor Grafikus processzor
|
||||
Graphics: {adapter} Grafika: {adapter}
|
||||
Gravity Gravitáció
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2736,6 +2736,7 @@ digits Malayalam Malayalam
|
||||
Fail Gagal
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Kontras minimum WCAG 2.2: teks normal AA 4.5:1 (1.4.3) dan AAA 7:1 (1.4.6), teks besar AA 3:1 dan AAA 4.5:1, grafis dan kontrol AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Latar dibaca di tengah seleksi.
|
||||
The closest color that passes {level}: click to apply it. Warna terdekat yang lolos {level}: klik untuk menerapkannya.
|
||||
Local Libraries Pustaka lokal
|
||||
Add Content Tambahkan konten
|
||||
Click to apply to the selected type Klik untuk menerapkan ke teks terpilih
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1716,6 +1716,7 @@ file-filter Templates Modelli
|
||||
Fail Non superato
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrasto minimo WCAG 2.2: testo normale AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), testo grande AA 3:1 e AAA 4.5:1, grafica e controlli AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Lo sfondo viene letto al centro della selezione.
|
||||
The closest color that passes {level}: click to apply it. Il colore più vicino che soddisfa {level}: fai clic per applicarlo.
|
||||
Graphics Processor Processore grafico
|
||||
Graphics: {adapter} Scheda grafica: {adapter}
|
||||
Gravity Gravità
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4457,6 +4457,7 @@ file-filter Templates テンプレート
|
||||
Fail 不合格
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 の最小コントラスト:通常のテキスト AA 4.5:1 (1.4.3) と AAA 7:1 (1.4.6)、大きなテキスト AA 3:1 と AAA 4.5:1、グラフィックとコントロール AA 3:1 (1.4.11)。
|
||||
The background is read at the center of the selection. 背景は選択範囲の中央で読み取ります。
|
||||
The closest color that passes {level}: click to apply it. {level} を満たす最も近いカラー:クリックで適用します。
|
||||
Greek & Cyrillic ギリシャ文字とキリル文字
|
||||
Hex by Column 六角形 (列)
|
||||
Hex by Row 六角形 (行)
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4135,6 +4135,7 @@ digits Malayalam მალაიალამური
|
||||
Fail არ აკმაყოფილებს
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2-ის მინიმალური კონტრასტი: ჩვეულებრივი ტექსტი AA 4.5:1 (1.4.3) და AAA 7:1 (1.4.6), დიდი ტექსტი AA 3:1 და AAA 4.5:1, გრაფიკა და მართვის ელემენტები AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. ფონი იკითხება მონიშნულის ცენტრში.
|
||||
The closest color that passes {level}: click to apply it. უახლოესი ფერი, რომელიც აკმაყოფილებს {level}-ს: დააწკაპუნეთ მის გამოსაყენებლად.
|
||||
Local Libraries ლოკალური ბიბლიოთეკები
|
||||
Add Content შიგთავსის დამატება
|
||||
Click to apply to the selected type დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4447,6 +4447,7 @@ file-filter Templates 템플릿
|
||||
Fail 실패
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 최소 대비: 일반 텍스트 AA 4.5:1 (1.4.3) 및 AAA 7:1 (1.4.6), 큰 텍스트 AA 3:1 및 AAA 4.5:1, 그래픽과 컨트롤 AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. 배경은 선택 영역의 중앙에서 읽습니다.
|
||||
The closest color that passes {level}: click to apply it. {level}을(를) 충족하는 가장 가까운 색상: 클릭하여 적용합니다.
|
||||
Greek & Cyrillic 그리스어 및 키릴 문자
|
||||
Hex by Column 열 기준 육각형
|
||||
Hex by Row 행 기준 육각형
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2721,6 +2721,7 @@ digits Malayalam Malayalam
|
||||
Fail Niet geslaagd
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimumcontrast volgens WCAG 2.2: normale tekst AA 4.5:1 (1.4.3) en AAA 7:1 (1.4.6), grote tekst AA 3:1 en AAA 4.5:1, illustraties en bedieningselementen AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. De achtergrond wordt in het midden van de selectie gemeten.
|
||||
The closest color that passes {level}: click to apply it. De dichtstbijzijnde kleur die aan {level} voldoet: klik om deze toe te passen.
|
||||
Local Libraries Lokale bibliotheken
|
||||
Add Content Inhoud toevoegen
|
||||
Click to apply to the selected type Klik om toe te passen op de geselecteerde tekst
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2109,6 +2109,7 @@ digits Malayalam Malajalam
|
||||
Fail Nie spełnia
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalny kontrast według WCAG 2.2: zwykły tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), duży tekst AA 3:1 i AAA 4.5:1, grafika i elementy sterujące AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Tło jest odczytywane na środku zaznaczenia.
|
||||
The closest color that passes {level}: click to apply it. Najbliższy kolor spełniający {level}: kliknij, aby go zastosować.
|
||||
Local Libraries Biblioteki lokalne
|
||||
Add Content Dodaj zawartość
|
||||
Click to apply to the selected type Kliknij, aby zastosować do zaznaczonego tekstu
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4139,6 +4139,7 @@ font-technology Variable Variáveis
|
||||
Fail Reprovado
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo da WCAG 2.2: texto normal AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), texto grande AA 3:1 e AAA 4.5:1, gráficos e controles AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. O fundo é lido no centro da seleção.
|
||||
The closest color that passes {level}: click to apply it. A cor mais próxima que atende a {level}: clique para aplicá-la.
|
||||
Highlight Rows Destacar linhas
|
||||
Highlight Variable Destacar variável
|
||||
Sort Variables Ordenar variáveis
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1701,6 +1701,7 @@ file-filter Templates Шаблоны
|
||||
Fail Не соответствует
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимальный контраст по WCAG 2.2: обычный текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), крупный текст AA 3:1 и AAA 4.5:1, графика и элементы управления AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Фон определяется в центре выделения.
|
||||
The closest color that passes {level}: click to apply it. Ближайший цвет, соответствующий {level}: щёлкните, чтобы применить его.
|
||||
Graphics Processor Графический процессор
|
||||
Graphics: {adapter} Графика: {adapter}
|
||||
Gravity Гравитация
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1635,6 +1635,7 @@ font-technology Variable Variabla
|
||||
Fail Underkänd
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minsta kontrast enligt WCAG 2.2: normal text AA 4.5:1 (1.4.3) och AAA 7:1 (1.4.6), stor text AA 3:1 och AAA 4.5:1, grafik och kontroller AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Bakgrunden läses i mitten av markeringen.
|
||||
The closest color that passes {level}: click to apply it. Den närmaste färgen som klarar {level}: klicka för att använda den.
|
||||
Graphics Processor Grafikprocessor
|
||||
Graphics: {adapter} Grafik: {adapter}
|
||||
Gravity Gravitation
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1599,6 +1599,7 @@ font-technology Variable Değişken
|
||||
Fail Kaldı
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 en düşük kontrast: normal metin AA 4.5:1 (1.4.3) ve AAA 7:1 (1.4.6), büyük metin AA 3:1 ve AAA 4.5:1, grafikler ve denetimler AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Arka plan seçimin ortasında okunur.
|
||||
The closest color that passes {level}: click to apply it. {level} düzeyini karşılayan en yakın renk: uygulamak için tıklayın.
|
||||
Graphics Processor Grafik İşlemcisi
|
||||
Graphics: {adapter} Grafik: {adapter}
|
||||
Gravity Yerçekimi
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1710,6 +1710,7 @@ file-filter Templates Шаблони
|
||||
Fail Не відповідає
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Мінімальний контраст за WCAG 2.2: звичайний текст AA 4.5:1 (1.4.3) і AAA 7:1 (1.4.6), великий текст AA 3:1 і AAA 4.5:1, графіка й елементи керування AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Фон визначається в центрі виділення.
|
||||
The closest color that passes {level}: click to apply it. Найближчий колір, що відповідає {level}: клацніть, щоб застосувати його.
|
||||
Graphics Processor Графічний процесор
|
||||
Graphics: {adapter} Графіка: {adapter}
|
||||
Gravity Гравітація
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1944,6 +1944,7 @@ file-filter Templates Mẫu
|
||||
Fail Không đạt
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Độ tương phản tối thiểu theo WCAG 2.2: văn bản thường AA 4.5:1 (1.4.3) và AAA 7:1 (1.4.6), văn bản lớn AA 3:1 và AAA 4.5:1, đồ họa và điều khiển AA 3:1 (1.4.11).
|
||||
The background is read at the center of the selection. Nền được đọc tại tâm vùng chọn.
|
||||
The closest color that passes {level}: click to apply it. Màu gần nhất đạt {level}: bấm để áp dụng.
|
||||
Graphics Processor Bộ xử lý đồ họa
|
||||
Graphics: {adapter} Đồ họa: {adapter}
|
||||
Gravity Trọng lực
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1644,6 +1644,7 @@ file-filter Templates 模板
|
||||
Fail 未通过
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低对比度:普通文本 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大号文本 AA 3:1 和 AAA 4.5:1,图形和控件 AA 3:1 (1.4.11)。
|
||||
The background is read at the center of the selection. 背景在所选对象的中心读取。
|
||||
The closest color that passes {level}: click to apply it. 符合 {level} 的最接近颜色:单击即可应用。
|
||||
Gravity 重力
|
||||
Grays 灰度级数
|
||||
Grays and Neutrals 灰色和中性色
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1680,6 +1680,7 @@ file-filter Templates 範本
|
||||
Fail 未通過
|
||||
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低對比度:一般文字 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大型文字 AA 3:1 和 AAA 4.5:1,圖形和控制項 AA 3:1 (1.4.11)。
|
||||
The background is read at the center of the selection. 背景在選取範圍的中心讀取。
|
||||
The closest color that passes {level}: click to apply it. 符合 {level} 的最接近顏色:按一下即可套用。
|
||||
Graphics Processor 圖形處理器
|
||||
Graphics: {adapter} 圖形:{adapter}
|
||||
Gravity 重力
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -44,6 +44,8 @@ pub(crate) struct Menus {
|
||||
/// The states of the catalogued commands and of every menu item's reference.
|
||||
pub(crate) states: Tracked<CommandStates>,
|
||||
catalog: Option<AppCatalog>,
|
||||
/// The rows `catalog` was made from, kept while what they are made from stays the same.
|
||||
rows: Option<CatalogRows>,
|
||||
}
|
||||
|
||||
impl Menus {
|
||||
@@ -245,26 +247,35 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
|
||||
.collect();
|
||||
let Build { mut states, refs, .. } = build;
|
||||
|
||||
let defs = catalog_defs(app, &refs, &mut states);
|
||||
// The catalog is built again only when what its rows are made from changed; edits and selection changes change
|
||||
// the rows' states alone.
|
||||
let inputs = CatalogInputs {
|
||||
snapshot: crate::shortcut_editor::snapshot(),
|
||||
platform: crate::keymap::platform(),
|
||||
plays: crate::panels::actions::function_keys(&app.ui.actions),
|
||||
refs,
|
||||
overrides: app.shortcut_overrides.clone(),
|
||||
generation: generation(&listed, &[], &[]),
|
||||
};
|
||||
let rows = match app.menus.rows.take().filter(|rows| rows.accepted && rows.inputs == inputs) {
|
||||
Some(rows) => rows,
|
||||
None => {
|
||||
let (defs, known) = catalog_defs(&inputs);
|
||||
let catalog = build_catalog(app, &listed, &inputs.plays, defs.clone());
|
||||
let accepted = catalog.is_some();
|
||||
if catalog.is_some() {
|
||||
app.menus.catalog = catalog;
|
||||
}
|
||||
CatalogRows { inputs, defs, known, accepted }
|
||||
}
|
||||
};
|
||||
row_states(app, &rows, &mut states);
|
||||
crate::panels::panel_menu_states(app, &mut states);
|
||||
|
||||
let bar = MenuBar::new(menus);
|
||||
let options = LayoutOptions::new(APP_NAME).label(&translate_label);
|
||||
let laid = layout(&bar, target, &options).bar;
|
||||
let type_keys = crate::type_editing::app_keys(&defs, &app.shortcut_overrides);
|
||||
let (defs, linked_keys) = without_linked(defs);
|
||||
match AppCatalog::new(defs, generation(&listed, &crate::panels::actions::function_keys(&app.ui.actions), &type_keys)) {
|
||||
Ok(catalog) => {
|
||||
// While a text field has the keys no shortcut runs, as in production; the text-editing chords still edit it,
|
||||
// and the Type tool's commands run while it types.
|
||||
let catalog = catalog.typing_rule(TypingRule::AllWait);
|
||||
let catalog = linked_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys));
|
||||
let catalog = UNROUTED.iter().fold(catalog, |catalog, id| catalog.replace_defaults(id.as_str(), Vec::new()));
|
||||
app.menus.catalog = Some(type_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys)));
|
||||
}
|
||||
// A refused catalog is a bug in the rows; the last good one keeps the commands working.
|
||||
Err(e) => eprintln!("menu catalog refused: {e:?}"),
|
||||
}
|
||||
app.menus.rows = Some(rows);
|
||||
app.menus.bar = bar;
|
||||
if *app.menus.laid != laid {
|
||||
app.menus.laid.edit(|l| *l = laid);
|
||||
@@ -272,28 +283,63 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
|
||||
app.menus.states.edit(|s| *s = states);
|
||||
}
|
||||
|
||||
/// What the catalog's rows are made from: the editor's entries, the platform, the actions' function keys, the menu
|
||||
/// references with their labels, the user's shortcuts, and the language, plug-ins, scripts, fonts and listed names.
|
||||
struct CatalogInputs {
|
||||
snapshot: std::sync::Arc<crate::shortcut_editor::Snapshot>,
|
||||
platform: craft::keymap::Platform,
|
||||
plays: Vec<(String, craft::keymap::Chord)>,
|
||||
refs: Vec<(CommandRef, String, bool)>,
|
||||
overrides: std::sync::Arc<craft::keymap::Overrides>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl PartialEq for CatalogInputs {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
std::sync::Arc::ptr_eq(&self.snapshot, &other.snapshot)
|
||||
&& std::sync::Arc::ptr_eq(&self.overrides, &other.overrides)
|
||||
&& (self.platform, self.generation) == (other.platform, other.generation)
|
||||
&& self.plays == other.plays
|
||||
&& self.refs == other.refs
|
||||
}
|
||||
}
|
||||
|
||||
/// The catalog's rows as the last rebuild made them from `inputs`, the keys of those rows, and whether the catalog
|
||||
/// took them (a refused set is made again on the next rebuild).
|
||||
struct CatalogRows {
|
||||
inputs: CatalogInputs,
|
||||
defs: Vec<CommandDef>,
|
||||
known: HashSet<String>,
|
||||
accepted: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times this thread made the catalog's rows.
|
||||
pub(crate) static CATALOG_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The catalog's rows: the keymap's, with icons, then a row for every menu reference the keymap
|
||||
/// does not name (by its key or its bare id), and the state of every row not set by the tree.
|
||||
/// does not name (by its key or its bare id), with the keys of every row.
|
||||
// PLAN: the Shift+Space row for MomentaryCommands::RotateView (S-CV8) is the canvas area's: that
|
||||
// command is not in the app scope, which `AppCatalog` accepts.
|
||||
// PLAN: ActionsPanelCommands' defs (area plan X6) are menus-w18's; their signature is not visible here.
|
||||
fn catalog_defs(app: &VectorcraftApp, refs: &[(CommandRef, String, bool)], states: &mut CommandStates) -> Vec<CommandDef> {
|
||||
let snapshot = crate::shortcut_editor::snapshot();
|
||||
fn catalog_defs(inputs: &CatalogInputs) -> (Vec<CommandDef>, HashSet<String>) {
|
||||
#[cfg(test)]
|
||||
CATALOG_BUILDS.set(CATALOG_BUILDS.get() + 1);
|
||||
// An action's function key comes first: it takes priority over the command shortcuts.
|
||||
let plays = crate::panels::actions::function_keys(&app.ui.actions).into_iter().map(|(name, chord)| {
|
||||
let plays = inputs.plays.iter().map(|(name, chord)| {
|
||||
let play = CommandRef::with_params(crate::panels::actions::PLAY_ACTION, json!({ "action": name }));
|
||||
CommandDef::new(play, name, Scope::app()).with_default(Binding::new(chord))
|
||||
CommandDef::new(play, name.clone(), Scope::app()).with_default(Binding::new(*chord))
|
||||
});
|
||||
let mut defs: Vec<CommandDef> = plays
|
||||
.chain(crate::keymap::catalog_defs(crate::keymap::platform(), &snapshot).into_iter().map(|d| {
|
||||
match crate::panels::command_icon(&d.command.id) {
|
||||
Some(icon) => d.with_icon(icon),
|
||||
None => d,
|
||||
}
|
||||
.chain(crate::keymap::catalog_defs(inputs.platform, &inputs.snapshot).into_iter().map(|d| match crate::panels::command_icon(&d.command.id) {
|
||||
Some(icon) => d.with_icon(icon),
|
||||
None => d,
|
||||
}))
|
||||
.collect();
|
||||
let mut known: HashSet<String> = defs.iter().map(|d| d.command.key()).collect();
|
||||
for (command, label, checkable) in refs {
|
||||
for (command, label, checkable) in &inputs.refs {
|
||||
if known.contains(&command.key()) || known.contains(&command.id) {
|
||||
continue;
|
||||
}
|
||||
@@ -301,20 +347,46 @@ fn catalog_defs(app: &VectorcraftApp, refs: &[(CommandRef, String, bool)], state
|
||||
let def = CommandDef::new(command.clone(), label.clone(), Scope::app());
|
||||
defs.push(if *checkable { def.toggle() } else { def });
|
||||
}
|
||||
for d in &defs {
|
||||
(defs, known)
|
||||
}
|
||||
|
||||
/// The catalog made from `defs`, or `None` when it refuses them.
|
||||
fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft::keymap::Chord)], defs: Vec<CommandDef>) -> Option<AppCatalog> {
|
||||
let type_keys = crate::type_editing::app_keys(&defs, &app.shortcut_overrides);
|
||||
let (defs, linked_keys) = without_linked(defs);
|
||||
match AppCatalog::new(defs, generation(listed, plays, &type_keys)) {
|
||||
Ok(catalog) => {
|
||||
// While a text field has the keys no shortcut runs, as in production; the text-editing chords still edit it,
|
||||
// and the Type tool's commands run while it types.
|
||||
let catalog = catalog.typing_rule(TypingRule::AllWait);
|
||||
let catalog = linked_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys));
|
||||
let catalog = UNROUTED.iter().fold(catalog, |catalog, id| catalog.replace_defaults(id.as_str(), Vec::new()));
|
||||
Some(type_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys)))
|
||||
}
|
||||
// A refused catalog is a bug in the rows; the last good one keeps the commands working.
|
||||
Err(e) => {
|
||||
eprintln!("menu catalog refused: {e:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The state of every catalog row the tree did not set, and of the engine commands the palette lists that no row
|
||||
/// names.
|
||||
fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates) {
|
||||
for d in &rows.defs {
|
||||
if states.get(&d.command).is_none() {
|
||||
states.set(d.command.clone(), row_state(app, &d.command, &d.label));
|
||||
}
|
||||
}
|
||||
// The engine commands the palette lists and no row names (Asset Export's Remove and Rename) are dimmed there and say
|
||||
// why, as the rows are.
|
||||
for c in crate::palette::listed_engine_commands().filter(|c| !known.contains(c.id)) {
|
||||
for c in crate::palette::listed_engine_commands().filter(|c| !rows.known.contains(c.id)) {
|
||||
let command = CommandRef::new(c.id);
|
||||
if states.get(&command).is_none() {
|
||||
states.set(command.clone(), row_state(app, &command, c.label));
|
||||
}
|
||||
}
|
||||
defs
|
||||
}
|
||||
|
||||
/// `defs` without the commands a linked framework set defines (Undo, Redo, Cut, Copy, Paste and Tab's panels toggles):
|
||||
@@ -506,3 +578,44 @@ impl Build<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn app_with_document() -> (VectorcraftApp, egui::Context) {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let ctx = crate::testing::ui_context();
|
||||
refresh(&mut app, &ctx);
|
||||
(app, ctx)
|
||||
}
|
||||
|
||||
/// Edits and selection changes give the rows new states and leave the catalog's rows as they were made.
|
||||
#[test]
|
||||
fn edits_and_selection_changes_keep_the_catalog_rows() {
|
||||
let (mut app, ctx) = app_with_document();
|
||||
// The plug-ins, fonts and scripts are the process's, which tests on other threads change, and a row the menus
|
||||
// leave out while it is off comes back with the art: a rebuild that made the rows while those moved is not counted.
|
||||
let shared = |app: &VectorcraftApp| {
|
||||
app.menus.rows.as_ref().map(|r| (std::sync::Arc::as_ptr(&r.inputs.snapshot).addr(), r.inputs.generation, r.inputs.refs.clone()))
|
||||
};
|
||||
let mut remade = 0;
|
||||
let mut step = |app: &mut VectorcraftApp, id: &str, params: Value| {
|
||||
app.run(id, params).unwrap();
|
||||
let (builds, before) = (CATALOG_BUILDS.get(), shared(app));
|
||||
refresh(app, &ctx);
|
||||
if CATALOG_BUILDS.get() > builds && shared(app) == before {
|
||||
remade += 1;
|
||||
}
|
||||
};
|
||||
for k in 0..5 {
|
||||
step(&mut app, "shape.rectangle", json!({"x": k * 20, "y": 0, "width": 10, "height": 10}));
|
||||
step(&mut app, "select.none", json!({}));
|
||||
}
|
||||
step(&mut app, "select.all", json!({}));
|
||||
assert_eq!(remade, 0, "11 rebuilds after edits and selection changes made the catalog's rows again");
|
||||
assert!(app.menus.states.get(&CommandRef::new("edit.undo")).is_some_and(CommandState::is_enabled), "the states follow the edits");
|
||||
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled));
|
||||
}
|
||||
}
|
||||
@@ -1616,7 +1616,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.colorWheel",
|
||||
"Color Wheel Options",
|
||||
"",
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing,
Line truncated
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Opacity, Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection;
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.savePdfDialog",
|
||||
|
||||
@@ -52,6 +52,9 @@ pub struct SwatchRows {
|
||||
pub groups: bool,
|
||||
/// Whether the grabbed swatch's paint can travel as an unlinked process color.
|
||||
pub unlinked_process_color: bool,
|
||||
/// The rows as the document held them when the drag started, which New Swatch and Delete
|
||||
/// Swatch check before acting on them.
|
||||
pub(crate) held: std::sync::Arc<crate::panels::swatches::HeldRows>,
|
||||
}
|
||||
|
||||
impl PanelDrag {
|
||||
|
||||
@@ -1136,7 +1136,14 @@ mod tests {
|
||||
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
|
||||
let source = app.session.active().unwrap();
|
||||
let paint = source.doc.swatch(name).unwrap().paint.clone();
|
||||
let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true };
|
||||
let rows = SwatchRows {
|
||||
document: source.uid,
|
||||
grabbed: name.into(),
|
||||
names: vec![name.into()],
|
||||
groups: false,
|
||||
unlinked_process_color: true,
|
||||
held: Default::default(),
|
||||
};
|
||||
let drag = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None };
|
||||
app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap();
|
||||
drop_paint(&mut app, Well::Primary, &drag);
|
||||
@@ -1164,8 +1171,14 @@ mod tests {
|
||||
app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap();
|
||||
let source = app.session.active().unwrap();
|
||||
let paint = source.doc.swatch(name).unwrap().paint.clone();
|
||||
let rows =
|
||||
SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false };
|
||||
let rows = SwatchRows {
|
||||
document: source.uid,
|
||||
grabbed: name.into(),
|
||||
names: vec![name.into()],
|
||||
groups: false,
|
||||
unlinked_process_color: false,
|
||||
held: Default::default(),
|
||||
};
|
||||
let drag = PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None };
|
||||
if different_drawing {
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
@@ -1227,6 +1240,8 @@ mod tests_color_wheel_box;
|
||||
#[cfg(test)]
|
||||
mod tests_color_wheel_contrast;
|
||||
#[cfg(test)]
|
||||
mod tests_color_wheel_contrast_lines;
|
||||
#[cfg(test)]
|
||||
mod tests_color_wheel_copy;
|
||||
#[cfg(test)]
|
||||
mod tests_color_wheel_document_colors;
|
||||
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user