diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000..e3ff66fc1c
--- /dev/null
+++ b/.gitattributes
@@ -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
diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json
index 507caffe10..6b6099e7b6 100644
--- a/.github/nightly-signing-policy.json
+++ b/.github/nightly-signing-policy.json
@@ -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",
diff --git a/assets/app-icon/vectorcraft-nightly.png b/assets/app-icon/vectorcraft-nightly.png
index 4211c1ddb8..09b2747606 100644
Binary files a/assets/app-icon/vectorcraft-nightly.png and b/assets/app-icon/vectorcraft-nightly.png differ
diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs
index ef42eec957..ba5bb3b974 100644
--- a/crates/color/src/wcag.rs
+++ b/crates/color/src/wcag.rs
@@ -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
+/// () 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 = (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]);
diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs
index b9fd0b98e6..8a4e6ebe6f 100644
--- a/crates/engine/src/cmd.rs
+++ b/crates/engine/src/cmd.rs
@@ -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.
diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs
index 401879bc91..dd18bcadcb 100644
--- a/crates/engine/src/cmd/colorcmds.rs
+++ b/crates/engine/src/cmd/colorcmds.rs
@@ -151,7 +151,7 @@ pub fn specs() -> Vec {
"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
),
@@ -1032,7 +1032,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,
+ /// 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 {
+ 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 {
+ 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 {
+ 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, Backdrop)> {
const C: &str = "color.contrast";
check_numbers(p, &["opacity"], C)?;
let opacity = match p.get("opacity").and_then(Value::as_f64) {
@@ -1044,23 +1266,28 @@ fn contrast(s: &mut Session, p: &Value) -> Result {
None => None,
};
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
+ let given = p.get("color").is_some_and(|v| !v.is_null());
let (color, drawn) = match p.get("color") {
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
- Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
+ Some(v) => (Some(color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?), Drawn::default()),
};
+ if need_color && color.is_none() {
+ return Err(bad(C, no_color()));
+ }
let rich_black = s.prefs.black_on_screen == "rich";
let cms = vectorcraft_color::cms::active();
- let shown = |c: &Color| match *c {
- Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
- _ => cms.display_rgb(c),
- };
+ let shown = |c: &Color| shown_rgb(&cms, rich_black, c);
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
+ // Whether the background read is one color across its pixels.
+ let mut uniform = true;
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
let (against, written) = match p.get("against").filter(|_| !below) {
None => {
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
// one the ratio uses, and giving it back answers the same ratio.
- let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
+ let ((sample, _), one) = color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?;
+ uniform &= one;
+ let working = to_8bit(cms.srgb_to_rgb(sample));
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
}
Some(v) => {
@@ -1096,60 +1323,51 @@ fn contrast(s: &mut Session, p: &Value) -> Result {
// 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::>();
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
- let backdrop = match scope {
- Some(_) if !sampled => ([0.0; 3], 0.0),
- None if !sampled => (against, 1.0),
+ let (backdrop, one) = match scope {
+ Some(_) if !sampled => (([0.0; 3], 0.0), true),
+ None if !sampled => ((against, 1.0), uniform),
// The background itself, as the answer writes it.
- None if step.hide.is_none() && full.is_empty() => (against, 1.0),
+ None if step.hide.is_none() && full.is_empty() => ((against, 1.0), uniform),
_ => read(scope.map(|a| &a.within))?,
};
// The alpha of the art below the level inside the level around it, while a blending level
// lies further out (none for a given background).
- let inner = match above.first() {
- Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
- _ => 0.0,
+ let (inner, inner_one) = match above.first() {
+ Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => {
+ let ((_, a), one) = read(Some(&around.within))?;
+ (a, one)
+ }
+ _ => (0.0, true),
};
- let source = if !blends(step) {
- x
- } else if alone <= 0.0 {
- (x.0, 0.0)
- } else {
- (std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
- };
- // A level that isolates its blending carries out the alpha of what it holds composited on
- // its own.
- let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
- x = composite(step.blend, source, step.opacity, backdrop);
- alone = drawn + inner * (1.0 - drawn);
- }
- let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
- let ratio = wcag::contrast_ratio(front, against);
- let levels = |c: Category| {
- let (aa, aaa) = c.passes(ratio);
- match aaa {
- Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
- None => json!({ "aa": aa }),
+ // A blend mode mixes the color with the art below it pixel by pixel, which one color read for
+ // art of several colors does not stand for, also when that art reaches it through the levels
+ // inside it.
+ mixed |= !one || !inner_one;
+ if mixed && step.blend != BlendMode::Normal && step.opacity > 0.0 {
+ return Err(bad(C, "the art behind the selection is not one color where it is read, and the color blends with it: give `against`"));
}
- };
- let [r, g, b] = written;
- Ok(json!({
- "ratio": ratio,
- "against": format!("#{r:02x}{g:02x}{b:02x}"),
- "normalText": levels(Category::NormalText),
- "largeText": levels(Category::LargeText),
- "graphics": levels(Category::Graphics),
- }))
+ let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, blends: blends(step), isolate: step.isolate, inner };
+ (_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone));
+ passes.push(pass);
+ }
+ let stain = if given { None } else { stain_of(s, !need_color) };
+ Ok((color, Backdrop { against, written, passes, stain, rich_black }))
}
/// An object around the proxy's object: one in the document, or a group of the picked object's
@@ -1232,7 +1450,8 @@ fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32;
/// levels that change what they draw must be the same objects too, since the art below each one is
/// read with that object hidden, and the object's opacity must be the same apart from its row's,
/// since the row draws over the object's rows below it and the object over the art behind it, and a
-/// row that blends or is translucent must lie over the same shown rows.
+/// row that blends or is translucent must lie over the same shown rows, and over a lower row that
+/// blends, with the same isolation.
fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0);
let level = |x: &Level, y: &Level| {
@@ -1248,10 +1467,26 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1);
// A row that blends or lets art through draws over the rows below it, read at one point.
let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0);
+ // A lower row that blends reads the art behind the object unless the object isolates its
+ // blending, so a row drawn over it reads a backdrop that depends on the isolation. A blending
+ // row at no opacity does not show, nor does a fill row without effects under an opaque solid
+ // Normal fill row without effects, which covers the same shape (a stroke reaches outside it).
+ let plain_fill = |i: &vectorcraft_doc::AppearanceItem| i.is_fill() && i.effects().is_empty();
+ let covers = |i: &vectorcraft_doc::AppearanceItem| {
+ plain_fill(i) && i.blend() == BlendMode::Normal && i.opacity() >= 1.0 && matches!(i.paint(), Paint::Solid { .. })
+ };
+ let over_blended = |d: &Drawn| {
+ over_rows(d)
+ && d.lower
+ .iter()
+ .enumerate()
+ .any(|(k, i)| i.blend() != BlendMode::Normal && i.opacity() > 0.0 && !(plain_fill(i) && d.lower[k + 1..].iter().any(covers)))
+ };
row(a) == row(b)
&& (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower)
&& a.blend == b.blend
&& (row(a).is_none() || a.isolate == b.isolate)
+ && (given_opacity || !below || !(over_blended(a) || over_blended(b)) || a.isolate == b.isolate)
&& (given_opacity || (total(a) - total(b)).abs() < 1e-6)
&& (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6)
&& la.len() == lb.len()
@@ -1263,8 +1498,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, Drawn), String> {
let stroke = !s.fill_active;
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
if if stroke { stroke_mixed } else { fill_mixed } {
@@ -1320,20 +1556,28 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
} else {
drawing = source()?.unwrap_or_default();
}
- let no_color = || "the active fill or stroke has no color: give `color`".to_string();
- match if stroke { stroke_paint } else { fill } {
- Paint::Solid { color, .. } => Ok((stained(s, color), drawing)),
+ let found = match if stroke { stroke_paint } else { fill } {
+ Paint::Solid { color, .. } => Some((color, drawing.clone())),
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
- f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color)
+ f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity)))
}
Paint::Gradient(g) => {
let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));
- g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color)
+ g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity)))
}
- Paint::None | Paint::Pattern { .. } => Err(no_color()),
- }
+ Paint::None | Paint::Pattern { .. } => None,
+ };
+ Ok(match found {
+ Some((color, drawn)) => (Some(color), drawn),
+ None => (None, drawing),
+ })
+}
+
+/// The message for an active fill or stroke with no color to measure.
+fn no_color() -> String {
+ "the active fill or stroke has no color: give `color`".to_string()
}
/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its
@@ -1398,19 +1642,21 @@ fn drawn_settings(s: &Session, n: &Node, item: Option, stroke: bool) -> s
Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower })
}
-/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
-/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
-/// `color` itself otherwise.
-fn stained(s: &Session, color: Color) -> Color {
- let stain = s.active().and_then(|st| {
- let sp = st.selection.symbol_part.as_ref()?;
- st.selected_symbol_part()?;
- vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
- });
- match stain {
- Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
- None => color,
+/// The color and amount a fill stains the picked object of a dynamic symbol instance with
+/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill), when
+/// such an object is picked and its proxy shows a solid color. For a pick (`pick`), a proxy of None
+/// or a pattern counts too, as the pick puts a solid color in its place.
+fn stain_of(s: &Session, pick: bool) -> Option<(Color, f32)> {
+ let (fill, stroke) = s.proxy_paints();
+ match if s.fill_active { fill } else { stroke } {
+ Paint::Solid { .. } => {}
+ Paint::None | Paint::Pattern { .. } if pick => {}
+ _ => return None,
}
+ let st = s.active()?;
+ let sp = st.selection.symbol_part.as_ref()?;
+ st.selected_symbol_part()?;
+ vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?).map(|(c, amount)| (c, amount.clamp(0.0, 1.0)))
}
/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and
@@ -1455,14 +1701,14 @@ fn enclosing(s: &Session, id: NodeId) -> Vec {
/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it;
/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer
/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing,
-/// without artboards.
+/// without artboards. Also whether the square's pixels are all one color.
fn color_below(
s: &Session,
rich_black: bool,
hide: Option<&Part>,
full: &[&Part],
scope: Option<&Part>,
-) -> std::result::Result<([f32; 3], f32), String> {
+) -> std::result::Result<(([f32; 3], f32), bool), String> {
super::has_selection(s)?;
let st = s.active().ok_or("no document open")?;
let ids = st.selection.objects.clone();
@@ -1591,8 +1837,10 @@ fn color_below(
let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts);
let px = img.pixels.as_chunks::<4>().0;
if px.is_empty() {
- return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) });
+ return Ok((if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) }, true));
}
+ // Whether the pixels are one color, to within one step of 255 per channel.
+ let uniform = px.first().is_none_or(|first| px.iter().all(|p| p.iter().zip(first).all(|(a, b)| a.abs_diff(*b) <= 1)));
// The pixels are premultiplied: the average color is their sum over their alpha's.
let mut sum = [0.0f64; 4];
for p in px {
@@ -1602,10 +1850,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.
diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs
index 37f4b132b5..1d6bd59fd1 100644
--- a/crates/engine/src/cmd/fileio/tests_psdread.rs
+++ b/crates/engine/src/cmd/fileio/tests_psdread.rs
@@ -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
diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs
index cc210ffa2a..ded0f137b3 100644
--- a/crates/engine/src/cmd/fileio/tests_psdslices.rs
+++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs
@@ -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()));
diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs
index de6f945b58..65f268f2b0 100644
--- a/crates/engine/src/cmd/links.rs
+++ b/crates/engine/src/cmd/links.rs
@@ -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 {
+pub(super) fn warped(path: &PathData, map: &Homography) -> Option {
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;
diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs
index c277af5c28..58612c744c 100644
--- a/crates/engine/src/cmd/place.rs
+++ b/crates/engine/src/cmd/place.rs
@@ -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 {
"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.\" (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 order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
+ "{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.\" (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 order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
has_doc,
place
),
@@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result