mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-20 09:23:10 +01:00
Merge main into #8741
# Conflicts: # docs/effects-parity.md # docs/three-d.md
This commit is contained in:
commit
aa853ad275
296 files changed
+25382
-1775
No files matched your search
Generated
+10
@@ -1009,6 +1009,15 @@ dependencies = [
|
||||
"ruzstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
@@ -6741,6 +6750,7 @@ dependencies = [
|
||||
name = "vectorcraft-color"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-cms",
|
||||
"kurbo 0.13.1",
|
||||
"moxcms",
|
||||
"proptest",
|
||||
|
||||
@@ -11,6 +11,7 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
|
||||
|
||||
@@ -146,7 +146,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
|
||||
@@ -253,6 +253,7 @@ fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_pdf_preset_store(&mut h.session);
|
||||
prefs_dir::attach_custom_dictionary(&mut h.session);
|
||||
prefs_dir::attach_arrowheads(&mut h.session);
|
||||
prefs_dir::attach_bevels(&mut h.session);
|
||||
h
|
||||
}
|
||||
|
||||
|
||||
@@ -567,6 +567,8 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_custom_dictionary(&mut app.session);
|
||||
// The custom arrowheads, kept in their own file next to the preferences.
|
||||
prefs_dir::attach_arrowheads(&mut app.session);
|
||||
// The custom bevels, kept in their own file next to the preferences.
|
||||
prefs_dir::attach_bevels(&mut app.session);
|
||||
// Fit the window to its monitor, or put it back where it was (still hidden).
|
||||
let winit_window = cc.winit_window().cloned();
|
||||
if let Some(w) = &winit_window {
|
||||
|
||||
@@ -122,6 +122,14 @@ pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the custom bevels (`threeD.bevels.edit`) in the `Bevels.vectorcraft` file next to the
|
||||
/// settings, and list the bevels it holds.
|
||||
pub fn attach_bevels(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(path) = store_dir(vectorcraft_engine::cmd::bevels::FILE_NAME) {
|
||||
session.attach_bevels_file(path.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+22
-8
@@ -34,6 +34,7 @@ const WIDE_LINES: &str =
|
||||
"lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width";
|
||||
const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)";
|
||||
const CLIPPING: &str = "clipping masks are not applied: the art they clip is written whole";
|
||||
const DISTORTED_IMAGES: &str = "images changed by Perspective Distort or Free Distort are written as the nearest parallelogram";
|
||||
const TYPE_ITEMS: &str = "fills and strokes added to whole type objects are left out of text entities (outline the text to keep them)";
|
||||
/// The warning for an image left out because it can't be decoded: the note raster exports give
|
||||
/// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`).
|
||||
@@ -671,7 +672,18 @@ impl<'a> Scene<'a> {
|
||||
self.shape(n, &bp, *rule);
|
||||
}
|
||||
NodeKind::Text(t) => self.text(n, t),
|
||||
NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)),
|
||||
NodeKind::Image(im) => match vectorcraft_doc::image_quad::nearest_affine(n) {
|
||||
// DXF clips nothing, so a distorted image is written at the affine placement nearest
|
||||
// its corners, with the warning once it is written.
|
||||
Some(xf) => {
|
||||
if self.image(&ImageObject { xf, ..self.doc.shown_image(n, im).into_owned() }) {
|
||||
self.warn(DISTORTED_IMAGES);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
self.image(&self.doc.shown_image(n, im));
|
||||
}
|
||||
},
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let doc = self.doc;
|
||||
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
|
||||
@@ -1325,18 +1337,19 @@ impl<'a> Scene<'a> {
|
||||
name
|
||||
}
|
||||
|
||||
/// A placed image, linked to its file (written once per image).
|
||||
fn image(&mut self, im: &ImageObject) {
|
||||
/// A placed image, linked to its file (written once per image). False when no `IMAGE` entity is
|
||||
/// written.
|
||||
fn image(&mut self, im: &ImageObject) -> bool {
|
||||
if !self.o.version.handles() {
|
||||
self.warn(NO_IMAGES);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
if !self.o.include_images {
|
||||
self.note_setting(IMAGES_OFF);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
let Some(i) = self.image_def(im) else { return };
|
||||
let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return };
|
||||
let Some(i) = self.image_def(im) else { return false };
|
||||
let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return false };
|
||||
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
|
||||
let map = self.to_dxf * im.xf;
|
||||
let lin = |v: kurbo::Vec2| (map * v.to_point()) - (map * Point::ZERO);
|
||||
@@ -1349,7 +1362,7 @@ impl<'a> Scene<'a> {
|
||||
let at = map * Point::new(0.0, h);
|
||||
let handle = self.handle();
|
||||
let reactor = self.handle();
|
||||
let Some(def) = self.images.get_mut(i) else { return };
|
||||
let Some(def) = self.images.get_mut(i) else { return false };
|
||||
def.reactors.push((reactor, handle));
|
||||
let def = def.handle;
|
||||
let layer = self.layer.clone();
|
||||
@@ -1375,6 +1388,7 @@ impl<'a> Scene<'a> {
|
||||
if self.o.version >= crate::DxfVersion::R2010 {
|
||||
self.e.int(290, 0);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The image file for image `im`, encoded once in the chosen format (`None`: left out).
|
||||
|
||||
@@ -984,6 +984,37 @@ fn images_can_be_left_out_with_their_files() {
|
||||
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty());
|
||||
}
|
||||
|
||||
/// DXF does not clip, so an image changed by Perspective Distort is written as one image at the
|
||||
/// placement nearest its corners, with a warning; an undistorted image gets no warning.
|
||||
#[test]
|
||||
fn a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning() {
|
||||
let mut d = image_and_fill_doc(Paint::None);
|
||||
let warned = |o: &DxfOutput| o.warnings.iter().any(|w| w.contains("Perspective Distort or Free Distort"));
|
||||
assert!(!warned(&export(&d, &opts(&d)).unwrap()));
|
||||
let id = d.layers[0].children().unwrap()[1].id;
|
||||
let q = [(12.0, 20.0), (28.0, 20.0), (30.0, 30.0), (10.0, 30.0)].map(|(x, y)| Point::new(x, y));
|
||||
d.node_mut(id).unwrap().set_image_corners(q).unwrap();
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
assert!(warned(&out), "{:?}", out.warnings);
|
||||
assert_eq!(kinds(&out).iter().filter(|k| *k == "IMAGE").count(), 1, "{:?}", kinds(&out));
|
||||
// Placed as an undistorted image with the nearest affine placement as its transform would be.
|
||||
let near = vectorcraft_doc::image_quad::nearest_affine(d.node(id).unwrap()).unwrap();
|
||||
let mut plain = d.clone();
|
||||
let n = plain.node_mut(id).unwrap();
|
||||
n.extras_mut().image_quad = None;
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
im.xf = near;
|
||||
}
|
||||
let placement = |o: &DxfOutput| {
|
||||
let e = entities(o).into_iter().find(|e| kind(e) == "IMAGE").expect("an IMAGE");
|
||||
[10, 20, 11, 21, 12, 22].map(|c| all(&e, c))
|
||||
};
|
||||
assert_eq!(placement(&out), placement(&export(&plain, &opts(&plain)).unwrap()));
|
||||
// With images left out, no IMAGE is written and the distortion warning does not appear.
|
||||
let left_out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap();
|
||||
assert!(!warned(&left_out), "{:?}", left_out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() {
|
||||
let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
|
||||
@@ -9,6 +9,7 @@ description = "VectorCraft color"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-cms = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod freeform;
|
||||
pub mod gradient;
|
||||
pub mod harmony;
|
||||
pub mod libraries;
|
||||
pub mod oklab;
|
||||
pub mod palette_io;
|
||||
pub mod recolor;
|
||||
pub mod swatch;
|
||||
@@ -340,6 +341,49 @@ pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
|
||||
[r + m, g + m, b + m]
|
||||
}
|
||||
|
||||
/// HSL (hue in degrees 0..360, saturation and lightness 0..1) of RGB numbers 0..1, with no color
|
||||
/// conversion, as CSS Color 4 converts sRGB to HSL
|
||||
/// (<https://www.w3.org/TR/css-color-4/#rgb-to-hsl>). The hue is 0 while the saturation is
|
||||
/// powerless, and a color outside 0..1 that gives a negative saturation turns its hue by 180°. As in
|
||||
/// the specification's conversion, a lightness of 0.00001 or less, a lightness less than 0.00001
|
||||
/// below 1, or a saturation of 0.00001 or less reads as a gray.
|
||||
pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] {
|
||||
const EPSILON: f32 = 1e-5;
|
||||
let max = r.max(g).max(b);
|
||||
let min = r.min(g).min(b);
|
||||
let d = max - min;
|
||||
let l = (max + min) / 2.0;
|
||||
if d <= 0.0 {
|
||||
return [0.0, 0.0, l];
|
||||
}
|
||||
let mut s = if l.abs() <= EPSILON || (1.0 - l).abs() < EPSILON { 0.0 } else { (max - l) / l.min(1.0 - l) };
|
||||
let mut h = rgb_to_hsb([r, g, b])[0];
|
||||
if s < 0.0 {
|
||||
h += 180.0;
|
||||
s = -s;
|
||||
}
|
||||
if s <= EPSILON {
|
||||
return [0.0, 0.0, l];
|
||||
}
|
||||
let h = h.rem_euclid(360.0);
|
||||
[if h >= 360.0 { 0.0 } else { h }, s, l]
|
||||
}
|
||||
|
||||
/// RGB numbers 0..1 of HSL `[h, s, l]` (hue in degrees, saturation and lightness 0..1), as CSS
|
||||
/// Color 4 converts HSL to sRGB (<https://www.w3.org/TR/css-color-4/#hsl-to-rgb>): the inverse of
|
||||
/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range before the conversion, so -120°
|
||||
/// gives the color of 240° and a hue of 10,000,000,000° the color of 280°. The specification's
|
||||
/// sample code uses JavaScript's remainder operator and gives a different color for a negative hue.
|
||||
pub fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] {
|
||||
let h = h.rem_euclid(360.0);
|
||||
let a = s * l.min(1.0 - l);
|
||||
let f = |n: f32| {
|
||||
let k = (n + h / 30.0).rem_euclid(12.0);
|
||||
l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
|
||||
};
|
||||
[f(0.0), f(8.0), f(4.0)]
|
||||
}
|
||||
|
||||
/// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations
|
||||
/// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from.
|
||||
pub fn keep_model(orig: Color, new: Color) -> Color {
|
||||
@@ -499,6 +543,59 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The HSL examples of CSS Color 4, section 7 (<https://www.w3.org/TR/css-color-4/#the-hsl-notation>),
|
||||
/// the first six rows, and two hues outside 0..360 that wrap into that range.
|
||||
#[test]
|
||||
fn hsl_follows_css_color_4() {
|
||||
for (hsl, hex) in [
|
||||
([0.0, 1.0, 0.5], "#ff0000"),
|
||||
([120.0, 1.0, 0.5], "#00ff00"),
|
||||
([120.0, 1.0, 0.25], "#008000"),
|
||||
([120.0, 1.0, 0.75], "#80ff80"),
|
||||
([240.0, 1.0, 0.5], "#0000ff"),
|
||||
([60.0, 1.0, 0.5], "#ffff00"),
|
||||
([360.0, 1.0, 0.5], "#ff0000"),
|
||||
([-120.0, 1.0, 0.5], "#0000ff"),
|
||||
] {
|
||||
let [r, g, b] = hsl_to_rgb(hsl);
|
||||
assert_eq!(Color::rgb(r, g, b).to_hex(), hex, "{hsl:?}");
|
||||
}
|
||||
let [h, s, l] = rgb_to_hsl([1.0, 0.5, 0.0]);
|
||||
assert!((h - 30.0).abs() < 1e-4 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-6, "{h} {s} {l}");
|
||||
let [h, s, l] = rgb_to_hsl(Color::rgb8(255, 128, 0).to_rgb_uncalibrated());
|
||||
assert!((h - 30.0).abs() < 0.2 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-3, "{h} {s} {l}");
|
||||
// A gray has no hue: the hue is 0 and the saturation 0, at any lightness.
|
||||
for v in [0.0, 0.25, 0.5, 1.0] {
|
||||
assert_eq!(rgb_to_hsl([v, v, v]), [0.0, 0.0, v]);
|
||||
}
|
||||
// Black and white keep any hue and saturation they are given.
|
||||
assert_eq!(hsl_to_rgb([200.0, 0.7, 0.0]), [0.0, 0.0, 0.0]);
|
||||
assert_eq!(hsl_to_rgb([200.0, 0.7, 1.0]), [1.0, 1.0, 1.0]);
|
||||
// A color past the gamut that gives a negative saturation turns its hue by 180°.
|
||||
let [h, s, _] = rgb_to_hsl([1.2, 1.5, 1.4]);
|
||||
assert!(s > 0.0 && (h - (160.0 + 180.0)).abs() < 1e-3, "{h} {s}");
|
||||
// A huge hue wraps before the channels are worked out: 10,000,000,000° is 280°.
|
||||
let (huge, wrapped) = (hsl_to_rgb([10_000_000_000.0, 1.0, 0.5]), hsl_to_rgb([280.0, 1.0, 0.5]));
|
||||
assert!((0..3).all(|i| (huge[i] - wrapped[i]).abs() < 1e-6), "{huge:?} {wrapped:?}");
|
||||
}
|
||||
|
||||
/// The 216 web colors go to HSL and back to the same 8-bit color.
|
||||
#[test]
|
||||
fn hsl_roundtrip() {
|
||||
let steps = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff];
|
||||
for r in steps {
|
||||
for g in steps {
|
||||
for b in steps {
|
||||
let c = Color::rgb8(r, g, b);
|
||||
let [h, s, l] = rgb_to_hsl(c.to_rgb_uncalibrated());
|
||||
assert!((0.0..360.0).contains(&h) && (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&l), "{}", c.to_hex());
|
||||
let back = hsl_to_rgb([h, s, l]).map(|v| (v * 255.0).round() as u8);
|
||||
assert_eq!(back, [r, g, b], "{}", c.to_hex());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_conversions() {
|
||||
assert_eq!(Color::cmyk(0.0, 0.0, 0.0, 1.0).to_rgb_uncalibrated(), [0.0, 0.0, 0.0]);
|
||||
|
||||
@@ -99,18 +99,24 @@ pub fn builtin_library(id: &str) -> Option<Arc<SwatchLibrary>> {
|
||||
|
||||
// ---------- colour construction ----------
|
||||
|
||||
/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped.
|
||||
/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. A linear channel below
|
||||
/// −0.0031308 is encoded with the curve's sign turned, as CSS Color 4's extended sRGB does
|
||||
/// (<https://www.w3.org/TR/css-color-4/#color-conversion-code>).
|
||||
pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
|
||||
oklab_to_linear_srgb(l, a, b).map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) })
|
||||
}
|
||||
|
||||
/// Linear sRGB of OKLab `(l, a, b)`, unclamped.
|
||||
pub(crate) fn oklab_to_linear_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
|
||||
let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
|
||||
let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
|
||||
let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
|
||||
let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
|
||||
let lin = [
|
||||
[
|
||||
4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3,
|
||||
-1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3,
|
||||
-0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3,
|
||||
];
|
||||
lin.map(|v| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 })
|
||||
]
|
||||
}
|
||||
|
||||
/// OKLab `[l, a, b]` of a colour's display RGB.
|
||||
@@ -118,11 +124,13 @@ pub fn to_oklab(c: &Color) -> [f64; 3] {
|
||||
srgb_to_oklab(c.to_rgb_uncalibrated())
|
||||
}
|
||||
|
||||
/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded).
|
||||
/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). A channel below −0.04045 is decoded
|
||||
/// with the curve's sign turned, as CSS Color 4's extended sRGB does
|
||||
/// (<https://www.w3.org/TR/css-color-4/#color-conversion-code>).
|
||||
pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] {
|
||||
let [r, g, b] = rgb.map(|v| {
|
||||
let v = f64::from(v);
|
||||
if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
if v.abs() <= 0.040_45 { v / 12.92 } else { v.signum() * ((v.abs() + 0.055) / 1.055).powf(2.4) }
|
||||
});
|
||||
let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt();
|
||||
let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt();
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! OKLCH, the polar form of Oklab, as CSS Color 4 defines it
|
||||
//! (<https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch>): lightness L from 0 to 1, chroma
|
||||
//! C (CSS reads 100% as 0.4) and hue H in degrees from the positive `a` axis. The conversions take
|
||||
//! and give gamma-encoded sRGB through the Oklab matrices of [`crate::libraries`].
|
||||
|
||||
use crate::libraries::{oklab_to_linear_srgb, oklab_to_srgb, srgb_to_oklab};
|
||||
|
||||
/// The chroma CSS reads as 100%.
|
||||
pub const CHROMA_FULL: f64 = 0.4;
|
||||
|
||||
/// Chroma at or below which the hue is powerless (CSS Color 4's ε); [`to_oklch`] gives hue 0 there.
|
||||
pub const POWERLESS_CHROMA: f64 = 0.000_004;
|
||||
|
||||
/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
|
||||
const GAMUT_SLACK: f64 = 1e-4;
|
||||
|
||||
/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
|
||||
/// are. The hue is in 0..360, and 0 while the chroma is powerless.
|
||||
pub fn to_oklch(rgb: [f32; 3]) -> [f64; 3] {
|
||||
let [l, a, b] = srgb_to_oklab(rgb);
|
||||
let c = a.hypot(b);
|
||||
if c <= POWERLESS_CHROMA {
|
||||
return [l, 0.0, 0.0];
|
||||
}
|
||||
[l, c, b.atan2(a).to_degrees().rem_euclid(360.0)]
|
||||
}
|
||||
|
||||
/// sRGB (gamma encoded) of OKLCH `(l, c, h°)`, unclamped.
|
||||
pub fn oklch_to_srgb(l: f64, c: f64, h: f64) -> [f64; 3] {
|
||||
let (sin, cos) = h.to_radians().sin_cos();
|
||||
oklab_to_srgb(l, c * cos, c * sin)
|
||||
}
|
||||
|
||||
/// Whether sRGB `rgb` lies inside the sRGB gamut.
|
||||
pub fn in_srgb(rgb: [f64; 3]) -> bool {
|
||||
rgb.iter().all(|v| (-GAMUT_SLACK..=1.0 + GAMUT_SLACK).contains(v))
|
||||
}
|
||||
|
||||
/// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white.
|
||||
pub fn max_chroma(l: f64, h: f64) -> f64 {
|
||||
largest_fitting_chroma(l, h, f64::INFINITY)
|
||||
}
|
||||
|
||||
/// The largest chroma no more than `limit` that sRGB holds at lightness `l` and hue `h°`: 0 at or
|
||||
/// outside black and white.
|
||||
///
|
||||
/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
|
||||
/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
|
||||
/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
|
||||
/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
|
||||
/// search finds each such chroma between the cubic's turning points and takes the largest one that
|
||||
/// fits.
|
||||
fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
|
||||
if !(l > 0.0 && l < 1.0) || !h.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
let top = limit.min(0.5);
|
||||
if top <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h));
|
||||
if fits(top) {
|
||||
return top;
|
||||
}
|
||||
let (sin, cos) = h.to_radians().sin_cos();
|
||||
let lin = |c: f64| oklab_to_linear_srgb(l, c * cos, c * sin);
|
||||
// The linear channels at chromas 0, s, 2s and 3s give each cubic's coefficients in t = c / s.
|
||||
let s = top / 3.0;
|
||||
let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
|
||||
let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
|
||||
let mut ends = vec![0.0];
|
||||
for ch in 0..3 {
|
||||
let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
|
||||
let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
|
||||
let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
|
||||
let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
|
||||
// The cubic rises or falls on each stretch between its turning points.
|
||||
let mut cuts = vec![0.0, 3.0];
|
||||
cuts.extend(turning_points(3.0 * k[3], 2.0 * k[2], k[1]).into_iter().filter(|t| *t > 0.0 && *t < 3.0));
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
ends.extend(cuts.iter().map(|t| t * s));
|
||||
for w in cuts.windows(2) {
|
||||
for bound in bounds {
|
||||
let (mut a, mut b) = (w[0], w[1]);
|
||||
let fa = p(a) - bound;
|
||||
if fa * (p(b) - bound) > 0.0 {
|
||||
continue;
|
||||
}
|
||||
for _ in 0..60 {
|
||||
let mid = (a + b) / 2.0;
|
||||
if (p(mid) - bound) * fa > 0.0 { a = mid } else { b = mid }
|
||||
}
|
||||
ends.extend([a * s, b * s]);
|
||||
}
|
||||
}
|
||||
}
|
||||
ends.sort_by(|a, b| b.total_cmp(a));
|
||||
ends.into_iter().flat_map(|c| [c, c - 1e-9]).find(|c| (0.0..=top).contains(c) && fits(*c)).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// The real roots of `a t² + b t + c`.
|
||||
fn turning_points(a: f64, b: f64, c: f64) -> Vec<f64> {
|
||||
if a.abs() < 1e-15 {
|
||||
return if b.abs() < 1e-15 { Vec::new() } else { vec![-c / b] };
|
||||
}
|
||||
let disc = b * b - 4.0 * a * c;
|
||||
if disc < 0.0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let r = disc.sqrt();
|
||||
vec![(-b - r) / (2.0 * a), (-b + r) / (2.0 * a)]
|
||||
}
|
||||
|
||||
/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
|
||||
/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
|
||||
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
|
||||
pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
|
||||
let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
|
||||
let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
|
||||
let h = if h.is_finite() { h } else { 0.0 };
|
||||
let exact = oklch_to_srgb(l, c, h);
|
||||
let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
|
||||
(rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn eight(rgb: [f32; 3]) -> [u8; 3] {
|
||||
rgb.map(|v| (v * 255.0).round() as u8)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn red_has_the_oklch_of_the_oklab_matrices_and_converts_back() {
|
||||
let [l, c, h] = to_oklch([1.0, 0.0, 0.0]);
|
||||
assert!((l - 0.6280).abs() < 5e-5 && (c - 0.2577).abs() < 5e-5 && (h - 29.23).abs() < 5e-3, "{l} {c} {h}");
|
||||
let (rgb, lowered) = from_oklch(l, c, h);
|
||||
assert_eq!((eight(rgb), lowered), ([255, 0, 0], false));
|
||||
}
|
||||
|
||||
/// CSS Color 4's examples convert to the hue its oklab() and oklch() forms give.
|
||||
#[test]
|
||||
fn the_polar_form_matches_the_css_examples() {
|
||||
for ([l, a, b], [cl, cc, ch]) in
|
||||
[([0.40101, 0.1147, 0.0453], [0.40101, 0.12332, 21.555]), ([0.65125, -0.0320, 0.1274], [0.65125, 0.13138, 104.097])]
|
||||
{
|
||||
let rgb = oklab_to_srgb(l, a, b).map(|v| v as f32);
|
||||
let [ol, oc, oh] = to_oklch(rgb);
|
||||
assert!((ol - cl).abs() < 1e-4 && (oc - cc).abs() < 1e-4 && (oh - ch).abs() < 0.05, "{ol} {oc} {oh}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_216_web_colors_round_trip() {
|
||||
let steps = [0u8, 0x33, 0x66, 0x99, 0xcc, 0xff];
|
||||
for r in steps {
|
||||
for g in steps {
|
||||
for b in steps {
|
||||
let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
|
||||
let [l, c, h] = to_oklch(rgb);
|
||||
assert_eq!(eight(from_oklch(l, c, h).0), [r, g, b], "{l} {c} {h}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grays_have_no_chroma_and_hue_zero() {
|
||||
for v in [0.0, 0.5, 1.0] {
|
||||
let [_, c, h] = to_oklch([v, v, v]);
|
||||
assert!(c <= POWERLESS_CHROMA && h == 0.0, "{c} {h}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A chroma past the gamut gives a color inside it with the same lightness and hue, and says so.
|
||||
#[test]
|
||||
fn a_chroma_past_the_gamut_is_lowered_keeping_lightness_and_hue() {
|
||||
let (l, h) = (0.7, 150.0);
|
||||
let max = max_chroma(l, h);
|
||||
assert!(max > 0.05 && max < CHROMA_FULL, "{max}");
|
||||
assert!(in_srgb(oklch_to_srgb(l, max, h)) && !in_srgb(oklch_to_srgb(l, max + 1e-3, h)));
|
||||
let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
|
||||
assert!(lowered);
|
||||
let [ol, oc, oh] = to_oklch(rgb);
|
||||
assert!((ol - l).abs() < 2e-3 && (oh - h).abs() < 1.0 && (oc - max).abs() < 2e-3, "{ol} {oc} {oh}");
|
||||
assert!(!from_oklch(l, max * 0.5, h).1);
|
||||
}
|
||||
|
||||
/// At the lightness and hue of blue the ray leaves sRGB and comes back at blue itself, so the
|
||||
/// largest chroma is blue's, and a chroma past it gives blue.
|
||||
#[test]
|
||||
fn the_largest_chroma_at_blues_hue_is_blues() {
|
||||
let [l, c, h] = to_oklch([0.0, 0.0, 1.0]);
|
||||
let max = max_chroma(l, h);
|
||||
assert!((max - c).abs() < 1e-4 && in_srgb(oklch_to_srgb(l, max, h)), "{max} {c}");
|
||||
let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
|
||||
assert_eq!((eight(rgb), lowered), ([0, 0, 255], true));
|
||||
// A chroma between the two stretches takes the end of the first one, inside sRGB.
|
||||
let (rgb, lowered) = from_oklch(l, 0.29, h);
|
||||
let [_, gc, _] = to_oklch(rgb);
|
||||
assert!(lowered && gc < 0.27 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
|
||||
// A hue just past blue's: a narrow second stretch ends just below the line from black to blue.
|
||||
let (l, h) = (0.44, 264.06);
|
||||
let max = max_chroma(l, h);
|
||||
assert!(max > 0.304 && max < 0.305 && in_srgb(oklch_to_srgb(l, max, h)), "{max}");
|
||||
let [_, got, _] = to_oklch(from_oklch(l, 0.35, h).0);
|
||||
assert!(got > 0.303, "{got}");
|
||||
// A darker blue on the line from black to blue.
|
||||
let [l, c, h] = to_oklch([0.0, 0.0, 0.25]);
|
||||
assert!((max_chroma(l, h) - c).abs() < 1e-4, "{} {c}", max_chroma(l, h));
|
||||
}
|
||||
|
||||
/// Just below blue's lightness the line from black to blue passes a chroma of 0.3125, where a
|
||||
/// search from 0 to 0.5 lands first. A chroma asked for below that line still gives a color
|
||||
/// inside sRGB with the lightness and hue asked for.
|
||||
#[test]
|
||||
fn a_chroma_below_the_line_from_black_to_blue_stays_inside_srgb() {
|
||||
let [bl, bc, h] = to_oklch([0.0, 0.0, 1.0]);
|
||||
let l = bl * 0.3125 / bc;
|
||||
let (rgb, lowered) = from_oklch(l, 0.29, h);
|
||||
let [gl, gc, gh] = to_oklch(rgb);
|
||||
assert!(lowered && gc < 0.29 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
|
||||
assert!((gl - l).abs() < 2e-3 && (gh - h).abs() < 1.0, "{gl} {gh}");
|
||||
}
|
||||
|
||||
/// sRGB channels below 0 go through the transfer curve with its sign turned, as CSS Color 4's
|
||||
/// extended sRGB does, in both directions.
|
||||
#[test]
|
||||
fn negative_channels_use_the_signed_transfer_curve() {
|
||||
let linear = -((0.5_f64 + 0.055) / 1.055).powf(2.4);
|
||||
let [l, c, _] = to_oklch([-0.5; 3]);
|
||||
assert!((l - linear.cbrt()).abs() < 1e-4 && c <= POWERLESS_CHROMA, "{l} {c}");
|
||||
for v in oklch_to_srgb(linear.cbrt(), 0.0, 0.0) {
|
||||
assert!((v + 0.5).abs() < 1e-4, "{v}");
|
||||
}
|
||||
// Small values near 0 keep the straight part of the curve.
|
||||
let [l, _, _] = to_oklch([-0.01; 3]);
|
||||
assert!((l - (-0.01_f64 / 12.92).cbrt()).abs() < 1e-4, "{l}");
|
||||
}
|
||||
|
||||
/// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
|
||||
/// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
|
||||
/// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
|
||||
#[test]
|
||||
fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
|
||||
let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
|
||||
assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
|
||||
for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
|
||||
for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
|
||||
let max = max_chroma(l, h);
|
||||
assert!(in_srgb(oklch_to_srgb(l, max, h)) && max >= scan(l, h), "L {l} H {h}: {max} < {}", scan(l, h));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_white_and_bad_numbers_hold_no_chroma() {
|
||||
assert_eq!(max_chroma(0.0, 30.0), 0.0);
|
||||
assert_eq!(max_chroma(1.0, 30.0), 0.0);
|
||||
assert_eq!(max_chroma(f64::NAN, 30.0), 0.0);
|
||||
assert_eq!(max_chroma(0.5, f64::INFINITY), 0.0);
|
||||
assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
|
||||
assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
|
||||
}
|
||||
}
|
||||
+96
-455
@@ -6,6 +6,8 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub use craft_cms::palette::css_property;
|
||||
use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteError, PaletteGroup, PaletteSwatch};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary};
|
||||
@@ -83,18 +85,93 @@ struct NativeFile {
|
||||
|
||||
const NATIVE_FORMAT: &str = "vcswatches";
|
||||
const GPL_HEADER: &str = "GIMP Palette";
|
||||
const GPL_GROUP: &str = "# Group:";
|
||||
const ASE_SIGNATURE: &[u8] = b"ASEF";
|
||||
const ASE_GROUP_START: u16 = 0xC001;
|
||||
const ASE_GROUP_END: u16 = 0xC002;
|
||||
const ASE_COLOR: u16 = 0x0001;
|
||||
/// The most colors and groups read from one `.ase` file.
|
||||
const ASE_MAX_ENTRIES: usize = 100_000;
|
||||
/// The most UTF-16 code units of a name that are kept.
|
||||
const ASE_MAX_NAME: usize = 1024;
|
||||
const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
|
||||
const ACB_SIGNATURE: &[u8] = b"8BCB";
|
||||
const ACB_CUT_SHORT: &str = "the color book is cut short";
|
||||
#[cfg(test)]
|
||||
const ASE_GROUP_START: u16 = 0xC001;
|
||||
#[cfg(test)]
|
||||
const ASE_MAX_ENTRIES: usize = 100_000;
|
||||
|
||||
fn color_to_cms(c: Color) -> PaletteColor {
|
||||
match c {
|
||||
Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b },
|
||||
Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k },
|
||||
Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b },
|
||||
Color::Gray { k } => PaletteColor::Gray { k },
|
||||
}
|
||||
}
|
||||
|
||||
fn color_from_cms(c: PaletteColor) -> Color {
|
||||
match c {
|
||||
PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b),
|
||||
PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k),
|
||||
PaletteColor::Lab { l, a, b } => Color::lab(l, a, b),
|
||||
PaletteColor::Gray { k } => Color::gray(k),
|
||||
}
|
||||
}
|
||||
|
||||
// GPL must retain the app-managed display conversion; ASE preserves authoring models.
|
||||
fn swatches_to_cms(list: &[Swatch], rgb_only: bool) -> Vec<PaletteSwatch> {
|
||||
list.iter()
|
||||
.filter_map(|w| {
|
||||
w.paint.color().map(|c| PaletteSwatch {
|
||||
name: w.name.clone(),
|
||||
color: if rgb_only {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
PaletteColor::rgb8(r, g, b)
|
||||
} else {
|
||||
color_to_cms(c)
|
||||
},
|
||||
global: w.global,
|
||||
spot: w.spot,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn swatches_from_cms(list: Vec<PaletteSwatch>) -> Vec<Swatch> {
|
||||
list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect()
|
||||
}
|
||||
|
||||
fn to_cms_palette(lib: &SwatchLibrary, rgb_only: bool) -> Palette {
|
||||
Palette {
|
||||
name: lib.name.clone(),
|
||||
swatches: swatches_to_cms(&lib.swatches, rgb_only),
|
||||
groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches, rgb_only) }).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_cms_palette(p: Palette) -> SwatchLibrary {
|
||||
SwatchLibrary {
|
||||
name: p.name,
|
||||
swatches: swatches_from_cms(p.swatches),
|
||||
groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps structured shared palette errors to VectorCraft's translatable messages.
|
||||
fn palette_error(err: PaletteError) -> String {
|
||||
match err {
|
||||
PaletteError::UnsupportedFormat => "not a supported palette (.gpl, .ase, or .acb)".into(),
|
||||
PaletteError::TruncatedAse => "the swatch exchange file is cut short".into(),
|
||||
PaletteError::TruncatedAcb => "the color book is cut short".into(),
|
||||
PaletteError::AseWriteEntryLimit { limit, entries } => format!(
|
||||
"VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}",
|
||||
ASE_MAX_ENTRIES = limit
|
||||
),
|
||||
PaletteError::AseReadEntryLimit { limit } => {
|
||||
format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups", ASE_MAX_ENTRIES = limit)
|
||||
}
|
||||
PaletteError::AseBlockCount => "too many swatch exchange blocks".into(),
|
||||
PaletteError::AseBlockLength => "a swatch exchange block is too long".into(),
|
||||
PaletteError::AseNameLength => "a swatch exchange name is too long".into(),
|
||||
PaletteError::AseVersion { major, minor } => format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"),
|
||||
PaletteError::AcbVersion { version } => format!("color book version {version} isn't supported (only 1)"),
|
||||
PaletteError::AcbEntryLimit { limit } => format!("the color book holds more than {ASE_MAX_ENTRIES} colors", ASE_MAX_ENTRIES = limit),
|
||||
PaletteError::AcbColorSpace { space: other } => format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)"),
|
||||
PaletteError::AcbNameBytes { limit } => format!("the color book's names take more than {} MB", limit >> 20),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document)
|
||||
/// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid
|
||||
@@ -113,8 +190,12 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result<Vec<u8>, Stri
|
||||
let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library };
|
||||
serde_json::to_string_pretty(&file).unwrap_or_default()
|
||||
}
|
||||
PaletteFormat::Gpl => write_gpl(lib),
|
||||
PaletteFormat::Ase => return write_ase(lib),
|
||||
PaletteFormat::Gpl => {
|
||||
return cms_palette::write_palette_typed(&to_cms_palette(lib, true), cms_palette::PaletteFormat::Gpl).map_err(palette_error);
|
||||
}
|
||||
PaletteFormat::Ase => {
|
||||
return cms_palette::write_palette_typed(&to_cms_palette(lib, false), cms_palette::PaletteFormat::Ase).map_err(palette_error);
|
||||
}
|
||||
PaletteFormat::Css => write_css(lib, keep),
|
||||
};
|
||||
Ok(text.into_bytes())
|
||||
@@ -125,49 +206,6 @@ fn one_line(s: &str) -> String {
|
||||
s.split(['\n', '\r', '\t']).collect::<Vec<_>>().join(" ").trim().to_string()
|
||||
}
|
||||
|
||||
fn write_gpl(lib: &SwatchLibrary) -> String {
|
||||
let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name));
|
||||
let colors = |out: &mut String, list: &[Swatch]| {
|
||||
for w in list {
|
||||
if let Some(c) = w.paint.color() {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name)));
|
||||
}
|
||||
}
|
||||
};
|
||||
colors(&mut out, &lib.swatches);
|
||||
for g in &lib.groups {
|
||||
out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name)));
|
||||
colors(&mut out, &g.swatches);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as
|
||||
/// hyphens, other characters an identifier can't hold escaped with a backslash.
|
||||
pub fn css_property(name: &str) -> String {
|
||||
let mut out = String::from("--");
|
||||
for word in name.split_whitespace() {
|
||||
if out.len() > 2 {
|
||||
out.push('-');
|
||||
}
|
||||
for ch in word.chars().flat_map(char::to_lowercase) {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() {
|
||||
out.push(ch);
|
||||
} else if ch.is_ascii_graphic() {
|
||||
out.push('\\');
|
||||
out.push(ch);
|
||||
} else {
|
||||
out.push_str(&format!("\\{:x} ", ch as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.len() == 2 {
|
||||
out.push_str("swatch");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity).
|
||||
fn css_color(c: &Color, opacity: f32) -> String {
|
||||
let [r, g, b, a] = c.to_rgba8(opacity);
|
||||
@@ -265,108 +303,12 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// `.ase`, as [`read_ase`] reads it: version 1.0, the ungrouped colors, then each color group as a
|
||||
/// group start (its name), its colors and a group end, also for a group without colors. A color is
|
||||
/// written in its own model: RGB, CMYK and gray components from 0 to 1 (gray as a level, 1 is
|
||||
/// white), Lab lightness as a fraction of 100 and a and b from −128 to 127. Components are clamped
|
||||
/// to those ranges, and a component that isn't a finite number is written as 0. The color type is
|
||||
/// 1 for a spot color, 0 for another global color and 2 for a process color.
|
||||
///
|
||||
/// A swatch exchange file holds solid colors only: gradients, patterns and None are left out, and
|
||||
/// a tint swatch is written as the color it shows, a process color without its link to its base.
|
||||
/// The file has no library name ([`read_ase`] names a library after its file). More than
|
||||
/// [`ASE_MAX_ENTRIES`] colors and groups is an error.
|
||||
fn write_ase(lib: &SwatchLibrary) -> Result<Vec<u8>, String> {
|
||||
let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count();
|
||||
let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::<usize>();
|
||||
if entries > ASE_MAX_ENTRIES {
|
||||
return Err(format!(
|
||||
"VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}"
|
||||
));
|
||||
}
|
||||
let mut body = vec![];
|
||||
let mut blocks = put_ase_colors(&mut body, &lib.swatches)?;
|
||||
for g in &lib.groups {
|
||||
let mut name = vec![];
|
||||
put_ase_name(&mut name, &g.name)?;
|
||||
put_ase_block(&mut body, ASE_GROUP_START, &name)?;
|
||||
blocks += 2 + put_ase_colors(&mut body, &g.swatches)?;
|
||||
put_ase_block(&mut body, ASE_GROUP_END, &[])?;
|
||||
}
|
||||
let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?;
|
||||
let mut out = ASE_SIGNATURE.to_vec();
|
||||
out.extend(1u16.to_be_bytes());
|
||||
out.extend(0u16.to_be_bytes());
|
||||
out.extend(blocks.to_be_bytes());
|
||||
out.extend(body);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The color blocks of the solid colors in `list` → how many were written.
|
||||
fn put_ase_colors(out: &mut Vec<u8>, list: &[Swatch]) -> Result<usize, String> {
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 };
|
||||
let mut n = 0;
|
||||
for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) {
|
||||
let mut body = vec![];
|
||||
put_ase_name(&mut body, &w.name)?;
|
||||
let (model, values): (&[u8; 4], Vec<f32>) = match color {
|
||||
Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]),
|
||||
Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]),
|
||||
Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]),
|
||||
Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]),
|
||||
};
|
||||
body.extend(model);
|
||||
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
|
||||
let kind: u16 = if w.spot {
|
||||
1
|
||||
} else if w.global {
|
||||
0
|
||||
} else {
|
||||
2
|
||||
};
|
||||
body.extend(kind.to_be_bytes());
|
||||
put_ase_block(out, ASE_COLOR, &body)?;
|
||||
n += 1;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// A block: its type, the length of its body and the body.
|
||||
fn put_ase_block(out: &mut Vec<u8>, kind: u16, body: &[u8]) -> Result<(), String> {
|
||||
let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?;
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend(len.to_be_bytes());
|
||||
out.extend_from_slice(body);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included,
|
||||
/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units
|
||||
/// is cut before the character that would pass that limit.
|
||||
fn put_ase_name(out: &mut Vec<u8>, name: &str) -> Result<(), String> {
|
||||
let mut units: Vec<u16> = vec![];
|
||||
for c in name.chars().filter(|&c| c != '\0') {
|
||||
let mut buf = [0; 2];
|
||||
let encoded = c.encode_utf16(&mut buf);
|
||||
if units.len() + encoded.len() > ASE_MAX_NAME {
|
||||
break;
|
||||
}
|
||||
units.extend_from_slice(encoded);
|
||||
}
|
||||
units.push(0);
|
||||
let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?;
|
||||
out.extend(count.to_be_bytes());
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the
|
||||
/// file doesn't.
|
||||
pub fn read(text: &str, name: &str) -> Result<SwatchLibrary, String> {
|
||||
let text = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if text.starts_with(GPL_HEADER) {
|
||||
return Ok(read_gpl(text, name));
|
||||
return cms_palette::read_palette_typed(text.as_bytes(), name).map(from_cms_palette).map_err(palette_error);
|
||||
}
|
||||
if text.starts_with('{') {
|
||||
let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?;
|
||||
@@ -391,11 +333,8 @@ pub fn sniff(text: &str) -> bool {
|
||||
/// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or
|
||||
/// `.gpl` library ([`read`]). `name` names it when the file doesn't.
|
||||
pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
|
||||
if bytes.starts_with(ASE_SIGNATURE) {
|
||||
return read_ase(bytes, name);
|
||||
}
|
||||
if bytes.starts_with(ACB_SIGNATURE) {
|
||||
return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e });
|
||||
if bytes.starts_with(ASE_SIGNATURE) || bytes.starts_with(ACB_SIGNATURE) {
|
||||
return cms_palette::read_palette_typed(bytes, name).map(from_cms_palette).map_err(palette_error);
|
||||
}
|
||||
read(&String::from_utf8_lossy(bytes), name)
|
||||
}
|
||||
@@ -409,303 +348,5 @@ pub fn sniff_bytes(bytes: &[u8]) -> bool {
|
||||
|| sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)))
|
||||
}
|
||||
|
||||
/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and
|
||||
/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are
|
||||
/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets
|
||||
/// a number ([`UniqueNames`]).
|
||||
fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
|
||||
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
for line in text.lines().skip(1) {
|
||||
let line = line.trim();
|
||||
if let Some(g) = line.strip_prefix(GPL_GROUP) {
|
||||
lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] });
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = line.strip_prefix("Name:") {
|
||||
if !n.trim().is_empty() {
|
||||
lib.name = n.trim().to_string();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped.
|
||||
let words: Vec<&str> = line.split_whitespace().collect();
|
||||
let rgb: Vec<u8> = words.iter().take(3).map_while(|v| v.parse().ok()).collect();
|
||||
let [r, g, b] = rgb[..] else { continue };
|
||||
let rest = words[3..].join(" ");
|
||||
let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest };
|
||||
let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false };
|
||||
match lib.groups.last_mut() {
|
||||
Some(grp) => grp.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
}
|
||||
}
|
||||
lib
|
||||
}
|
||||
|
||||
/// `.ase`, from public descriptions of the format: the layout from
|
||||
/// <https://www.selapa.net/swatches/colors/fileformats.php>, the component ranges from
|
||||
/// <https://github.com/nsfmc/swatch>. After the signature come, big-endian, a `u16` major (1) and
|
||||
/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and
|
||||
/// the body. A group start's body is a name. A color's body is a name, a four-character model
|
||||
/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16`
|
||||
/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a
|
||||
/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness
|
||||
/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero
|
||||
/// included, then the units.
|
||||
///
|
||||
/// Color groups become groups: a group start inside an open group ends that group, and a group
|
||||
/// left open ends with the file. Blocks of other types and colors in other models are skipped.
|
||||
/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or
|
||||
/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than
|
||||
/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error.
|
||||
fn read_ase(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
|
||||
let mut data = AseData(bytes);
|
||||
data.bytes(ASE_SIGNATURE.len())?;
|
||||
let (major, minor) = (data.u16()?, data.u16()?);
|
||||
if major != 1 {
|
||||
return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"));
|
||||
}
|
||||
let blocks = data.u32()?;
|
||||
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
let (mut in_group, mut entries) = (false, 0usize);
|
||||
for _ in 0..blocks {
|
||||
let kind = data.u16()?;
|
||||
let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX);
|
||||
let mut body = AseData(data.bytes(len)?);
|
||||
if matches!(kind, ASE_GROUP_START | ASE_COLOR) {
|
||||
entries += 1;
|
||||
if entries > ASE_MAX_ENTRIES {
|
||||
return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups"));
|
||||
}
|
||||
}
|
||||
match kind {
|
||||
ASE_GROUP_START => {
|
||||
lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] });
|
||||
in_group = true;
|
||||
}
|
||||
ASE_GROUP_END => in_group = false,
|
||||
ASE_COLOR => {
|
||||
let Some(mut w) = ase_swatch(&mut body)? else { continue };
|
||||
w.name = names.unique(std::mem::take(&mut w.name));
|
||||
match lib.groups.last_mut().filter(|_| in_group) {
|
||||
Some(g) => g.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
}
|
||||
}
|
||||
// Other blocks are skipped.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(lib)
|
||||
}
|
||||
|
||||
/// `.acb` (a color book, read only), from public descriptions of the format: after the signature
|
||||
/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description
|
||||
/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0
|
||||
/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its
|
||||
/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab
|
||||
/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of
|
||||
/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand
|
||||
/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot
|
||||
/// or process colors (a book without it is a spot color book).
|
||||
///
|
||||
/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a
|
||||
/// name (the padding of a book's pages) are left out. A version other than 1, a color space other
|
||||
/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error.
|
||||
fn read_acb(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
|
||||
let mut data = AseData(bytes);
|
||||
data.bytes(ACB_SIGNATURE.len())?;
|
||||
let version = data.u16()?;
|
||||
if version != 1 {
|
||||
return Err(format!("color book version {version} isn't supported (only 1)"));
|
||||
}
|
||||
let _book_id = data.u16()?;
|
||||
let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?];
|
||||
let count = usize::from(data.u16()?);
|
||||
if count > ASE_MAX_ENTRIES {
|
||||
return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors"));
|
||||
}
|
||||
let (_page_size, _page_offset) = (data.u16()?, data.u16()?);
|
||||
let space = data.u16()?;
|
||||
let mut colors = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let name = data.acb_string()?;
|
||||
let _code = data.bytes(6)?;
|
||||
let color = match space {
|
||||
0 => {
|
||||
let [r, g, b] = data.array::<3>()?;
|
||||
Color::rgb8(r, g, b)
|
||||
}
|
||||
2 => {
|
||||
let ink = |v: u8| f32::from(255 - v) / 255.0;
|
||||
let [c, m, y, k] = data.array::<4>()?;
|
||||
Color::cmyk(ink(c), ink(m), ink(y), ink(k))
|
||||
}
|
||||
7 => {
|
||||
let [l, a, b] = data.array::<3>()?;
|
||||
Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0)
|
||||
}
|
||||
other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")),
|
||||
};
|
||||
colors.push((name, color));
|
||||
}
|
||||
// Spot colors unless the book says process ones.
|
||||
let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice());
|
||||
let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
// Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of
|
||||
// names taken): a megabyte book of long affixes and many colors came to hundreds of MB.
|
||||
let mut kept = 0usize;
|
||||
for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) {
|
||||
kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len()));
|
||||
if kept > ACB_MAX_NAME_BYTES {
|
||||
return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20));
|
||||
}
|
||||
let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string());
|
||||
lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot });
|
||||
}
|
||||
Ok(lib)
|
||||
}
|
||||
|
||||
/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted
|
||||
/// twice as they are kept twice.
|
||||
const ACB_MAX_NAME_BYTES: usize = 64 << 20;
|
||||
|
||||
/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray.
|
||||
/// Components are clamped to their ranges.
|
||||
fn ase_swatch(body: &mut AseData) -> Result<Option<Swatch>, String> {
|
||||
let name = body.name()?;
|
||||
let unit = |v: f32| v.clamp(0.0, 1.0);
|
||||
let color = match &body.array::<4>()? {
|
||||
b"RGB " => {
|
||||
let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
Color::rgb(unit(r), unit(g), unit(b))
|
||||
}
|
||||
b"CMYK" => {
|
||||
let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?];
|
||||
Color::cmyk(unit(c), unit(m), unit(y), unit(k))
|
||||
}
|
||||
// Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a
|
||||
// value above 1.
|
||||
b"LAB " => {
|
||||
let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 };
|
||||
Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0))
|
||||
}
|
||||
// A gray level (1 is white); a gray color holds its ink.
|
||||
b"Gray" => Color::gray(1.0 - unit(body.f32()?)),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
// Some writers leave the color type out, which makes a process color.
|
||||
let kind = if body.0.len() >= 2 { body.u16()? } else { 2 };
|
||||
// Spot colors are global.
|
||||
let (global, spot) = match kind {
|
||||
0 => (true, false),
|
||||
1 => (true, true),
|
||||
_ => (false, false),
|
||||
};
|
||||
let name = if name.is_empty() { value_name(color) } else { name };
|
||||
Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot }))
|
||||
}
|
||||
|
||||
/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0",
|
||||
/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30").
|
||||
fn value_name(c: Color) -> String {
|
||||
let pct = |v: f32| (v * 100.0).round();
|
||||
let byte = |v: f32| (v * 255.0).round();
|
||||
match c {
|
||||
Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)),
|
||||
Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)),
|
||||
Color::Gray { k } => format!("Gray K={}", pct(k)),
|
||||
// `+ 0.0` turns a rounded -0 into 0.
|
||||
Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// `.ase` data, read field by field; reading past its end is an error.
|
||||
struct AseData<'a>(&'a [u8]);
|
||||
|
||||
impl<'a> AseData<'a> {
|
||||
fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?;
|
||||
self.0 = rest;
|
||||
Ok(head)
|
||||
}
|
||||
fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
let (head, rest) = self.0.split_first_chunk::<N>().ok_or(ASE_CUT_SHORT)?;
|
||||
self.0 = rest;
|
||||
Ok(*head)
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, String> {
|
||||
self.array().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
self.array().map(u32::from_be_bytes)
|
||||
}
|
||||
/// A component; one that isn't a finite number reads as 0.
|
||||
fn f32(&mut self) -> Result<f32, String> {
|
||||
let v = f32::from_be_bytes(self.array()?);
|
||||
Ok(if v.is_finite() { v } else { 0.0 })
|
||||
}
|
||||
/// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units,
|
||||
/// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units
|
||||
/// are kept.
|
||||
fn acb_string(&mut self) -> Result<String, String> {
|
||||
let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX);
|
||||
let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>();
|
||||
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
|
||||
let s = String::from_utf16_lossy(&units);
|
||||
let s = match s.strip_prefix("$$$/") {
|
||||
Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(),
|
||||
None => s,
|
||||
};
|
||||
Ok(s.replace("^R", "®").replace("^C", "©"))
|
||||
}
|
||||
/// A name up to its terminating zero, trimmed. A block that ends before it has no name.
|
||||
fn name(&mut self) -> Result<String, String> {
|
||||
if self.0.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let n = usize::from(self.u16()?);
|
||||
let (units, _) = self.bytes(n * 2)?.as_chunks::<2>();
|
||||
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
|
||||
Ok(String::from_utf16_lossy(&units).trim().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's name as a file gives it, trimmed; "Color Group" when it has none.
|
||||
fn group_name(name: &str) -> String {
|
||||
let name = name.trim();
|
||||
if name.is_empty() { "Color Group".into() } else { name.to_string() }
|
||||
}
|
||||
|
||||
/// The swatch and group names a reader has handed out. Swatches and color groups share one set of
|
||||
/// names, as in a document, and a name already taken gets the first free number ("Black 2").
|
||||
#[derive(Default)]
|
||||
struct UniqueNames {
|
||||
taken: HashSet<String>,
|
||||
/// The last number tried for each repeated name.
|
||||
last: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl UniqueNames {
|
||||
fn unique(&mut self, base: String) -> String {
|
||||
if self.taken.insert(base.clone()) {
|
||||
return base;
|
||||
}
|
||||
// Each pass tries the next number, and only finitely many names are taken.
|
||||
let n = self.last.entry(base.clone()).or_insert(1);
|
||||
loop {
|
||||
*n += 1;
|
||||
let name = format!("{base} {n}");
|
||||
if self.taken.insert(name.clone()) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -2,6 +2,9 @@ use super::*;
|
||||
use crate::{Gradient, GradientPaint, GradientStop};
|
||||
use proptest::prelude::*;
|
||||
|
||||
const ASE_COLOR: u16 = 0x0001;
|
||||
const ASE_GROUP_END: u16 = 0xC002;
|
||||
|
||||
#[test]
|
||||
fn gpl_blank_name_keeps_fallback() {
|
||||
let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n";
|
||||
@@ -700,3 +703,52 @@ proptest! {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_gpl_adapter_uses_app_color_conversion() {
|
||||
let colors = [Color::cmyk(0.2, 0.4, 0.6, 0.1), Color::lab(55.0, 30.0, -25.0), Color::gray(0.3)];
|
||||
let lib = SwatchLibrary {
|
||||
name: "Managed".into(),
|
||||
swatches: colors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &color)| Swatch { name: format!("Color {i}"), paint: Paint::solid(color), global: false, spot: false })
|
||||
.collect(),
|
||||
groups: vec![],
|
||||
};
|
||||
let mut expected = String::from("GIMP Palette\nName: Managed\nColumns: 0\n#\n");
|
||||
for (i, color) in colors.iter().enumerate() {
|
||||
let [r, g, b, _] = color.to_rgba8(1.0);
|
||||
expected.push_str(&format!("{r:3} {g:3} {b:3}\tColor {i}\n"));
|
||||
}
|
||||
assert_eq!(write(&lib, PaletteFormat::Gpl).unwrap(), expected.as_bytes());
|
||||
assert!(to_cms_palette(&lib, true).swatches.iter().all(|w| matches!(w.color, PaletteColor::Rgb { .. })));
|
||||
assert!(matches!(to_cms_palette(&lib, false).swatches[0].color, PaletteColor::Cmyk { .. }));
|
||||
assert!(matches!(to_cms_palette(&lib, false).swatches[1].color, PaletteColor::Lab { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_palette_errors_keep_app_wording() {
|
||||
let cases = [
|
||||
(PaletteError::UnsupportedFormat, "not a supported palette (.gpl, .ase, or .acb)"),
|
||||
(PaletteError::TruncatedAse, "the swatch exchange file is cut short"),
|
||||
(PaletteError::TruncatedAcb, "the color book is cut short"),
|
||||
(
|
||||
PaletteError::AseWriteEntryLimit { limit: 3, entries: 4 },
|
||||
"VectorCraft reads at most 3 colors and groups from a swatch exchange file, and this library has 4",
|
||||
),
|
||||
(PaletteError::AseReadEntryLimit { limit: 3 }, "the swatch exchange file holds more than 3 colors and groups"),
|
||||
(PaletteError::AseBlockCount, "too many swatch exchange blocks"),
|
||||
(PaletteError::AseBlockLength, "a swatch exchange block is too long"),
|
||||
(PaletteError::AseNameLength, "a swatch exchange name is too long"),
|
||||
(PaletteError::AseVersion { major: 2, minor: 3 }, "swatch exchange version 2.3 isn't supported (only 1.x)"),
|
||||
(PaletteError::AcbVersion { version: 2 }, "color book version 2 isn't supported (only 1)"),
|
||||
(PaletteError::AcbEntryLimit { limit: 3 }, "the color book holds more than 3 colors"),
|
||||
(PaletteError::AcbColorSpace { space: 5 }, "color books in color space 5 aren't supported (only RGB, CMYK and Lab)"),
|
||||
(PaletteError::AcbNameBytes { limit: 64 << 20 }, "the color book's names take more than 64 MB"),
|
||||
];
|
||||
for (error, expected) in cases {
|
||||
assert_eq!(palette_error(error), expected);
|
||||
}
|
||||
assert_eq!(read_bytes(b"8BCB\0\x01\0\0\0\0\0\x03\0x", "fallback").unwrap_err(), "the color book is cut short");
|
||||
}
|
||||
@@ -1156,6 +1156,17 @@ impl Lerp {
|
||||
(NodeKind::PlacedDocument(o), NodeKind::PlacedDocument(x), NodeKind::PlacedDocument(y)) => o.xf = lerp_affine(x.xf, y.xf, t),
|
||||
_ => {}
|
||||
}
|
||||
// Between distorted images, each step's corners lie between the keys' corners. A
|
||||
// step whose corners would fold keeps the nearer key's.
|
||||
if (a.is_distorted_image() || b.is_distorted_image())
|
||||
&& let (Some(qa), Some(qb)) = (a.image_corners(), b.image_corners())
|
||||
{
|
||||
let near = if t < 0.5 { qa } else { qb };
|
||||
if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() {
|
||||
// The nearer key's corners passed the same check when it was distorted.
|
||||
let _ = n.set_image_corners(near);
|
||||
}
|
||||
}
|
||||
n.extras_mut().mask = None;
|
||||
n
|
||||
}
|
||||
@@ -2297,6 +2308,43 @@ mod tests {
|
||||
assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0));
|
||||
}
|
||||
|
||||
/// A step between two distorted images has its corners between the keys' corners.
|
||||
#[test]
|
||||
fn steps_between_distorted_images_have_corners_between_theirs() {
|
||||
let image = |q: [(f64, f64); 4]| {
|
||||
let im = crate::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let mut n = Node::new(NodeId(1), NodeKind::Image(Box::new(im)));
|
||||
n.set_image_corners(q.map(|(x, y)| Point::new(x, y))).unwrap();
|
||||
n
|
||||
};
|
||||
let a = image([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
let b = image([(200.0, 0.0), (300.0, 0.0), (280.0, 100.0), (220.0, 100.0)]);
|
||||
let mid = Lerp::new(&a, &b, (None, None)).at(0.5);
|
||||
let want = [(120.0, 0.0), (180.0, 0.0), (190.0, 100.0), (110.0, 100.0)];
|
||||
let got = mid.image_corners().unwrap();
|
||||
for (g, (x, y)) in got.iter().zip(want) {
|
||||
assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?}");
|
||||
}
|
||||
// Toward a key flipped left to right, the middle step's corners would meet: each step
|
||||
// there keeps the nearer key's corners, whether that key is distorted or not.
|
||||
let flipped = image([(60.0, 0.0), (40.0, 0.0), (0.0, 100.0), (100.0, 100.0)]);
|
||||
let mirror = image([(100.0, 0.0), (0.0, 0.0), (0.0, 100.0), (100.0, 100.0)]);
|
||||
assert!(!mirror.is_distorted_image());
|
||||
for (b, t) in [(&flipped, 0.5), (&mirror, 0.5), (&mirror, 0.45)] {
|
||||
let got = Lerp::new(&a, b, (None, None)).at(t).image_corners().unwrap();
|
||||
let near = (if t < 0.5 { &a } else { b }).image_corners().unwrap();
|
||||
assert!(got.iter().zip(near).all(|(g, w)| g.distance(w) < 1e-9), "{t}: {got:?} against {near:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn key(x: f64) -> Arc<Node> {
|
||||
Arc::new(Node::path(NodeId(1), vectorcraft_geom::shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default()))
|
||||
}
|
||||
|
||||
@@ -500,11 +500,73 @@ impl Document {
|
||||
self.patterns.iter_mut().find(|p| p.name == name)
|
||||
}
|
||||
|
||||
/// The [`Self::unknown`] key that holds each symbol set's Symbol Set Density, `{set id: density}`.
|
||||
/// [`Self::reid`] gives a copy of a set in this document the density recorded for its source, and
|
||||
/// [`Self::carry_set_densities`] gives a pasted set the density recorded for it at Copy.
|
||||
pub const SYMBOL_SET_DENSITY_KEY: &'static str = "symbolSetDensity";
|
||||
|
||||
/// The Symbol Set Densities recorded for `nodes` and their descendants, by id.
|
||||
pub fn set_densities_of(&self, nodes: &[Node]) -> std::collections::BTreeMap<NodeId, serde_json::Value> {
|
||||
let Some(serde_json::Value::Object(record)) = self.unknown.get(Self::SYMBOL_SET_DENSITY_KEY) else { return Default::default() };
|
||||
let mut out = std::collections::BTreeMap::new();
|
||||
let mut stack: Vec<&Node> = nodes.iter().collect();
|
||||
while let Some(n) = stack.pop() {
|
||||
if let Some(v) = record.get(&n.id.0.to_string()) {
|
||||
out.insert(n.id, v.clone());
|
||||
}
|
||||
stack.extend(n.children().into_iter().flatten().map(|c| &**c));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Record for `copy`, a [`Self::reid`] copy of `source`, and its descendants the Symbol Set
|
||||
/// Densities that `densities` holds for `source` and its descendants, and none for those it
|
||||
/// holds none for (whatever [`Self::reid`] recorded).
|
||||
pub fn carry_set_densities(&mut self, source: &Node, copy: &Node, densities: &std::collections::BTreeMap<NodeId, serde_json::Value>) {
|
||||
if densities.is_empty() && !self.unknown.contains_key(Self::SYMBOL_SET_DENSITY_KEY) {
|
||||
return;
|
||||
}
|
||||
let mut pairs = vec![(source, copy)];
|
||||
while let Some((s, c)) = pairs.pop() {
|
||||
match densities.get(&s.id) {
|
||||
Some(v) => {
|
||||
if let serde_json::Value::Object(m) =
|
||||
self.unknown.entry(Self::SYMBOL_SET_DENSITY_KEY).or_insert_with(|| serde_json::Value::Object(Default::default()))
|
||||
{
|
||||
m.insert(c.id.0.to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) {
|
||||
m.remove(&c.id.0.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(sc), Some(cc)) = (s.children(), c.children()) {
|
||||
pairs.extend(sc.iter().zip(cc.iter()).map(|(a, b)| (&**a, &**b)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deep-clone `node` with fresh ids for it and all descendants, its images' own pixels taken
|
||||
/// in ([`Self::adopt_pixels`]).
|
||||
pub fn reid(&mut self, node: &Node) -> Node {
|
||||
let mut n = node.clone();
|
||||
n.id = self.alloc_id();
|
||||
// A copy of a symbol set keeps the Symbol Set Density recorded for its source, when the source
|
||||
// is this document's node with that id; a node from another document may share the id of an
|
||||
// unrelated set here.
|
||||
let density = self
|
||||
.unknown
|
||||
.get(Self::SYMBOL_SET_DENSITY_KEY)
|
||||
.and_then(|m| m.get(node.id.0.to_string()))
|
||||
.filter(|_| self.node(node.id) == Some(node))
|
||||
.cloned();
|
||||
if let Some(v) = density
|
||||
&& let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY)
|
||||
{
|
||||
m.insert(n.id.0.to_string(), v);
|
||||
}
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
self.adopt_image_pixels(im);
|
||||
}
|
||||
|
||||
@@ -1503,14 +1503,17 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
// An image is hit within its frame (on the frame's edge only with Selection by Path Only,
|
||||
// #3291, and in outline mode where the frame is all that is drawn, #6437), and where its
|
||||
// own fills and strokes paint ([`image_paint`]) except in outline mode.
|
||||
NodeKind::Image(im) => {
|
||||
NodeKind::Image(_) => {
|
||||
// The frame joins the image's corners ([`Node::image_frame`]); a plain image is picked
|
||||
// inside by its bounds, without building it.
|
||||
if opt.path_only || (opt.outline && !symbols.document().setup.outline_images) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let mut frame = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1);
|
||||
frame.apply_affine(im.xf);
|
||||
if stroke_contains(&frame, 0.0, opt.tol, p) {
|
||||
if n.image_frame().is_some_and(|frame| stroke_contains(&frame, 0.0, opt.tol, p)) {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
} else if let Some(frame) = n.is_distorted_image().then(|| n.image_frame()).flatten() {
|
||||
if fill_contains(&frame, FillRule::NonZero, p) || stroke_contains(&frame, 0.0, opt.tol, p) {
|
||||
return Some(HitKind::Bounds);
|
||||
}
|
||||
} else if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return Some(HitKind::Bounds);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,599 @@
|
||||
//! Perspective Distort and Free Distort on an image: its pixel rectangle's corners placed anywhere
|
||||
//! on the page, as long as they make a strictly convex quadrilateral.
|
||||
//!
|
||||
//! An image whose corners make a parallelogram is placed by its transform alone
|
||||
//! ([`crate::ImageObject::xf`]). Other corners are kept in the image's extras
|
||||
//! ([`crate::NodeExtras::image_quad`]), and the image is then drawn through the projective map
|
||||
//! that takes its pixel rectangle to them. The renderer, the exporters and printing draw it as a
|
||||
//! raster mesh warp ([`crate::live::mesh_warp_image`]) made from that map ([`distorted_art`]): no
|
||||
//! warped copy of the pixels is kept. The quad stays with the image's transform: moving, scaling,
|
||||
//! rotating or shearing the image maps its corners too ([`crate::Node::transform`]).
|
||||
//!
|
||||
//! The convexity rule, the tolerance of the mesh and its cell limit are VectorCraft's own.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::kurbo::BezPath;
|
||||
use vectorcraft_geom::{Affine, Homography, PathData, Point, Rect, SubPath};
|
||||
|
||||
use crate::{Appearance, ImageObject, Node, NodeKind};
|
||||
|
||||
/// Most cells along each side of the mesh an image is drawn with ([`cells`]).
|
||||
pub const MAX_CELLS: usize = 64;
|
||||
|
||||
/// The cells along each side an image with fewer pixels than this may still take ([`cells`]).
|
||||
pub const MIN_CELL_CAP: usize = 8;
|
||||
|
||||
/// How far (in points) the mesh an image is drawn with in files and print may stray from the exact
|
||||
/// projective map ([`Density::PAGE`]).
|
||||
pub const TOLERANCE: f64 = 0.05;
|
||||
|
||||
/// How finely [`distorted_art_at`] cuts a distorted image ([`cells`]), and how far each piece
|
||||
/// reaches into its neighbors. A pixel inside the image draws opaque only when one piece covers
|
||||
/// it whole, so pieces much smaller than a pixel would let the page show through.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Density {
|
||||
/// How far (in points) the mesh may stray from the exact projective map.
|
||||
pub tolerance: f64,
|
||||
/// The shortest a cell may be along the longest side of the corners, in points.
|
||||
pub min_cell: f64,
|
||||
/// How far (in points) each piece reaches past its triangle.
|
||||
pub overlap: f64,
|
||||
}
|
||||
|
||||
impl Density {
|
||||
/// For files and print, whose viewing size is not known: within [`TOLERANCE`], cells of at
|
||||
/// least 2 pt, and pieces that reach half a point past their triangles.
|
||||
pub const PAGE: Density = Density { tolerance: TOLERANCE, min_cell: 2.0, overlap: 0.5 };
|
||||
|
||||
/// For drawing at `scale` device pixels a point: within a quarter of a pixel, cells of at least
|
||||
/// 4 pixels, and pieces that reach 2 pixels past their triangles.
|
||||
pub fn at_scale(scale: f64) -> Density {
|
||||
let s = if scale.is_finite() && scale > 1e-6 { scale } else { 1.0 };
|
||||
Density { tolerance: 0.25 / s, min_cell: 4.0 / s, overlap: 2.0 / s }
|
||||
}
|
||||
|
||||
/// [`Density::PAGE`] for art that is drawn `scale` times its size (a symbol's art in an
|
||||
/// instance that scales it): the tolerance, the cell size and the overlap measured on the page.
|
||||
pub fn page_at(scale: f64) -> Density {
|
||||
let s = if scale.is_finite() && scale > 1e-6 { scale } else { 1.0 };
|
||||
let p = Density::PAGE;
|
||||
Density { tolerance: p.tolerance / s, min_cell: p.min_cell / s, overlap: p.overlap / s }
|
||||
}
|
||||
}
|
||||
|
||||
/// How much `a` stretches its most stretched direction: the larger singular value of its linear
|
||||
/// part.
|
||||
pub fn max_stretch(a: Affine) -> f64 {
|
||||
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
|
||||
let sum = m0 * m0 + m1 * m1 + m2 * m2 + m3 * m3;
|
||||
let det = m0 * m3 - m1 * m2;
|
||||
((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
|
||||
}
|
||||
|
||||
/// Why corners cannot be an image's.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum QuadError {
|
||||
/// A corner is not a finite point.
|
||||
NotFinite,
|
||||
/// The corners fold over, meet, or lie on one line: the quadrilateral is not strictly convex.
|
||||
NotConvex,
|
||||
/// The corners are convex but so close to a line that the perspective map through them cannot
|
||||
/// place every corner.
|
||||
TooNarrow,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for QuadError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::NotFinite => "the corners of a distorted image must be finite points",
|
||||
Self::NotConvex => "the corners of a distorted image must make a convex shape: an image cannot fold over itself or collapse to a line",
|
||||
Self::TooNarrow => "the corners of a distorted image are too close together for a perspective map",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `im`'s pixel rectangle: (0, 0) to its width and height.
|
||||
fn pixel_rect(im: &ImageObject) -> Rect {
|
||||
Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))
|
||||
}
|
||||
|
||||
/// The corners of `r` in the order a quad keeps them: top left, top right, bottom right, bottom
|
||||
/// left.
|
||||
fn rect_corners(r: Rect) -> [Point; 4] {
|
||||
[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]
|
||||
}
|
||||
|
||||
/// Whether the corners `q` (in order around the shape) are finite and make a strictly convex
|
||||
/// quadrilateral, turning either way round. Each turn must be larger than 1e-9 times the product
|
||||
/// of the two sides it joins, a test that gives the same answer at any scale.
|
||||
pub fn check(q: &[Point; 4]) -> Result<(), QuadError> {
|
||||
if q.iter().any(|p| !p.is_finite()) {
|
||||
return Err(QuadError::NotFinite);
|
||||
}
|
||||
let mut sign = 0.0;
|
||||
for i in 0..4 {
|
||||
let (a, b, c) = (q[i], q[(i + 1) % 4], q[(i + 2) % 4]);
|
||||
let (u, v) = (b - a, c - b);
|
||||
let cross = u.cross(v);
|
||||
let scale = u.hypot() * v.hypot();
|
||||
if !cross.is_finite() || !scale.is_finite() || cross.abs() <= 1e-9 * scale || scale == 0.0 {
|
||||
return Err(QuadError::NotConvex);
|
||||
}
|
||||
if sign == 0.0 {
|
||||
sign = cross.signum();
|
||||
} else if cross.signum() != sign {
|
||||
return Err(QuadError::NotConvex);
|
||||
}
|
||||
}
|
||||
// Four turns the same way round can still wind twice (a star); a convex quadrilateral's
|
||||
// diagonals cross.
|
||||
let crosses = |a: Point, b: Point, c: Point, d: Point| (b - a).cross(c - a).signum() != (b - a).cross(d - a).signum();
|
||||
if !crosses(q[0], q[2], q[1], q[3]) || !crosses(q[1], q[3], q[0], q[2]) {
|
||||
return Err(QuadError::NotConvex);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `q` can be image `im`'s corners: [`check`], and either a parallelogram or corners the
|
||||
/// perspective map from its pixels ([`pixel_map`]) places, each within a millionth of `q`'s
|
||||
/// shortest side plus the rounding error of coordinates as far from the origin as `q`'s.
|
||||
pub fn check_for(im: &ImageObject, q: &[Point; 4]) -> Result<(), QuadError> {
|
||||
check(q)?;
|
||||
if parallelogram(im, q).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let tol = placement_tolerance(q);
|
||||
let map = pixel_map(im, q);
|
||||
let placed = rect_corners(pixel_rect(im)).iter().zip(q).all(|(c, want)| map.apply(*c).is_some_and(|p| p.distance(*want) <= tol));
|
||||
if placed { Ok(()) } else { Err(QuadError::TooNarrow) }
|
||||
}
|
||||
|
||||
/// How far a map may place a corner from `q`'s: a millionth of `q`'s shortest side plus the
|
||||
/// rounding error of coordinates as far from the origin as `q`'s.
|
||||
fn placement_tolerance(q: &[Point; 4]) -> f64 {
|
||||
let side = (0..4).map(|i| q[i].distance(q[(i + 1) % 4])).fold(f64::INFINITY, f64::min);
|
||||
let far = q.iter().map(|p| p.x.abs().max(p.y.abs())).fold(0.0, f64::max);
|
||||
side * 1e-6 + far * 1e-12
|
||||
}
|
||||
|
||||
/// The affine map from `im`'s pixel space that places its corners at `q`, when `q` is a
|
||||
/// parallelogram (within 1e-9 of the quad's size): the map puts the fourth corner within
|
||||
/// [`placement_tolerance`] of `q`'s. `None` otherwise.
|
||||
fn parallelogram(im: &ImageObject, q: &[Point; 4]) -> Option<Affine> {
|
||||
let size = q.iter().fold(0.0_f64, |m, p| m.max((*p - q[0]).hypot()));
|
||||
// The affine map through the other three corners misses the bottom right one by this much.
|
||||
let gap = (q[0].to_vec2() + q[2].to_vec2() - q[1].to_vec2() - q[3].to_vec2()).hypot();
|
||||
if gap > 1e-9 * size || gap > placement_tolerance(q) {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
|
||||
let (x, y) = ((q[1] - q[0]) / w, (q[3] - q[0]) / h);
|
||||
let a = Affine::new([x.x, x.y, y.x, y.y, q[0].x, q[0].y]);
|
||||
a.is_finite().then_some(a)
|
||||
}
|
||||
|
||||
/// The homography taking the unit square's corners (0,0), (1,0), (1,1), (0,1) to `q`.
|
||||
fn square_to(q: &[Point; 4]) -> Homography {
|
||||
let [p0, p1, p2, p3] = *q;
|
||||
let (sx, sy) = (p0.x - p1.x + p2.x - p3.x, p0.y - p1.y + p2.y - p3.y);
|
||||
let (dx1, dx2, dy1, dy2) = (p1.x - p2.x, p3.x - p2.x, p1.y - p2.y, p3.y - p2.y);
|
||||
let den = dx1 * dy2 - dx2 * dy1;
|
||||
let (g, h) = if den.abs() < 1e-300 { (0.0, 0.0) } else { ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den) };
|
||||
Homography([[p1.x - p0.x + g * p1.x, p3.x - p0.x + h * p3.x, p0.x], [p1.y - p0.y + g * p1.y, p3.y - p0.y + h * p3.y, p0.y], [g, h, 1.0]])
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// This image's distortion: where its pixel rectangle's corners stand (top left, top right,
|
||||
/// bottom right, bottom left) when they do not make a parallelogram. `None` for an image placed
|
||||
/// by its transform alone, for anything that is not an image, and for corners a file holds
|
||||
/// that [`check_for`] refuses (the image is then placed by its transform).
|
||||
pub fn image_quad(&self) -> Option<[Point; 4]> {
|
||||
let NodeKind::Image(im) = &self.kind else { return None };
|
||||
let q = **self.extras().image_quad.as_ref()?;
|
||||
check_for(im, &q).is_ok().then_some(q)
|
||||
}
|
||||
|
||||
/// Whether this is an image with a distortion ([`Self::image_quad`]).
|
||||
pub fn is_distorted_image(&self) -> bool {
|
||||
self.image_quad().is_some()
|
||||
}
|
||||
|
||||
/// Where this image's pixel rectangle's corners stand: its distortion, or its transform's
|
||||
/// corners. `None` for anything that is not an image.
|
||||
pub fn image_corners(&self) -> Option<[Point; 4]> {
|
||||
let NodeKind::Image(im) = &self.kind else { return None };
|
||||
Some(self.image_quad().unwrap_or_else(|| rect_corners(pixel_rect(im)).map(|p| im.xf * p)))
|
||||
}
|
||||
|
||||
/// Place this image's corners at `q` (top left, top right, bottom right, bottom left): by its
|
||||
/// transform when they make a parallelogram (and the distortion is cleared), else as its
|
||||
/// distortion. An error, and nothing changes, when `q` fails [`check_for`] or this is not an
|
||||
/// image.
|
||||
pub fn set_image_corners(&mut self, q: [Point; 4]) -> Result<(), QuadError> {
|
||||
let NodeKind::Image(im) = &mut self.kind else { return Err(QuadError::NotConvex) };
|
||||
check_for(im, &q)?;
|
||||
match parallelogram(im, &q) {
|
||||
Some(xf) => {
|
||||
im.xf = xf;
|
||||
if self.extras().image_quad.is_some() {
|
||||
self.extras_mut().image_quad = None;
|
||||
}
|
||||
}
|
||||
None => self.extras_mut().image_quad = Some(Box::new(q)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The outline of this image's frame on the page: its corners joined by straight lines.
|
||||
/// `None` for anything that is not an image.
|
||||
pub fn image_frame(&self) -> Option<BezPath> {
|
||||
let q = self.image_corners()?;
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(q[0]);
|
||||
for p in &q[1..] {
|
||||
bp.line_to(*p);
|
||||
}
|
||||
bp.close_path();
|
||||
Some(bp)
|
||||
}
|
||||
|
||||
/// The map from this image's pixel space to the page: projective for a distorted image, its
|
||||
/// transform otherwise. `None` for anything that is not an image.
|
||||
pub fn image_map(&self) -> Option<Homography> {
|
||||
let NodeKind::Image(im) = &self.kind else { return None };
|
||||
Some(match self.image_quad() {
|
||||
Some(q) => pixel_map(im, &q),
|
||||
None => Homography::from_affine(im.xf),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The projective map from `im`'s pixel space to the page that puts its corners at `q`.
|
||||
fn pixel_map(im: &ImageObject, q: &[Point; 4]) -> Homography {
|
||||
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
|
||||
square_to(q).then_after(&Homography::from_affine(Affine::scale_non_uniform(1.0 / w, 1.0 / h)))
|
||||
}
|
||||
|
||||
/// How many cells along each side the mesh of a distorted image takes: the fewest (a power of two
|
||||
/// up to [`MAX_CELLS`]) for which the mesh's triangles, each mapped by the affine map through its
|
||||
/// corners, stay within `density`'s tolerance of `map` at the middle of every cell and every cell
|
||||
/// side. An image takes no more cells than it has pixels along its longer side, or
|
||||
/// [`MIN_CELL_CAP`] when that is more, and no more than leave each cell `density.min_cell` along
|
||||
/// the longest side of its corners. A perspective that needs more cells than these limits allow is
|
||||
/// drawn with the cells they allow.
|
||||
pub fn cells(map: &Homography, im: &ImageObject, density: Density) -> usize {
|
||||
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
|
||||
let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| map.apply(p));
|
||||
let longest =
|
||||
corners.iter().zip(corners.iter().cycle().skip(1)).filter_map(|(a, b)| Some(a.as_ref()?.distance(*b.as_ref()?))).fold(0.0, f64::max);
|
||||
let by_size = longest / density.min_cell;
|
||||
let by_size = if by_size.is_finite() { (by_size as usize).max(1) } else { MAX_CELLS };
|
||||
let most = MAX_CELLS.min((im.width.max(im.height) as usize).max(MIN_CELL_CAP)).min(by_size);
|
||||
let at = |x: f64, y: f64| map.apply(Point::new(x, y));
|
||||
let mut k = 1;
|
||||
while k < most {
|
||||
let fits = (0..k * k).all(|c| {
|
||||
let (i, j) = ((c % k) as f64, (c / k) as f64);
|
||||
let (x0, y0, x1, y1) = (w * i / k as f64, h * j / k as f64, w * (i + 1.0) / k as f64, h * (j + 1.0) / k as f64);
|
||||
let (Some(a), Some(b), Some(cc), Some(d)) = (at(x0, y0), at(x1, y0), at(x1, y1), at(x0, y1)) else { return false };
|
||||
let near = |exact: Option<Point>, m: Point| exact.is_some_and(|e| e.distance(m) <= density.tolerance);
|
||||
near(at((x0 + x1) / 2.0, (y0 + y1) / 2.0), a.midpoint(cc))
|
||||
&& near(at((x0 + x1) / 2.0, y0), a.midpoint(b))
|
||||
&& near(at(x1, (y0 + y1) / 2.0), b.midpoint(cc))
|
||||
&& near(at((x0 + x1) / 2.0, y1), d.midpoint(cc))
|
||||
&& near(at(x0, (y0 + y1) / 2.0), a.midpoint(d))
|
||||
});
|
||||
if fits {
|
||||
break;
|
||||
}
|
||||
k *= 2;
|
||||
}
|
||||
k.min(most)
|
||||
}
|
||||
|
||||
/// For a format that cannot clip an image into the pieces of [`distorted_art`]: the affine
|
||||
/// placement nearest distorted image `n`'s projective map, the one that matches it at the middle
|
||||
/// of its pixels. `None` when `n` is not a distorted image.
|
||||
pub fn nearest_affine(n: &Node) -> Option<Affine> {
|
||||
let NodeKind::Image(im) = &n.kind else { return None };
|
||||
let q = n.image_quad()?;
|
||||
pixel_map(im, &q).affine_at(pixel_rect(im).center())
|
||||
}
|
||||
|
||||
/// Distorted image `n` as the art that draws it in files and print: [`distorted_art_at`] with
|
||||
/// [`Density::PAGE`].
|
||||
pub fn distorted_art(n: &Node) -> Option<Node> {
|
||||
distorted_art_at(n, Density::PAGE)
|
||||
}
|
||||
|
||||
/// Distorted image `n` as the art that draws it: a clip group, clipped by its corners, around the
|
||||
/// raster mesh warp ([`crate::live::mesh_warp_image`]) of its pixels through its projective map,
|
||||
/// with [`cells`] cells along each side for `density` and each piece reaching `density.overlap`
|
||||
/// past its triangle. The art has `n`'s id but not its name and transparency (which the caller
|
||||
/// keeps on the object around the art). `None` when `n` is not a distorted image.
|
||||
pub fn distorted_art_at(n: &Node, density: Density) -> Option<Node> {
|
||||
let NodeKind::Image(im) = &n.kind else { return None };
|
||||
let q = n.image_quad()?;
|
||||
let map = pixel_map(im, &q);
|
||||
let k = cells(&map, im, density);
|
||||
let mut plain = n.clone();
|
||||
// Whether the image shows is the image's to decide: a hidden source image that a view draws
|
||||
// anyway (Image Trace's Source Image) draws its art.
|
||||
plain.visible = true;
|
||||
// The image's own fills and strokes paint by the image's rules, not on the mesh's group.
|
||||
plain.appearance = Default::default();
|
||||
plain.name = None;
|
||||
plain.opacity = 1.0;
|
||||
plain.blend = Default::default();
|
||||
plain.isolate = false;
|
||||
plain.knockout = Default::default();
|
||||
plain.knockout_shape = false;
|
||||
if let Some(e) = plain.extras_if_any() {
|
||||
e.mask = None;
|
||||
}
|
||||
let mut art = crate::live::mesh_warp_image_with(&plain, im, &|p| p, k, n.extras().pixelated, false, Some(density.overlap));
|
||||
// The pieces along the image's edges reach past its corners too: the corners clip them.
|
||||
let mut edge = Node::path(n.id, PathData::single(SubPath::polyline(&q, true)), Appearance::default());
|
||||
if let NodeKind::Path { clipping, .. } = &mut edge.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let pieces = std::mem::replace(&mut art.kind, NodeKind::Group { children: vec![], clip: true });
|
||||
let mut mesh = art.clone();
|
||||
mesh.kind = pieces;
|
||||
art.knockout = Default::default();
|
||||
art.kind = NodeKind::Group { children: vec![Arc::new(edge), Arc::new(mesh)], clip: true };
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// The pieces of [`distorted_art_at`]'s art: the children of its mesh group.
|
||||
pub fn distorted_pieces(art: &Node) -> &[Arc<Node>] {
|
||||
art.children().and_then(|c| c.get(1)).and_then(|m| m.children()).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::NodeId;
|
||||
|
||||
fn image(w: u32, h: u32) -> Node {
|
||||
let im = ImageObject { key: "k".into(), width: w, height: h, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
|
||||
Node::new(NodeId(1), NodeKind::Image(Box::new(im)))
|
||||
}
|
||||
|
||||
fn pts(v: [(f64, f64); 4]) -> [Point; 4] {
|
||||
v.map(|(x, y)| Point::new(x, y))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_convex_quad_either_way_round_passes_and_a_fold_or_line_does_not() {
|
||||
assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Ok(()));
|
||||
assert_eq!(check(&pts([(0.0, 0.0), (0.0, 10.0), (10.0, 10.0), (10.0, 0.0)])), Ok(()));
|
||||
// Two corners swapped: the sides cross.
|
||||
assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])), Err(QuadError::NotConvex));
|
||||
// A dent.
|
||||
assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (2.0, 2.0), (0.0, 10.0)])), Err(QuadError::NotConvex));
|
||||
// Three on a line, and two corners at one point.
|
||||
assert_eq!(check(&pts([(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (0.0, 10.0)])), Err(QuadError::NotConvex));
|
||||
assert_eq!(check(&pts([(0.0, 0.0), (0.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Err(QuadError::NotConvex));
|
||||
assert_eq!(check(&pts([(f64::NAN, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Err(QuadError::NotFinite));
|
||||
}
|
||||
|
||||
/// A convex quad with one edge so short that the perspective map through it cannot place the
|
||||
/// other corners: refused when set, and a file's copy of it leaves the image undistorted.
|
||||
#[test]
|
||||
fn corners_the_perspective_map_cannot_place_are_refused() {
|
||||
let q = pts([(50.0, 0.0), (50.000000005, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
assert_eq!(check(&q), Ok(()));
|
||||
let mut n = image(100, 100);
|
||||
assert_eq!(n.set_image_corners(q), Err(QuadError::TooNarrow));
|
||||
assert!(n.extras().image_quad.is_none());
|
||||
n.extras_mut().image_quad = Some(Box::new(q));
|
||||
assert_eq!(n.image_quad(), None);
|
||||
assert!(distorted_art(&n).is_none());
|
||||
assert_eq!(n.image_corners(), Some(rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parallelogram_goes_into_the_transform_and_other_corners_into_the_quad() {
|
||||
let mut n = image(100, 50);
|
||||
n.set_image_corners(pts([(10.0, 0.0), (110.0, 10.0), (100.0, 60.0), (0.0, 50.0)])).unwrap();
|
||||
assert_eq!(n.image_quad(), None);
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
|
||||
assert!((im.xf * Point::new(100.0, 50.0)).distance(Point::new(100.0, 60.0)) < 1e-9);
|
||||
let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
n.set_image_corners(q).unwrap();
|
||||
assert_eq!(n.image_quad(), Some(q));
|
||||
assert_eq!(n.image_corners(), Some(q));
|
||||
let map = n.image_map().unwrap();
|
||||
for (c, want) in rect_corners(Rect::new(0.0, 0.0, 100.0, 50.0)).iter().zip(q) {
|
||||
assert!(map.apply(*c).unwrap().distance(want) < 1e-9, "{c:?}");
|
||||
}
|
||||
// Back to a rectangle: the quad is cleared.
|
||||
n.set_image_corners(pts([(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)])).unwrap();
|
||||
assert!(n.extras().image_quad.is_none());
|
||||
}
|
||||
|
||||
/// Corners whose gap from a parallelogram is tiny next to the quad's size but not next to its
|
||||
/// shortest side stay a distortion: the affine map would put the bottom right corner twice as
|
||||
/// low as asked.
|
||||
#[test]
|
||||
fn corners_the_affine_map_misses_stay_a_distortion() {
|
||||
let mut n = image(100, 100);
|
||||
let q = pts([(0.0, 0.0), (100000.0, 0.0), (100000.0, 0.00005), (0.0, 0.0001)]);
|
||||
n.set_image_corners(q).unwrap();
|
||||
assert_eq!(n.image_quad(), Some(q));
|
||||
let map = n.image_map().unwrap();
|
||||
for (c, want) in rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)).iter().zip(q) {
|
||||
assert!(map.apply(*c).unwrap().distance(want) < 1e-9, "{c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A scale that squeezes valid corners past what a perspective map can place leaves the image
|
||||
/// at the placement nearest them, scaled, not at the rectangle it had before.
|
||||
#[test]
|
||||
fn a_scale_past_the_perspective_limit_keeps_the_nearest_placement() {
|
||||
let mut n = image(100, 100);
|
||||
n.set_image_corners(pts([(0.0, 0.0), (100.0, 0.0), (200.0, 2e-7), (0.0, 2e-7)])).unwrap();
|
||||
assert!(n.is_distorted_image());
|
||||
n.transform(Affine::scale_non_uniform(1.0, 0.25), false);
|
||||
assert!(n.extras().image_quad.is_none());
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!(b.height() < 1e-6 && (b.width() - 150.0).abs() < 60.0, "{b:?}");
|
||||
}
|
||||
|
||||
/// A file's corners that the image cannot take are dropped as it is read, so a later scale
|
||||
/// that would make them valid leaves the image placed by its transform; a list of three
|
||||
/// points is dropped too, and the rest of the image is read.
|
||||
#[test]
|
||||
fn corners_a_file_holds_that_are_refused_or_not_four_are_dropped_as_it_is_read() {
|
||||
let mut n = image(100, 100);
|
||||
n.extras_mut().image_quad = Some(Box::new(pts([(0.0, 0.0), (100.0, 0.0), (200.0, 5e-8), (0.0, 5e-8)])));
|
||||
assert_eq!(n.image_quad(), None);
|
||||
let mut read: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap();
|
||||
assert!(read.extras().image_quad.is_none());
|
||||
read.transform(Affine::scale_non_uniform(1.0, 4.0), false);
|
||||
assert!(!read.is_distorted_image());
|
||||
assert_eq!(read.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 400.0)));
|
||||
let mut v = serde_json::to_value(&n).unwrap();
|
||||
v["image_quad"] = serde_json::json!([[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]);
|
||||
let read: Node = serde_json::from_value(v).unwrap();
|
||||
assert!(read.extras().image_quad.is_none());
|
||||
assert!(matches!(read.kind, NodeKind::Image(_)));
|
||||
// Past a fourth point the rest is skipped without being read as points.
|
||||
for extra in [serde_json::json!([5.0, 5.0]), serde_json::json!("not a point")] {
|
||||
let mut v = serde_json::to_value(&n).unwrap();
|
||||
v["image_quad"] = serde_json::json!([[40.0, 0.0], [60.0, 0.0], [100.0, 100.0], [0.0, 100.0], extra, {"x": 1}]);
|
||||
let read: Node = serde_json::from_value(v).unwrap();
|
||||
assert!(read.extras().image_quad.is_none());
|
||||
}
|
||||
// Valid corners read back.
|
||||
let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
n.set_image_corners(q).unwrap();
|
||||
let read: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap();
|
||||
assert_eq!(read.image_quad(), Some(q));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_corners_change_nothing_and_a_bad_quad_in_a_file_is_ignored() {
|
||||
let mut n = image(10, 10);
|
||||
let before = n.clone();
|
||||
assert!(n.set_image_corners(pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])).is_err());
|
||||
assert_eq!(n, before);
|
||||
n.extras_mut().image_quad = Some(Box::new(pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])));
|
||||
assert_eq!(n.image_quad(), None);
|
||||
assert_eq!(n.image_corners(), Some(pts([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mesh_is_as_fine_as_the_perspective_needs() {
|
||||
let mut n = image(400, 400);
|
||||
n.set_image_corners(pts([(10.0, 0.0), (400.0, 5.0), (390.0, 400.0), (0.0, 395.0)])).unwrap();
|
||||
let NodeKind::Image(im) = n.kind.clone() else { panic!("an image") };
|
||||
let gentle = cells(&n.image_map().unwrap(), &im, Density::PAGE);
|
||||
n.set_image_corners(pts([(160.0, 0.0), (240.0, 0.0), (400.0, 400.0), (0.0, 400.0)])).unwrap();
|
||||
let strong = cells(&n.image_map().unwrap(), &im, Density::PAGE);
|
||||
assert!(gentle < strong && strong <= MAX_CELLS, "{gentle} {strong}");
|
||||
// Three by two pixels drawn as large still bend, in up to MIN_CELL_CAP cells.
|
||||
let mut tiny = image(3, 2);
|
||||
tiny.set_image_corners(pts([(160.0, 0.0), (240.0, 0.0), (400.0, 400.0), (0.0, 400.0)])).unwrap();
|
||||
let NodeKind::Image(tim) = &tiny.kind else { panic!("an image") };
|
||||
assert_eq!(cells(&tiny.image_map().unwrap(), tim, Density::PAGE), MIN_CELL_CAP.min(strong));
|
||||
// Drawn small, the same corners take only cells of at least 4 pixels: their longest side,
|
||||
// about 431 pt, is about 17 pixels at 1/25 px a point, room for 4 cells.
|
||||
let map = n.image_map().unwrap();
|
||||
assert!(cells(&map, &im, Density::at_scale(1.0 / 25.0)) <= 4);
|
||||
// Drawn large, a quarter of a pixel is finer than 0.05 pt, so no fewer cells than on the page.
|
||||
assert!(cells(&map, &im, Density::at_scale(8.0)) >= strong);
|
||||
// Each cell of the page's mesh is at least 2 pt along the longest side: about 32 pt takes
|
||||
// 16 at most.
|
||||
let mut small = image(400, 400);
|
||||
small.set_image_corners(pts([(12.0, 0.0), (18.0, 0.0), (30.0, 30.0), (0.0, 30.0)])).unwrap();
|
||||
assert!(cells(&small.image_map().unwrap(), &im, Density::PAGE) <= 16);
|
||||
}
|
||||
|
||||
/// Each piece of the art reaches the density's overlap past its triangle, and the corners clip
|
||||
/// the art, so nothing draws outside them.
|
||||
#[test]
|
||||
fn the_pieces_overlap_and_the_corners_clip_them() {
|
||||
let mut n = image(100, 100);
|
||||
let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
n.set_image_corners(q).unwrap();
|
||||
let art = distorted_art_at(&n, Density { tolerance: 1.0, min_cell: 1.0, overlap: 3.0 }).unwrap();
|
||||
let Some([edge, _]) = art.children().map(Vec::as_slice) else { panic!("an edge and a mesh") };
|
||||
assert!(matches!(edge.kind, NodeKind::Path { clipping: true, .. }));
|
||||
assert_eq!(edge.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 100.0)));
|
||||
let pieces = distorted_pieces(&art);
|
||||
assert!(pieces.len() >= 2);
|
||||
// The first piece's clip triangle reaches 3 pt past the image's top left corner.
|
||||
let Some([clip, _]) = pieces[0].children().map(Vec::as_slice) else { panic!("a clip and an image") };
|
||||
let b = clip.geometric_bounds().unwrap();
|
||||
assert!(b.y0 < -2.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_art_puts_the_pixel_corners_on_the_quad() {
|
||||
let mut n = image(100, 100);
|
||||
n.opacity = 0.5;
|
||||
let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
n.set_image_corners(q).unwrap();
|
||||
let art = distorted_art(&n).unwrap();
|
||||
assert_eq!(art.opacity, 1.0);
|
||||
let mut corners_seen = [false; 4];
|
||||
art.walk(&mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind {
|
||||
for (i, (p, want)) in rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)).iter().zip(q).enumerate() {
|
||||
if (im.xf * *p).distance(want) < 1e-9 {
|
||||
corners_seen[i] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(corners_seen, [true; 4]);
|
||||
assert!(distorted_art(&image(4, 4)).is_none());
|
||||
// A hidden image that a view draws anyway gives art that draws.
|
||||
n.visible = false;
|
||||
assert!(distorted_art(&n).unwrap().visible);
|
||||
// The image's own fills and strokes stay off the mesh's group.
|
||||
let stroke = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
|
||||
n.appearance = crate::Appearance::basic(vectorcraft_color::Paint::None, stroke, 1.0).into();
|
||||
assert!(distorted_art(&n).unwrap().appearance.items.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_expansion_reaches_a_distorted_image_inside_a_group() {
|
||||
let mut n = image(100, 100);
|
||||
n.set_image_corners(pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)])).unwrap();
|
||||
let inner = Node::new(NodeId(2), NodeKind::Group { children: vec![std::sync::Arc::new(n)], clip: false });
|
||||
let outer = Node::new(NodeId(3), NodeKind::Group { children: vec![std::sync::Arc::new(inner)], clip: false });
|
||||
let out = crate::live::expand_deep(&outer, None);
|
||||
let mut distorted = 0;
|
||||
let mut pieces = 0;
|
||||
out.walk(&mut |c| {
|
||||
distorted += usize::from(c.is_distorted_image());
|
||||
pieces += usize::from(matches!(c.kind, NodeKind::Image(_)));
|
||||
});
|
||||
assert_eq!(distorted, 0);
|
||||
assert!(pieces > 1, "{pieces}");
|
||||
}
|
||||
|
||||
/// A distorted image with an effect of its own stays an image with its appearance when the
|
||||
/// art around it is expanded, so the effect still applies where the art is drawn.
|
||||
#[test]
|
||||
fn deep_expansion_keeps_a_distorted_image_with_its_own_appearance() {
|
||||
let mut n = image(100, 100);
|
||||
n.set_image_corners(pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)])).unwrap();
|
||||
let effect = crate::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 40}), visible: true };
|
||||
n.appearance = crate::Appearance { effects: vec![effect], ..Default::default() }.into();
|
||||
let inner = Node::new(NodeId(2), NodeKind::Group { children: vec![std::sync::Arc::new(n.clone())], clip: false });
|
||||
let outer = Node::new(NodeId(3), NodeKind::Group { children: vec![std::sync::Arc::new(inner)], clip: false });
|
||||
let out = crate::live::expand_deep(&outer, None);
|
||||
let mut kept = vec![];
|
||||
out.walk(&mut |c| {
|
||||
if c.is_distorted_image() {
|
||||
kept.push(c.appearance.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(kept, vec![n.appearance]);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub mod image_quad;
|
||||
pub use id_index::{path_lookups, tree_walks};
|
||||
pub mod inks;
|
||||
mod inline;
|
||||
|
||||
@@ -57,11 +57,11 @@ pub use envelope::{
|
||||
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
|
||||
envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
|
||||
};
|
||||
pub(crate) use expand::max_outset;
|
||||
pub use expand::{
|
||||
Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with,
|
||||
expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live,
|
||||
expanded_group, expanded_group_hooks, is_drawn_live, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live,
|
||||
};
|
||||
pub(crate) use expand::{max_outset, mesh_warp_image_with};
|
||||
#[cfg(test)]
|
||||
use mesh::grid_eval;
|
||||
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
|
||||
|
||||
@@ -212,12 +212,26 @@ pub fn mesh_warp_cost(cells: usize) -> usize {
|
||||
/// partly transparent image keeps its own alpha there. More cells than [`MAX_GENERATED`] objects
|
||||
/// allow make an empty group.
|
||||
pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node {
|
||||
mesh_warp_image_with(n, im, f, cells, pixelated, masked, None)
|
||||
}
|
||||
|
||||
/// [`mesh_warp_image`], each piece reaching `overlap` points past its edges when given.
|
||||
pub(crate) fn mesh_warp_image_with(
|
||||
n: &Node,
|
||||
im: &ImageObject,
|
||||
f: &dyn Fn(Point) -> Point,
|
||||
cells: usize,
|
||||
pixelated: bool,
|
||||
masked: bool,
|
||||
overlap: Option<f64>,
|
||||
) -> Node {
|
||||
let k = cells.max(1);
|
||||
let mut g = n.clone();
|
||||
g.kind = NodeKind::Group { children: vec![], clip: false };
|
||||
g.knockout = crate::Knockout::On;
|
||||
if let Some(e) = g.extras_if_any() {
|
||||
e.colorize = None;
|
||||
e.image_quad = None;
|
||||
}
|
||||
if mesh_warp_cost(k) > MAX_GENERATED {
|
||||
return g;
|
||||
@@ -228,24 +242,31 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
|
||||
let color_mask = n.extras().color_mask.clone();
|
||||
let (pw, ph) = (im.width as f64, im.height as f64);
|
||||
let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64);
|
||||
// A distorted image's pixels reach the page through its projective map.
|
||||
let to_page = n.image_map().filter(|_| n.is_distorted_image());
|
||||
let place = |p: Point| to_page.and_then(|m| m.apply(p)).unwrap_or(im.xf * p);
|
||||
let mut pieces = Vec::with_capacity(2 * k * k);
|
||||
for j in 0..k {
|
||||
for i in 0..k {
|
||||
let s = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)];
|
||||
let d = s.map(|p| f(im.xf * p));
|
||||
let d = s.map(|p| f(place(p)));
|
||||
for t in [[0, 1, 2], [0, 2, 3]] {
|
||||
let (st, dt) = (t.map(|v| s[v]), t.map(|v| d[v]));
|
||||
let Some(xf) = affine_between(st, dt) else { continue };
|
||||
let c = Point::new((dt[0].x + dt[1].x + dt[2].x) / 3.0, (dt[0].y + dt[1].y + dt[2].y) / 3.0);
|
||||
let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5);
|
||||
let tri: Vec<Point> = dt
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let v = *p - c;
|
||||
let len = v.hypot();
|
||||
if len > 1e-12 { *p + v * (grow / len) } else { *p }
|
||||
})
|
||||
.collect();
|
||||
let tri: Vec<Point> = match overlap {
|
||||
Some(g) => grown_triangle(dt, g),
|
||||
None => {
|
||||
let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5);
|
||||
dt.iter()
|
||||
.map(|p| {
|
||||
let v = *p - c;
|
||||
let len = v.hypot();
|
||||
if len > 1e-12 { *p + v * (grow / len) } else { *p }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
let shape = PathData::single(SubPath::polyline(&tri, true));
|
||||
let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() })));
|
||||
image.extras_mut().pixelated = pixelated;
|
||||
@@ -274,6 +295,23 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
|
||||
g
|
||||
}
|
||||
|
||||
/// Triangle `t` with each side moved `g` outward: `t` scaled about its incenter. A corner moves
|
||||
/// at most 8 `g`, so a very thin triangle's sides move less than `g`.
|
||||
fn grown_triangle(t: [Point; 3], g: f64) -> Vec<Point> {
|
||||
let side = |i: usize| t[(i + 1) % 3].distance(t[(i + 2) % 3]);
|
||||
let (a, b, c) = (side(0), side(1), side(2));
|
||||
let perimeter = a + b + c;
|
||||
let area = ((t[1] - t[0]).cross(t[2] - t[0]) / 2.0).abs();
|
||||
if !(perimeter > 1e-12 && area > 0.0 && g.is_finite() && g > 0.0) {
|
||||
return t.to_vec();
|
||||
}
|
||||
let center = Point::new((a * t[0].x + b * t[1].x + c * t[2].x) / perimeter, (a * t[0].y + b * t[1].y + c * t[2].y) / perimeter);
|
||||
let r = 2.0 * area / perimeter;
|
||||
let far = t.iter().map(|p| p.distance(center)).fold(0.0, f64::max);
|
||||
let grow = (g / r).min(8.0 * g / far.max(1e-12));
|
||||
t.iter().map(|p| center + (*p - center) * (1.0 + grow)).collect()
|
||||
}
|
||||
|
||||
/// Distort Pattern Fills: path or compound path `n` with each visible pattern fill turned into the
|
||||
/// tiles it paints in a clip group shaped like `n` (with the fill's opacity and blend mode), its
|
||||
/// other fills and strokes on copies of it, in paint order, under `n`'s transparency. `None`
|
||||
@@ -353,6 +391,13 @@ pub fn is_live(n: &Node) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// Is this drawn and written as evaluated art: a live object ([`is_live`]) or a distorted image
|
||||
/// ([`Node::image_quad`]), whose art is [`crate::image_quad::distorted_art`]. Effects and
|
||||
/// container paint treat a distorted image as an image, not as live art.
|
||||
pub fn is_drawn_live(n: &Node) -> bool {
|
||||
is_live(n) || n.is_distorted_image()
|
||||
}
|
||||
|
||||
/// Mesh tessellation as flat-filled paths (no stroke): each patch cut `n`×`n`, its quads joined
|
||||
/// where the colour hardly changes ([`GradientMesh::pieces`]).
|
||||
pub fn mesh_quad_nodes(m: &GradientMesh, n: usize) -> Vec<Node> {
|
||||
@@ -388,6 +433,7 @@ pub fn expand_live_hooks(n: &Node, hooks: Hooks) -> Vec<Node> {
|
||||
NodeKind::Repeat(r) => r.expand(hooks.symbols),
|
||||
NodeKind::PlacedDocument(p) => p.art(n),
|
||||
NodeKind::Intertwine { children } => crate::intertwine::expand(children),
|
||||
NodeKind::Image(_) => vec![crate::image_quad::distorted_art(n).unwrap_or_else(|| n.clone())],
|
||||
_ => vec![n.clone()],
|
||||
}
|
||||
}
|
||||
@@ -429,7 +475,7 @@ pub fn expand_deep(n: &Node, outline: Outliner) -> Node {
|
||||
/// expands to nothing.
|
||||
pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node {
|
||||
let _generating = Generating::enter();
|
||||
let mut out = if is_live(n) {
|
||||
let mut out = if is_drawn_live(n) {
|
||||
let g = expanded_group_hooks(n, hooks);
|
||||
if !Generating::charge(g.count()) {
|
||||
return Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
|
||||
@@ -440,7 +486,12 @@ pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node {
|
||||
};
|
||||
if let Some(ch) = out.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
if subtree_has_live(c) {
|
||||
// A distorted image with fills, strokes or effects of its own stays an image: whoever
|
||||
// draws the art draws it with them, as it draws a distorted image anywhere else.
|
||||
if c.is_distorted_image() && !(c.appearance.items.is_empty() && c.appearance.effects.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
if subtree_has_drawn_live(c) {
|
||||
*c = Arc::new(expand_deep_hooks(c, hooks));
|
||||
}
|
||||
}
|
||||
@@ -497,6 +548,13 @@ pub fn subtree_has_live(n: &Node) -> bool {
|
||||
any
|
||||
}
|
||||
|
||||
/// Does `n` or any descendant draw as evaluated art ([`is_drawn_live`])?
|
||||
fn subtree_has_drawn_live(n: &Node) -> bool {
|
||||
let mut any = false;
|
||||
n.walk(&mut |c| any |= is_drawn_live(c));
|
||||
any
|
||||
}
|
||||
|
||||
/// Largest stroke outset in a subtree (for visual bounds of envelopes, blends and repeats, and the
|
||||
/// reach of symbol art), type's character strokes included as type's own visual bounds measure them
|
||||
/// ([`crate::TextObject::char_stroke_outset`]): in an envelope they paint at their own weight
|
||||
|
||||
@@ -44,8 +44,12 @@ impl Node {
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
|
||||
out.push((frame.to_bezpath(), FillRule::NonZero));
|
||||
// A distorted image's frame joins its corners.
|
||||
let frame = match self.image_frame().filter(|_| self.is_distorted_image()) {
|
||||
Some(bp) => bp,
|
||||
None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf).to_bezpath(),
|
||||
};
|
||||
out.push((frame, FillRule::NonZero));
|
||||
}
|
||||
NodeKind::PlacedDocument(p) => {
|
||||
let frame = shapes::rectangle(p.natural()).transformed(p.xf);
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::kind::NodeKind;
|
||||
use super::live_shape::LiveShape;
|
||||
use super::opacity::OpacityMask;
|
||||
use super::{Node, PathData};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
/// The parts of a [`Node`] that few objects have: kept out of line, so that the nodes without
|
||||
/// them stay small ([`Node::extras`]).
|
||||
@@ -87,6 +88,10 @@ pub struct NodeExtras {
|
||||
/// are applied, one path or compound path per fill and stroke: as the clipping path of a clip group it paints
|
||||
/// those pieces as the path paints its fills and strokes ([`Node::clip_paint`]).
|
||||
pub clip_pieces: bool,
|
||||
/// As an image after Perspective Distort or Free Distort, where its pixel rectangle's corners
|
||||
/// (top left, top right, bottom right, bottom left in pixel space) stand on the page when they
|
||||
/// do not make a parallelogram, which its transform alone could place ([`crate::image_quad`]).
|
||||
pub image_quad: Option<Box<[Point; 4]>>,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -118,6 +123,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
color_mask: None,
|
||||
warp_piece: false,
|
||||
clip_pieces: false,
|
||||
image_quad: None,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
@@ -386,6 +386,10 @@ impl Node {
|
||||
.filter(|c| c.visible || !matches!(self.kind, NodeKind::Layer { .. }))
|
||||
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols))),
|
||||
NodeKind::Text(t) => self.projected(t.bounds()),
|
||||
// A distorted image is bounded by its corners.
|
||||
NodeKind::Image(_) if self.is_distorted_image() => {
|
||||
self.image_corners().map(|q| q[1..].iter().fold(Rect::from_points(q[0], q[0]), |r, p| r.union_pt(*p)))
|
||||
}
|
||||
NodeKind::Image(im) => Some(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, im.width as f64, im.height as f64))),
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let art = symbols.and_then(|s| s.art(symbol)).map_or(SYMBOL_SQUARE, |a| a.geometric);
|
||||
@@ -528,6 +532,9 @@ impl Node {
|
||||
}
|
||||
// The path the objects are attached to, before it is transformed.
|
||||
let on_path_before = self.on_path_data().cloned();
|
||||
// A distorted image's placement nearest its corners, before they are transformed (`None`
|
||||
// within when its stored corners are refused, and `None` for anything else).
|
||||
let image_before = self.extras().image_quad.is_some().then(|| crate::image_quad::nearest_affine(self));
|
||||
if !self.is_layer() {
|
||||
self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a);
|
||||
}
|
||||
@@ -637,7 +644,8 @@ impl Node {
|
||||
{
|
||||
Arc::make_mut(&mut m.art).transform_scaled(a, sc);
|
||||
}
|
||||
// The area where an Intertwine member is drawn over the others moves with it.
|
||||
// The area where an Intertwine member is drawn over the others moves with it, and so do a
|
||||
// distorted image's corners.
|
||||
if let Some(e) = self.extras_if_any() {
|
||||
if let Some(area) = e.intertwine.as_mut() {
|
||||
area.transform(a);
|
||||
@@ -645,6 +653,23 @@ impl Node {
|
||||
for area in &mut e.intertwine_tiers {
|
||||
area.transform(a);
|
||||
}
|
||||
if let Some(q) = e.image_quad.as_mut() {
|
||||
for p in q.iter_mut() {
|
||||
*p = a * *p;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Corners that a scale squeezes past what a perspective map can place (or that were
|
||||
// refused already) leave the image placed by its transform: for valid corners, the
|
||||
// placement that was nearest them, transformed, rather than the rectangle it had before
|
||||
// it was distorted.
|
||||
if let Some(before) = image_before
|
||||
&& self.image_quad().is_none()
|
||||
{
|
||||
if let (Some(near), NodeKind::Image(im)) = (before, &mut self.kind) {
|
||||
im.xf = a * near;
|
||||
}
|
||||
self.extras_mut().image_quad = None;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ impl Serialize for Node {
|
||||
e.color_mask.is_none(),
|
||||
is_default(&e.warp_piece),
|
||||
is_default(&e.clip_pieces),
|
||||
e.image_quad.is_none(),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
@@ -106,6 +107,7 @@ impl Serialize for Node {
|
||||
field!("color_mask", &e.color_mask);
|
||||
field!("warp_piece", &e.warp_piece);
|
||||
field!("clip_pieces", &e.clip_pieces);
|
||||
field!("image_quad", &e.image_quad);
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
@@ -257,10 +259,55 @@ pub(super) struct NodeWire {
|
||||
warp_piece: bool,
|
||||
#[serde(default)]
|
||||
clip_pieces: bool,
|
||||
#[serde(default, deserialize_with = "image_corners")]
|
||||
image_quad: Option<Box<[vectorcraft_geom::Point; 4]>>,
|
||||
}
|
||||
|
||||
/// A distorted image's corners as a file holds them: a list of exactly four points, else none (the
|
||||
/// image is then placed by its transform). At most five points of a longer list are kept while it
|
||||
/// is read.
|
||||
fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Box<[vectorcraft_geom::Point; 4]>>, D::Error> {
|
||||
use vectorcraft_geom::Point;
|
||||
struct Corners;
|
||||
impl<'de> serde::de::Visitor<'de> for Corners {
|
||||
type Value = Option<Box<[Point; 4]>>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a list of points")
|
||||
}
|
||||
fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
fn visit_some<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
|
||||
d.deserialize_seq(Corners)
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
|
||||
let mut points = Vec::with_capacity(4);
|
||||
while points.len() < 4
|
||||
&& let Some(p) = seq.next_element::<Point>()?
|
||||
{
|
||||
points.push(p);
|
||||
}
|
||||
// A fifth entry drops the field, so the rest is skipped without decoding it.
|
||||
let mut extra = false;
|
||||
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
|
||||
extra = true;
|
||||
}
|
||||
Ok(if extra { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) })
|
||||
}
|
||||
}
|
||||
d.deserialize_option(Corners)
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
fn from(w: NodeWire) -> Self {
|
||||
// Corners an image cannot take are dropped, so a later transform cannot make them its own.
|
||||
let image_quad = match &w.kind {
|
||||
NodeKind::Image(im) => w.image_quad.filter(|q| crate::image_quad::check_for(im, q).is_ok()),
|
||||
_ => None,
|
||||
};
|
||||
let extras = NodeExtras {
|
||||
mask: w.mask,
|
||||
trace: w.trace,
|
||||
@@ -289,6 +336,7 @@ impl From<NodeWire> for Node {
|
||||
color_mask: w.color_mask,
|
||||
warp_piece: w.warp_piece,
|
||||
clip_pieces: w.clip_pieces,
|
||||
image_quad,
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
|
||||
@@ -686,6 +686,43 @@ fn reid_gives_fresh_ids() {
|
||||
assert!(!ids.contains(&a) && !ids.contains(&b));
|
||||
}
|
||||
|
||||
/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from
|
||||
/// another document with the same id does not.
|
||||
#[test]
|
||||
fn reid_copies_the_set_density_of_the_documents_own_node() {
|
||||
let (mut d, a, _) = doc_with_rects();
|
||||
d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 }));
|
||||
let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned();
|
||||
let own = d.node(a).cloned().unwrap();
|
||||
let copy = d.reid(&own);
|
||||
assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0)));
|
||||
let foreign = Node::group(a, vec![]);
|
||||
let copy = d.reid(&foreign);
|
||||
assert_eq!(density(&d, copy.id), None);
|
||||
}
|
||||
|
||||
/// A pasted copy and its descendants take the densities recorded at Copy, and none where Copy
|
||||
/// recorded none, whatever [`Document::reid`] found for an identical node in the document.
|
||||
#[test]
|
||||
fn carry_set_densities_gives_the_densities_recorded_at_copy() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 }));
|
||||
let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned();
|
||||
let (na, nb) = (d.node(a).cloned().unwrap(), d.node(b).cloned().unwrap());
|
||||
// Copy recorded nothing for `a`: the copy reid gave a density loses it.
|
||||
let copy = d.reid(&na);
|
||||
assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0)));
|
||||
d.carry_set_densities(&na, ©, &Default::default());
|
||||
assert_eq!(density(&d, copy.id), None);
|
||||
// Copy recorded 7 for `b` inside a group: the group's copy has none, and `b`'s copy has 7.
|
||||
let g = d.alloc_id();
|
||||
let group = Node::group(g, vec![Arc::new(nb)]);
|
||||
let copy = d.reid(&group);
|
||||
d.carry_set_densities(&group, ©, &[(b, serde_json::json!(7.0))].into_iter().collect());
|
||||
let inner = copy.children().unwrap()[0].id;
|
||||
assert_eq!((density(&d, copy.id), density(&d, inner)), (None, Some(serde_json::json!(7.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setup_round_trips_and_old_files_load() {
|
||||
let (mut d, _, _) = doc_with_rects();
|
||||
|
||||
@@ -38,7 +38,7 @@ pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList,
|
||||
TabAlign, TabStop,
|
||||
};
|
||||
pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work};
|
||||
pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work};
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
///
|
||||
|
||||
@@ -451,12 +451,25 @@ impl TextObject {
|
||||
/// fractions of the path. False, changing nothing, for other type, when the anchor doesn't
|
||||
/// exist, a degenerate `xf` or a path that would not be finite.
|
||||
pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool {
|
||||
self.set_path_handle_with_symmetry((si, ai), out, pos, independent, false)
|
||||
}
|
||||
/// [`Self::set_path_handle`] with an optional mirror of the opposite handle about the anchor
|
||||
/// in document space, preserving the anchor kind. `independent` takes precedence, and at an
|
||||
/// open end of the path, where no segment leaves the anchor on that side, the handle moves as
|
||||
/// it would without `symmetric`. Both handles are edited in one reshape, using the same validated
|
||||
/// document-to-text map.
|
||||
pub fn set_path_handle_with_symmetry(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool, symmetric: bool) -> bool {
|
||||
let xf = self.xf;
|
||||
matches!(self.kind, TextKind::OnPath { .. })
|
||||
&& self.reshape_local(|path, to_text| {
|
||||
let mirror = symmetric && !independent && path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, !out));
|
||||
let Some(a) = path.anchor_mut(si, ai) else { return false };
|
||||
let mut drawn = a.transform(xf);
|
||||
drawn.set_handle(out, pos, independent);
|
||||
if mirror {
|
||||
let opposite = drawn.p - (pos - drawn.p);
|
||||
if out { drawn.h_in = opposite } else { drawn.h_out = opposite }
|
||||
}
|
||||
*a = drawn.transform(to_text);
|
||||
true
|
||||
})
|
||||
|
||||
@@ -669,6 +669,34 @@ fn area_type() -> TextObject {
|
||||
t
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrap_object_below_every_area_type_object_makes_no_outline() {
|
||||
use crate::{Appearance, Document, Node, NodeKind};
|
||||
let mut d = Document::new(300.0, 300.0);
|
||||
let l = d.layers[0].id;
|
||||
let wrap = |d: &mut Document, r: Rect| {
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::path(id, vectorcraft_geom::shapes::rectangle(r), Appearance::default_art());
|
||||
n.extras_mut().wrap = Some(TextWrap::default());
|
||||
n
|
||||
};
|
||||
// Bottom to top: a wrap object, the area type, then a wrap object.
|
||||
let below = wrap(&mut d, Rect::new(0.0, 0.0, 250.0, 250.0));
|
||||
d.insert(Some(l), 9, below).unwrap();
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::new(id, NodeKind::Text(Box::new(area_type())))).unwrap();
|
||||
let above = wrap(&mut d, Rect::new(60.0, 40.0, 80.0, 60.0));
|
||||
d.insert(Some(l), 9, above).unwrap();
|
||||
wrap::OUTLINES_MADE.with(|c| c.set(0));
|
||||
let mut sources = 0;
|
||||
wrap_sources(&d, |_, objects, shapes| {
|
||||
sources += 1;
|
||||
assert_eq!((objects.len(), shapes.len()), (1, 1));
|
||||
});
|
||||
assert_eq!(sources, 1);
|
||||
assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_resizes_its_frame_and_keeps_its_type() {
|
||||
let mut t = area_type();
|
||||
|
||||
@@ -7,6 +7,12 @@ use vectorcraft_geom::{PathData, shapes};
|
||||
use super::{TextKind, TextObject, WrapShape};
|
||||
use crate::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many wrap outlines [`each_text`] has made on this thread (for tests).
|
||||
pub(super) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
|
||||
fn outline(n: &Node, out: &mut PathData) {
|
||||
match &n.kind {
|
||||
@@ -66,10 +72,45 @@ fn collect<'a>(n: &'a Node, out: &mut Vec<Item<'a>>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors and subpaths [`outline`] would collect for wrap object `n`, counted without copying
|
||||
/// them.
|
||||
fn outline_size(n: &Node) -> (usize, usize) {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, .. } => path
|
||||
.subpaths
|
||||
.iter()
|
||||
.filter(|sp| sp.closed || sp.anchors.len() > 2)
|
||||
.fold((0usize, 0usize), |(a, s), sp| (a.saturating_add(sp.anchors.len()), s.saturating_add(1))),
|
||||
NodeKind::Compound { children, .. } | NodeKind::Group { children, clip: false } => children
|
||||
.iter()
|
||||
.filter(|c| c.visible)
|
||||
.map(|c| outline_size(c))
|
||||
.fold((0, 0), |(a, s), (ca, cs)| (a.saturating_add(ca), s.saturating_add(cs))),
|
||||
NodeKind::Group { children, clip: true } => children.first().map_or((0, 0), |c| outline_size(c)),
|
||||
// A rectangle of the object's bounds.
|
||||
_ => {
|
||||
if n.geometric_bounds().is_some() {
|
||||
(4, 1)
|
||||
} else {
|
||||
(0, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How much [`resolve_wrap`] would copy into the wrap shapes of every area text object in `doc`:
|
||||
/// each wrap object's outline (its anchors, plus one for the shape) once for each area text object
|
||||
/// below it in its layer.
|
||||
pub fn wrap_work(doc: &Document) -> usize {
|
||||
work(doc, false)
|
||||
}
|
||||
|
||||
/// [`wrap_work`], with one more for each subpath of each outline, empty ones included.
|
||||
pub fn wrap_copy_units(doc: &Document) -> usize {
|
||||
work(doc, true)
|
||||
}
|
||||
|
||||
fn work(doc: &Document, count_subpaths: bool) -> usize {
|
||||
let mut total = 0usize;
|
||||
for layer in &doc.layers {
|
||||
let mut items = vec![];
|
||||
@@ -78,11 +119,10 @@ pub fn wrap_work(doc: &Document) -> usize {
|
||||
for it in items.iter().rev() {
|
||||
match it {
|
||||
Item::Wrap(n) => {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
let anchors: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum();
|
||||
above = above.saturating_add(anchors.saturating_add(1));
|
||||
let (anchors, subpaths) = outline_size(n);
|
||||
if anchors > 0 {
|
||||
let subpaths = if count_subpaths { subpaths } else { 0 };
|
||||
above = above.saturating_add(anchors).saturating_add(subpaths).saturating_add(1);
|
||||
}
|
||||
}
|
||||
Item::Text(_) => total = total.saturating_add(above),
|
||||
@@ -99,9 +139,15 @@ fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapS
|
||||
let mut items = vec![];
|
||||
collect(layer, &mut items);
|
||||
let mut above: Vec<(&Node, WrapShape)> = vec![];
|
||||
for it in items.iter().rev() {
|
||||
// A wrap object below every area text object of the layer wraps none of them: its outline is
|
||||
// not made.
|
||||
let first_text = items.iter().position(|it| matches!(it, Item::Text(_)));
|
||||
for (i, it) in items.iter().enumerate().rev() {
|
||||
match it {
|
||||
Item::Wrap(_) if first_text.is_none_or(|t| i < t) => {}
|
||||
Item::Wrap(n) => {
|
||||
#[cfg(test)]
|
||||
OUTLINES_MADE.with(|c| c.set(c.get() + 1));
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
|
||||
@@ -111,6 +111,8 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
"sketch.tornEdges" => always(&["smoothness"]),
|
||||
"sketch.waterPaper" => always(&["fiberLength"]),
|
||||
TRAP => always(&["thickness", "precision"]),
|
||||
// The Pathfinder Options' refit tolerance.
|
||||
id if crate::takes_pathfinder_options(id) => always(&["precision"]),
|
||||
RASTERIZE => always(&["addAround"]),
|
||||
// The points one unit of the filter measures.
|
||||
crate::SVG_FILTER => always(&["scale"]),
|
||||
@@ -189,7 +191,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
EXTRUDE,
|
||||
"Extrude & Bevel…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
@@ -210,7 +212,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
CLASSIC_EXTRUDE,
|
||||
"Extrude & Bevel (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.",
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's points, as for threeD.extrude; bevel {custom: name} takes a bevel of the bevels file), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false,"mapArt":[],"mapShade":false,"mapInvisible":false}),
|
||||
),
|
||||
g(
|
||||
@@ -832,15 +834,11 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
}
|
||||
for (id, label, _) in PATHFINDER_EFFECTS {
|
||||
if id == "pathfinder.softMix" {
|
||||
v.push(g(
|
||||
id,
|
||||
label,
|
||||
PATHFINDER,
|
||||
"{mixingRate?: 1..100 % (50)} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)",
|
||||
json!({"mixingRate": 50.0}),
|
||||
));
|
||||
v.push(g(id, label, PATHFINDER, crate::group::SOFT_MIX_PARAMS_DOC, json!({"mixingRate": 50.0})));
|
||||
} else {
|
||||
v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({})));
|
||||
// No dialog defaults, so the Effect menu applies it directly; effect.apply fills its
|
||||
// Pathfinder Options in.
|
||||
v.push(g(id, label, PATHFINDER, crate::group::PATHFINDER_PARAMS_DOC, json!({})));
|
||||
}
|
||||
}
|
||||
v.extend(crate::addons::color::catalog());
|
||||
|
||||
+121
-8
@@ -51,6 +51,80 @@ fn op_of(id: &str) -> Option<PathfinderOp> {
|
||||
PATHFINDER_EFFECTS.iter().find(|e| e.0 == id).map(|e| e.2)
|
||||
}
|
||||
|
||||
/// Does effect `id` keep Pathfinder Options of its own ([`PathfinderEffectOptions`]): one of
|
||||
/// [`PATHFINDER_EFFECTS`] (Trap has options of its own)?
|
||||
pub fn takes_pathfinder_options(id: &str) -> bool {
|
||||
op_of(id).is_some()
|
||||
}
|
||||
|
||||
/// The parameters holding a Pathfinder effect's Pathfinder Options.
|
||||
pub const PATHFINDER_OPTION_KEYS: [&str; 3] = ["precision", "removeRedundantPoints", "removeUnpainted"];
|
||||
|
||||
/// The range of a Pathfinder effect's `precision` (pt), the Pathfinder panel's range.
|
||||
pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive<f64> = 0.001..=10.0;
|
||||
|
||||
/// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`.
|
||||
macro_rules! options_doc {
|
||||
() => {
|
||||
"precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing; results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)"
|
||||
};
|
||||
}
|
||||
|
||||
/// The documentation of [`PATHFINDER_OPTION_KEYS`], shared by the Pathfinder effects' parameters.
|
||||
pub const PATHFINDER_OPTIONS_DOC: &str = options_doc!();
|
||||
|
||||
/// The parameters of a Pathfinder effect other than Soft Mix.
|
||||
pub const PATHFINDER_PARAMS_DOC: &str = concat!("{", options_doc!(), "} (groups and layers: live Pathfinder over the members)");
|
||||
|
||||
/// The parameters of Effect › Pathfinder › Soft Mix.
|
||||
pub const SOFT_MIX_PARAMS_DOC: &str = concat!(
|
||||
"{mixingRate?: 1..100 % (50), ",
|
||||
options_doc!(),
|
||||
"} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)"
|
||||
);
|
||||
|
||||
/// The Pathfinder Options a Pathfinder effect evaluates with, read from its parameters. An effect
|
||||
/// without them (saved before effects kept their own) evaluates as it did then: the default
|
||||
/// precision, with no points or pieces removed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PathfinderEffectOptions {
|
||||
/// Refit tolerance of the results, in points ([`PATHFINDER_EFFECT_PRECISION`]).
|
||||
pub precision: f64,
|
||||
/// Drop anchors that don't change a result's shape.
|
||||
pub remove_redundant_points: bool,
|
||||
/// Divide and Outline leave out the pieces of members with no visible fill.
|
||||
pub remove_unpainted: bool,
|
||||
}
|
||||
|
||||
impl Default for PathfinderEffectOptions {
|
||||
fn default() -> Self {
|
||||
PathfinderEffectOptions { precision: po::DEFAULT_PRECISION, remove_redundant_points: false, remove_unpainted: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl PathfinderEffectOptions {
|
||||
/// The options in `p`: a missing or non-numeric value takes its default and a precision out of
|
||||
/// range its nearest bound, so a live effect always evaluates.
|
||||
pub fn from_params(p: &Value) -> Self {
|
||||
let d = PathfinderEffectOptions::default();
|
||||
let (lo, hi) = (*PATHFINDER_EFFECT_PRECISION.start(), *PATHFINDER_EFFECT_PRECISION.end());
|
||||
PathfinderEffectOptions {
|
||||
precision: crate::util::num(p, "precision", d.precision).clamp(lo, hi),
|
||||
remove_redundant_points: crate::util::flag(p, "removeRedundantPoints", d.remove_redundant_points),
|
||||
remove_unpainted: crate::util::flag(p, "removeUnpainted", d.remove_unpainted),
|
||||
}
|
||||
}
|
||||
|
||||
/// These options as the parameters [`PATHFINDER_OPTION_KEYS`] name.
|
||||
pub fn to_params(self) -> Value {
|
||||
serde_json::json!({
|
||||
"precision": self.precision,
|
||||
"removeRedundantPoints": self.remove_redundant_points,
|
||||
"removeUnpainted": self.remove_unpainted,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n` (a group or layer) carry a visible Pathfinder effect, or is it a compound shape?
|
||||
pub fn has_pathfinder(n: &Node) -> bool {
|
||||
n.is_compound_shape()
|
||||
@@ -503,6 +577,23 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
out.extend(source.iter().skip(art).cloned());
|
||||
return Some(out);
|
||||
}
|
||||
// When the group has a visible fill of its own, that fill paints its members' geometry, a
|
||||
// compound shape's area included ([`evaluate_container`]), so Remove Unpainted Artwork keeps
|
||||
// every Divide piece. Outline's open segments still go by their source's fill.
|
||||
let own_fill = has_visible_fill(group);
|
||||
// A compound shape's area has no paint of its own: the shape's own appearance paints it. The
|
||||
// shape's top painting fill is the area's fill for Remove Unpainted Artwork and for Outline's
|
||||
// strokes, while Divide pieces stay unpainted so that the fill is not drawn twice.
|
||||
let area_style = group.is_compound_shape().then(|| {
|
||||
let items = group.appearance.items.iter().filter(|i| paints(i)).cloned().collect();
|
||||
Node::path(group.id, PathData::default(), Appearance { items, ..Default::default() })
|
||||
});
|
||||
let style_of = |s: &Node| -> Option<Node> {
|
||||
let a = area_style.as_ref().filter(|_| s.id == group.id && s.appearance.items.is_empty())?;
|
||||
let mut a = a.clone();
|
||||
(a.opacity, a.blend) = (s.opacity, s.blend);
|
||||
Some(a)
|
||||
};
|
||||
let mut stack: Vec<Arc<Node>> = if group.is_compound_shape() {
|
||||
// The group's own appearance paints the area ([`evaluate_container`]), so the art has none.
|
||||
match compound_shape_area(doc, group, hook) {
|
||||
@@ -535,6 +626,7 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
continue;
|
||||
}
|
||||
let Some(op) = op_of(&e.id) else { continue };
|
||||
let options = PathfinderEffectOptions::from_params(&e.params);
|
||||
let shape_mode =
|
||||
matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack);
|
||||
let nodes = SymbolNodes::default();
|
||||
@@ -558,7 +650,7 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
|
||||
let key = sources.len() as u64;
|
||||
if let Some(top) = lv.pop() {
|
||||
shapes.push(po::Shape::new(po::unite_all(&refs), FillRule::NonZero, key));
|
||||
shapes.push(po::Shape::new(po::unite_all_with(&refs, options.precision), FillRule::NonZero, key));
|
||||
sources.push(top);
|
||||
}
|
||||
} else {
|
||||
@@ -574,24 +666,40 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
if shapes.is_empty() {
|
||||
return Some(vec![]);
|
||||
}
|
||||
// Remove Redundant Points: each result loses the anchors that don't change its shape.
|
||||
let tidy = |path: PathData| if options.remove_redundant_points { po::remove_redundant_points(&path, options.precision) } else { path };
|
||||
stack = if op == PathfinderOp::SoftMix {
|
||||
let rate = mixing_rate(&e.params);
|
||||
po::regions(&shapes)
|
||||
po::regions_with(&shapes, options.precision)
|
||||
.into_iter()
|
||||
.filter(|r| !r.path.is_empty())
|
||||
.map(|r| Arc::new(soft_mix_face(r.path, &r.sources, rate, &shapes, &sources)))
|
||||
.map(|r| Arc::new(soft_mix_face(tidy(r.path), &r.sources, rate, &shapes, &sources)))
|
||||
.collect()
|
||||
} else if op == PathfinderOp::HardMix {
|
||||
po::regions(&shapes)
|
||||
po::regions_with(&shapes, options.precision)
|
||||
.into_iter()
|
||||
.filter(|r| !r.path.is_empty())
|
||||
.map(|r| Arc::new(hard_mix_face(r.path, &r.sources, &shapes, &sources)))
|
||||
.map(|r| Arc::new(hard_mix_face(tidy(r.path), &r.sources, &shapes, &sources)))
|
||||
.collect()
|
||||
} else {
|
||||
po::pathfinder(op, &shapes)
|
||||
// Divide and Outline Will Remove Unpainted Artwork: the pieces of members with no
|
||||
// visible fill go.
|
||||
let unpainted = options.remove_unpainted
|
||||
&& match op {
|
||||
PathfinderOp::Divide => !own_fill,
|
||||
PathfinderOp::Outline => true,
|
||||
_ => false,
|
||||
};
|
||||
let fill_sources: Vec<Option<Node>> = sources.iter().map(style_of).collect();
|
||||
let fill_source = |k: u64| fill_sources[k as usize].as_ref().unwrap_or(&sources[k as usize]);
|
||||
po::pathfinder_with(op, &shapes, options.precision)
|
||||
.into_iter()
|
||||
.filter(|r| !r.path.is_empty())
|
||||
.map(|r| Arc::new(styled(&sources[r.key as usize], r.path, op == PathfinderOp::Outline)))
|
||||
.filter(|r| !r.path.is_empty() && !(unpainted && !has_visible_fill(fill_source(r.key))))
|
||||
.map(|r| {
|
||||
let outline = op == PathfinderOp::Outline;
|
||||
let src = if outline { fill_source(r.key) } else { &sources[r.key as usize] };
|
||||
Arc::new(styled(src, tidy(r.path), outline))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
}
|
||||
@@ -676,6 +784,11 @@ pub fn paints(item: &AppearanceItem) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Has `n` a visible fill that paints, as the Pathfinder panel's Remove Unpainted Artwork counts it?
|
||||
fn has_visible_fill(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none()))
|
||||
}
|
||||
|
||||
/// Do the own fills or strokes of `n`, a group or layer, paint anything?
|
||||
pub(crate) fn has_own_paint(n: &Node) -> bool {
|
||||
is_container(n) && n.appearance.items.iter().any(paints)
|
||||
|
||||
@@ -213,6 +213,81 @@ fn divide_and_outline_draw_nothing_for_unpainted_members() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Remove Unpainted Artwork, Divide and Outline keep the area of a compound shape whose own
|
||||
/// appearance has a visible fill and leave out the area of one without.
|
||||
#[test]
|
||||
fn remove_unpainted_keeps_a_filled_compound_shapes_area() {
|
||||
for effect in ["pathfinder.divide", "pathfinder.outline"] {
|
||||
for filled in [true, false] {
|
||||
let mut g = compound_shape(ShapeMode::Add);
|
||||
if !filled {
|
||||
g.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
|
||||
}
|
||||
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": true}), visible: true });
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
assert_eq!(!out.is_empty(), filled, "{effect}, filled {filled}: {out:#?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline strokes a compound shape's area in the shape's own fill (its top visible one that
|
||||
/// paints), with Remove Unpainted Artwork on or off, and Divide leaves the area's pieces
|
||||
/// unpainted for the shape's fill to paint.
|
||||
#[test]
|
||||
fn outline_strokes_a_compound_shapes_area_in_its_fill() {
|
||||
let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0));
|
||||
for (remove, covered) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
for effect in ["pathfinder.divide", "pathfinder.outline"] {
|
||||
let mut g = compound_shape(ShapeMode::Add);
|
||||
if covered {
|
||||
// A hidden fill and an unpainted fill above the green one.
|
||||
let mut hidden = FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
hidden.visible = false;
|
||||
let mut a = (*g.appearance).clone();
|
||||
a.insert_item(a.items.len(), AppearanceItem::Fill(hidden));
|
||||
a.insert_item(a.items.len(), AppearanceItem::Fill(FillLayer::new(Paint::None)));
|
||||
g.appearance = a.into();
|
||||
}
|
||||
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": remove}), visible: true });
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
assert!(!out.is_empty(), "{effect}, remove {remove}");
|
||||
for n in &out {
|
||||
if effect == "pathfinder.outline" {
|
||||
assert_eq!(n.appearance.stroke_paint(), green, "{effect}, remove {remove}: {n:#?}");
|
||||
assert!(n.appearance.fill_paint().is_none(), "{effect}, remove {remove}: {n:#?}");
|
||||
} else {
|
||||
assert!(n.appearance.items.is_empty(), "{effect}, remove {remove}: {n:#?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With Remove Unpainted Artwork, Divide keeps the pieces of an unfilled member when its group's
|
||||
/// own visible fill paints them and leaves them out when the group has no fill. Outline leaves out
|
||||
/// the member's segments either way.
|
||||
#[test]
|
||||
fn remove_unpainted_keeps_members_a_groups_own_fill_paints() {
|
||||
let unfilled = Arc::new(Node::path(
|
||||
NodeId(2),
|
||||
shapes::rectangle(Rect::new(5.0, 0.0, 15.0, 10.0)),
|
||||
Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
));
|
||||
for effect in ["pathfinder.divide", "pathfinder.outline"] {
|
||||
for filled in [true, false] {
|
||||
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), unfilled.clone()]);
|
||||
if filled {
|
||||
g.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0).into();
|
||||
}
|
||||
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": true}), visible: true });
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
assert!(out.iter().any(|n| n.id == NodeId(1)), "{effect}, filled {filled}: {out:#?}");
|
||||
let kept = filled && effect == "pathfinder.divide";
|
||||
assert_eq!(out.iter().any(|n| n.id == NodeId(2)), kept, "{effect}, filled {filled}: {out:#?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an "H" in blue type at 100 pt on a baseline at y = 80, with its stems on either
|
||||
/// side of x = 100.
|
||||
fn type_h() -> Node {
|
||||
|
||||
@@ -75,8 +75,9 @@ pub use bake::{
|
||||
};
|
||||
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
|
||||
pub use group::{
|
||||
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
|
||||
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art,
|
||||
OutlineHook, PATHFINDER_EFFECT_PRECISION, PATHFINDER_EFFECTS, PATHFINDER_OPTION_KEYS, PATHFINDER_OPTIONS_DOC, PathfinderEffectOptions,
|
||||
compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves,
|
||||
member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art, takes_pathfinder_options,
|
||||
};
|
||||
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
|
||||
@@ -96,11 +97,11 @@ pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
};
|
||||
pub use solids::{
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES,
|
||||
ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading,
|
||||
extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics,
|
||||
mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art,
|
||||
solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
|
||||
BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics,
|
||||
RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options,
|
||||
classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d,
|
||||
mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe,
|
||||
solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
|
||||
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
|
||||
validate_three_d_params, view_options, with_graphic,
|
||||
};
|
||||
@@ -115,8 +116,8 @@ pub use solids::{
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
pub use trap::TRAP;
|
||||
pub use vectorcraft_three_d::Mesh;
|
||||
pub use vectorcraft_three_d::PlanarFace;
|
||||
pub use vectorcraft_three_d::{BevelProfile, Mesh};
|
||||
pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version};
|
||||
|
||||
mod catalog;
|
||||
|
||||
@@ -120,7 +120,10 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> {
|
||||
/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see
|
||||
/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which
|
||||
/// keep their share of the object so. A distance left at its default is written out scaled; one
|
||||
/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent.
|
||||
/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent. A Pathfinder
|
||||
/// effect without a `precision` gets the precision it evaluates with, scaled. Values are scaled
|
||||
/// as stored, out of range or not, so a scale and its inverse restore them; evaluation applies
|
||||
/// each effect's range.
|
||||
pub fn scale_effect(e: &mut Effect, s: f64) {
|
||||
let Some(info) = catalog_index().get(e.id.as_str()) else { return };
|
||||
let merged = merged_params(&e.id, &e.params);
|
||||
@@ -128,7 +131,9 @@ pub fn scale_effect(e: &mut Effect, s: f64) {
|
||||
let mut keys: Vec<&str> = info.lengths.keys(relative).collect();
|
||||
keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some()));
|
||||
for k in keys {
|
||||
let v = util::num(&merged, k, f64::NAN);
|
||||
let missing =
|
||||
if k == "precision" && crate::takes_pathfinder_options(&e.id) { crate::PathfinderEffectOptions::default().precision } else { f64::NAN };
|
||||
let v = util::num(&merged, k, missing);
|
||||
if v.is_finite() {
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Map::new());
|
||||
|
||||
@@ -1248,15 +1248,20 @@ fn as_art_opts(
|
||||
let fx = geometry_effects(n);
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Image(im) => {
|
||||
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
|
||||
// A distorted image's frame joins its corners.
|
||||
let frame = match n.image_frame().filter(|_| n.is_distorted_image()) {
|
||||
Some(bp) => PathData::from_bezpath(&bp),
|
||||
None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf),
|
||||
};
|
||||
let mut image = Node::new(n.id, n.kind.clone());
|
||||
// Its pixels draw as the image's do: colorized by a grayscale image's fill color,
|
||||
// smoothed or not, and with its color mask's masked pixels.
|
||||
// smoothed or not, with its color mask's masked pixels, and distorted.
|
||||
{
|
||||
let mut e = image.extras_mut();
|
||||
e.colorize = n.extras().colorize.clone();
|
||||
e.pixelated = n.extras().pixelated;
|
||||
e.color_mask = n.extras().color_mask.clone();
|
||||
e.image_quad = n.extras().image_quad.clone();
|
||||
}
|
||||
let clipped = || {
|
||||
let mut clip = Node::path(n.id, frame.clone(), Appearance::default());
|
||||
@@ -1276,6 +1281,17 @@ fn as_art_opts(
|
||||
clipped()
|
||||
} else {
|
||||
let opaque = std::cell::OnceCell::new();
|
||||
// A distorted image's opaque area, traced in its pixels, goes to the page through
|
||||
// its projective map.
|
||||
let opaque_on_page = || match n.image_map().filter(|_| n.is_distorted_image()) {
|
||||
Some(map) => {
|
||||
let plain = ImageObject { xf: Affine::IDENTITY, ..(**im).clone() };
|
||||
let piece = f64::from(im.width.max(im.height).max(1)) / 64.0;
|
||||
opaque_area(&[symbols, paint_doc], &plain)
|
||||
.map(|p| vectorcraft_doc::live::map_nonlinear(&p, piece, |q| map.apply(q).unwrap_or(q)))
|
||||
}
|
||||
None => opaque_area(&[symbols, paint_doc], im),
|
||||
};
|
||||
let rows = |items: Vec<AppearanceItem>| {
|
||||
let mut out = vec![];
|
||||
let mut items = items.into_iter().peekable();
|
||||
@@ -1285,7 +1301,7 @@ fn as_art_opts(
|
||||
while let Some(next) = items.next_if(|i| follows_opaque_area(i) == follows) {
|
||||
run.push(next);
|
||||
}
|
||||
let path = if follows { opaque.get_or_init(|| opaque_area(&[symbols, paint_doc], im)).as_ref() } else { None };
|
||||
let path = if follows { opaque.get_or_init(opaque_on_page).as_ref() } else { None };
|
||||
let path = path.unwrap_or(&frame);
|
||||
if !path.is_empty() {
|
||||
out.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: run, ..Default::default() })));
|
||||
@@ -3718,8 +3734,21 @@ fn restore_warped_images(n: &mut Node, warped: &WarpedImages, cut: bool) {
|
||||
// The pieces start from the image as it was placed when it took its first warp.
|
||||
let first = warps.first().map(|(_, at)| ImageObject { xf: *at, ..(**own).clone() });
|
||||
let map = warped_map(warps, own.xf);
|
||||
// A placement with no inverse cannot take a distorted image's corners back.
|
||||
let det = own.xf.determinant();
|
||||
let back = warps.first().filter(|_| det.is_finite() && det != 0.0).map(|(_, at)| *at * own.xf.inverse()).filter(Affine::is_finite);
|
||||
let distorted = image.extras().image_quad.is_some();
|
||||
*c = Arc::new(match (first, map) {
|
||||
(Some(first), Some(map)) if cut => {
|
||||
(Some(first), Some(map)) if cut && (back.is_some() || !distorted) => {
|
||||
// A distorted image's corners go back to where they stood at its first warp, as
|
||||
// its placement does: the moves since then are in `map`.
|
||||
if let Some(back) = back
|
||||
&& let Some(q) = image.extras_if_any().and_then(|e| e.image_quad.as_mut())
|
||||
{
|
||||
for p in q.iter_mut() {
|
||||
*p = back * *p;
|
||||
}
|
||||
}
|
||||
let pixelated = image.extras().pixelated;
|
||||
vectorcraft_doc::live::mesh_warp_image(&image, &first, &*map, WARP_IMAGE_CELLS, pixelated, false)
|
||||
}
|
||||
@@ -3787,6 +3816,12 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc:
|
||||
NodeKind::SymbolInstance { xf: at, .. } => *at = xf * *at,
|
||||
_ => {}
|
||||
}
|
||||
// A distorted image's corners move with it.
|
||||
if let Some(q) = one.extras_if_any().and_then(|e| e.image_quad.as_mut()) {
|
||||
for p in q.iter_mut() {
|
||||
*p = xf * *p;
|
||||
}
|
||||
}
|
||||
// The placed gradients of its own fills and strokes move with it, as a path's do.
|
||||
if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() {
|
||||
one.appearance.transform_gradients(xf);
|
||||
|
||||
@@ -8,7 +8,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId
|
||||
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
|
||||
use vectorcraft_pathops::BoolOp;
|
||||
use vectorcraft_three_d::{
|
||||
Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View,
|
||||
Bevel, BevelProfile, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -72,7 +72,9 @@ pub const THREE_D_TYPES: [(&str, &str); 4] = [("plane", ROTATE), ("extrude", EXT
|
||||
/// The parameters of 3D effect `to` for an effect `from` with `params`, as switching the object
|
||||
/// type keeps them: every setting `to` takes keeps its value from `params` (the defaults of `from`
|
||||
/// under them), each rotation angle wrapped into -180° to 180° when `to` is not Revolve, and the
|
||||
/// settings only `to` takes start at their defaults. Settings `to` does not take are dropped.
|
||||
/// settings only `to` takes start at their defaults. Settings `to` does not take are dropped; a
|
||||
/// custom bevel's name and points ([`BEVEL_NAME`], [`BEVEL_PROFILE`]) go with `bevel` when `to`
|
||||
/// takes one.
|
||||
pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
|
||||
let current = crate::merged_params(from, params);
|
||||
let mut out = crate::default_params(to).and_then(|v| v.as_object().cloned()).unwrap_or_default();
|
||||
@@ -81,6 +83,13 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
|
||||
value.clone_from(v);
|
||||
}
|
||||
}
|
||||
if out.contains_key("bevel") {
|
||||
for key in [BEVEL_NAME, BEVEL_PROFILE] {
|
||||
if let Some(v) = current.get(key).filter(|v| !v.is_null()) {
|
||||
out.insert(key.into(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if to != crate::REVOLVE {
|
||||
for key in ["rotationX", "rotationY", "rotationZ"] {
|
||||
if let Some(a) = out.get(key).and_then(Value::as_f64).filter(|a| !(-180.0..=180.0).contains(a)) {
|
||||
@@ -170,14 +179,66 @@ pub fn view_options(p: &Value) -> View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Extrude & Bevel's parameters. `bevel` is `"none"` or a [`BevelShape`] id.
|
||||
/// The custom bevel's name parameter: the name the bevels file gave it, kept for the menus.
|
||||
pub const BEVEL_NAME: &str = "bevelName";
|
||||
/// The custom bevel's points parameter: `[[across, down], …]`, shares of the bevel's width and
|
||||
/// height from the cap's edge `[0, 0]` to the side wall `[1, 1]` (a copy of the bevel's path, so
|
||||
/// the document draws it without the bevels file).
|
||||
pub const BEVEL_PROFILE: &str = "bevelProfile";
|
||||
|
||||
/// The points of `v`, a [`BEVEL_PROFILE`] value; `None` unless it is an array of `[x, y]` number
|
||||
/// pairs that make a [`BevelProfile`].
|
||||
fn bevel_profile(v: &Value) -> Option<BevelProfile> {
|
||||
let list = v.as_array().filter(|a| a.len() <= BevelProfile::MAX_POINTS)?;
|
||||
let pts: Option<Vec<(f64, f64)>> = list
|
||||
.iter()
|
||||
.map(|pt| match pt.as_array().map(Vec::as_slice) {
|
||||
Some([x, y]) => Some((x.as_f64()?, y.as_f64()?)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
BevelProfile::new(&pts?)
|
||||
}
|
||||
|
||||
/// The bevel shape of parameters `p`: `bevel` `"none"` (none), a built-in [`BevelShape`] id, or
|
||||
/// `"custom"` with its points in [`BEVEL_PROFILE`] (none when they do not make a profile).
|
||||
pub(crate) fn bevel_shape(p: &Value) -> Option<BevelShape> {
|
||||
match text(p, "bevel", "none") {
|
||||
"custom" => p.get(BEVEL_PROFILE).and_then(bevel_profile).map(BevelShape::Custom),
|
||||
id => BevelShape::parse(id),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check the custom bevel parameters of `p`: `bevel` `"custom"` needs [`BEVEL_PROFILE`], whose
|
||||
/// points, when given, must make a profile, and [`BEVEL_NAME`] is a string.
|
||||
fn validate_bevel(p: &Value) -> Result<(), String> {
|
||||
let most = BevelProfile::MAX_POINTS;
|
||||
if let Some(v) = p.get(BEVEL_PROFILE)
|
||||
&& !v.is_null()
|
||||
&& bevel_profile(v).is_none()
|
||||
{
|
||||
return Err(format!(
|
||||
"{BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall)"
|
||||
));
|
||||
}
|
||||
if text(p, "bevel", "none") == "custom" && p.get(BEVEL_PROFILE).is_none_or(Value::is_null) {
|
||||
return Err(format!("bevel custom needs {BEVEL_PROFILE}, the bevel's points"));
|
||||
}
|
||||
if p.get(BEVEL_NAME).is_some_and(|v| !v.is_string() && !v.is_null()) {
|
||||
return Err(format!("{BEVEL_NAME} must be a string"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Extrude & Bevel's parameters. `bevel` is `"none"`, a [`BevelShape`] id, or `"custom"` with
|
||||
/// its points in [`BEVEL_PROFILE`].
|
||||
pub fn extrude_options(p: &Value) -> Extrude {
|
||||
Extrude {
|
||||
depth: num(p, "depth", 50.0),
|
||||
twist: num(p, "twist", 0.0),
|
||||
taper: num(p, "taper", 100.0) / 100.0,
|
||||
cap: flag(p, "cap", true),
|
||||
bevel: BevelShape::parse(text(p, "bevel", "none")).map(|shape| Bevel {
|
||||
bevel: bevel_shape(p).map(|shape| Bevel {
|
||||
shape,
|
||||
width: num(p, "bevelWidth", 4.0),
|
||||
height: num(p, "bevelHeight", 4.0),
|
||||
@@ -354,12 +415,12 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
graphics::validate(id, p)?;
|
||||
wireframe::validate_render(id, p)?;
|
||||
if let Some(v) = p.get("bevel")
|
||||
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
|
||||
&& !v.as_str().is_some_and(|s| s == "none" || s == "custom" || BevelShape::parse(s).is_some())
|
||||
{
|
||||
let names: Vec<_> = BevelShape::ALL.iter().map(|b| b.id()).collect();
|
||||
return Err(format!("bevel must be none or one of {}", names.join(", ")));
|
||||
return Err(format!("bevel must be none or one of {}, or custom with {BEVEL_PROFILE}", names.join(", ")));
|
||||
}
|
||||
Ok(())
|
||||
validate_bevel(p)
|
||||
}
|
||||
|
||||
/// The name an error gives 3D effect `id`.
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::Value;
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light};
|
||||
use vectorcraft_three_d::{Bevel, ClassicShading, ClassicSurface, Extrude, Facet, Light};
|
||||
|
||||
use super::graphics::map_art::{self, MapArt, MapBudget, SolidLayout};
|
||||
use crate::util::{flag, num, text};
|
||||
@@ -44,13 +44,7 @@ pub fn classic_extrude_options(p: &Value) -> Extrude {
|
||||
Extrude {
|
||||
depth: num(p, "depth", 50.0),
|
||||
cap: flag(p, "cap", true),
|
||||
bevel: BevelShape::parse(text(p, "bevel", "none")).map(|shape| Bevel {
|
||||
shape,
|
||||
width: height,
|
||||
height,
|
||||
inside: flag(p, "bevelInside", false),
|
||||
..Bevel::default()
|
||||
}),
|
||||
bevel: super::bevel_shape(p).map(|shape| Bevel { shape, width: height, height, inside: flag(p, "bevelInside", false), ..Bevel::default() }),
|
||||
hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe,
|
||||
// The numbered surfaces are laid out only for an effect that maps art onto them.
|
||||
map_surfaces: !map_art::surface_maps(p).is_empty(),
|
||||
@@ -119,9 +113,15 @@ const FLAGS: [&str; 7] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"
|
||||
/// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of
|
||||
/// its parameters, numbers are in range, flags are true or false, `surface`, `shadingColor` and
|
||||
/// `shadingCustom` name a surface, a shading color and a #rrggbb color, and `mapArt` holds valid
|
||||
/// maps.
|
||||
/// maps. A custom bevel's name and points ([`super::BEVEL_NAME`], [`super::BEVEL_PROFILE`]) are
|
||||
/// parameters too, checked with Extrude & Bevel's.
|
||||
pub fn validate(p: &Value) -> Result<(), String> {
|
||||
validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)?;
|
||||
let mut rest = p.clone();
|
||||
if let Some(m) = rest.as_object_mut() {
|
||||
m.remove(super::BEVEL_NAME);
|
||||
m.remove(super::BEVEL_PROFILE);
|
||||
}
|
||||
validate_classic(CLASSIC_EXTRUDE, &rest, &RANGES, &FLAGS)?;
|
||||
map_art::validate(CLASSIC_EXTRUDE, p)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
|
||||
use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints};
|
||||
@@ -144,18 +144,17 @@ impl Resolver<'_> {
|
||||
}
|
||||
|
||||
/// Does the plain image `c` lie wholly outside what the clips around it show together, each
|
||||
/// clipping path with its own fill rule? Its frame, the pixel rectangle as its transform places
|
||||
/// it, is cut to each clip in turn until nothing is left. An error when a cut fails or the cuts
|
||||
/// pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out.
|
||||
/// clipping path with its own fill rule? Its frame, the quadrilateral of its corners
|
||||
/// ([`Node::image_corners`]: a distorted image's corners, else the pixel rectangle as its
|
||||
/// transform places it), is cut to each clip in turn until nothing is left. An error when a
|
||||
/// cut fails or the cuts pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out.
|
||||
fn hidden(&mut self, c: &Node) -> Result<bool, String> {
|
||||
let Some(shown) = &self.shown else { return Ok(false) };
|
||||
let NodeKind::Image(im) = &c.kind else { return Ok(false) };
|
||||
let Some(corners) = c.image_corners() else { return Ok(false) };
|
||||
let Some(b) = c.visual_bounds() else { return Ok(true) };
|
||||
if b.intersect(shown.bounds).area() <= 0.0 {
|
||||
return Ok(true);
|
||||
}
|
||||
let (w, h) = (f64::from(im.width), f64::from(im.height));
|
||||
let corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| im.xf * Point::new(x, y));
|
||||
if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
|
||||
return Err(image_refusal(self.label));
|
||||
}
|
||||
|
||||
@@ -1646,6 +1646,58 @@ fn parameters_are_validated_and_lengths_scale_with_the_object() {
|
||||
assert!(extrude_options(&json!({})).bevel.is_none());
|
||||
}
|
||||
|
||||
/// `bevel` custom draws the points of `bevelProfile` in both Extrude & Bevels, with the other bevel
|
||||
/// settings; bad points, a custom bevel without points and a name that is not a string are refused.
|
||||
#[test]
|
||||
fn custom_bevels_draw_their_points_and_bad_points_are_refused() {
|
||||
let n = square_node();
|
||||
let notch = json!([[0, 0], [0.2, 0.6], [0.7, 0.4], [1, 1]]);
|
||||
let custom = json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch, "bevelWidth": 10, "bevelRepeat": 2, "bevelBothSides": true});
|
||||
let b = extrude_options(&custom).bevel.unwrap();
|
||||
assert!(matches!(b.shape, BevelShape::Custom(_)));
|
||||
assert_eq!((b.width, b.repeat, b.both_sides), (10.0, 2, true));
|
||||
let points: Vec<(f64, f64)> = match b.shape {
|
||||
BevelShape::Custom(p) => p.points().collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
assert_eq!(points.len(), 4);
|
||||
assert!((points[2].0 - 0.7).abs() < 1e-4 && (points[2].1 - 0.4).abs() < 1e-4, "{points:?}");
|
||||
assert!(matches!(classic_extrude_options(&custom).bevel.map(|b| b.shape), Some(BevelShape::Custom(_))));
|
||||
for id in [EXTRUDE, CLASSIC_EXTRUDE] {
|
||||
let classic_params = json!({"bevel": "classic", "bevelHeight": 10});
|
||||
let custom_params = json!({"bevel": "custom", "bevelProfile": notch, "bevelHeight": 10, "bevelName": "Notch"});
|
||||
assert!(validate_solid(&n, id, &custom_params).is_ok(), "{id}");
|
||||
let art = |p: &Value| {
|
||||
let mut n = square_node();
|
||||
n.appearance.effects.push(fx(id, p.clone()));
|
||||
solid_art(&n).unwrap()
|
||||
};
|
||||
assert_ne!(art(&classic_params), art(&custom_params), "{id}");
|
||||
for (bad, err) in [
|
||||
(json!({"bevel": "custom"}), "bevel custom needs bevelProfile"),
|
||||
(json!({"bevel": "custom", "bevelProfile": [[0, 0]]}), "bevelProfile must be 2 to 64"),
|
||||
(json!({"bevel": "custom", "bevelProfile": [[0.1, 0], [1, 1]]}), "bevelProfile must be 2 to 64"),
|
||||
(json!({"bevel": "custom", "bevelProfile": [[0, 0], [2, 0.5], [1, 1]]}), "bevelProfile must be 2 to 64"),
|
||||
(json!({"bevel": "custom", "bevelProfile": [[0, 0], ["a", 0.5], [1, 1]]}), "bevelProfile must be 2 to 64"),
|
||||
(json!({"bevel": "custom", "bevelProfile": "0,0 1,1"}), "bevelProfile must be 2 to 64"),
|
||||
(json!({"bevel": "custom", "bevelProfile": notch, "bevelName": 3}), "bevelName must be a string"),
|
||||
] {
|
||||
let e = validate_solid(&n, id, &bad).unwrap_err();
|
||||
assert!(e.contains(err), "{id} {bad}: {e}");
|
||||
}
|
||||
}
|
||||
// A loaded file whose points do not make a profile draws no bevel.
|
||||
assert!(extrude_options(&json!({"bevel": "custom", "bevelProfile": [[0, 0]]})).bevel.is_none());
|
||||
// Changing the type keeps the custom bevel where the new effect takes a bevel, and drops it
|
||||
// where it does not.
|
||||
let classic = three_d_params_as(EXTRUDE, &custom, CLASSIC_EXTRUDE);
|
||||
assert_eq!((&classic["bevel"], &classic[BEVEL_NAME], &classic[BEVEL_PROFILE]), (&json!("custom"), &json!("Notch"), ¬ch));
|
||||
assert!(validate_solid(&n, CLASSIC_EXTRUDE, &classic).is_ok());
|
||||
assert_eq!(three_d_params_as(CLASSIC_EXTRUDE, &classic, EXTRUDE)[BEVEL_PROFILE], notch);
|
||||
let inflate = three_d_params_as(EXTRUDE, &custom, INFLATE);
|
||||
assert!(inflate.get(BEVEL_PROFILE).is_none() && inflate.get(BEVEL_NAME).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inflate_reads_twist_taper_and_cap() {
|
||||
let o = inflate_options(&json!({"twist": 90, "taper": 40, "cap": false}));
|
||||
|
||||
@@ -504,6 +504,38 @@ fn warped_images_keep_document_keys_and_hidden_images_apart() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A distorted image that a later effect leaves with no area after its warp is not cut, and its
|
||||
/// corners stay finite.
|
||||
#[test]
|
||||
fn a_distorted_image_left_with_no_area_after_its_warp_keeps_finite_corners() {
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::NodeId;
|
||||
let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1));
|
||||
let mut image = (*warp_test_image(2)).clone();
|
||||
image.set_image_corners([(10.0, 0.0), (30.0, 0.0), (40.0, 40.0), (0.0, 40.0)].map(|(x, y)| Point::new(x, y))).unwrap();
|
||||
let mut art = Node::group(NodeId(1), vec![Arc::new(image)]);
|
||||
let mut warped = crate::reshape::WarpedImages::new();
|
||||
warped.reserve(&art);
|
||||
crate::reshape::mark_warped_images(&mut art, &lift, &std::collections::HashSet::new(), false, &mut 0, &mut warped);
|
||||
// A later effect squeezes the placement flat.
|
||||
if let Some(c) = art.children_mut()
|
||||
&& let NodeKind::Image(im) = &mut Arc::make_mut(&mut c[0]).kind
|
||||
{
|
||||
im.xf = Affine::scale_non_uniform(1.0, 0.0);
|
||||
}
|
||||
crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX);
|
||||
let mut finite = true;
|
||||
art.walk(&mut |c| {
|
||||
if let Some(q) = c.extras().image_quad.as_deref() {
|
||||
finite &= q.iter().all(|p| p.x.is_finite() && p.y.is_finite());
|
||||
}
|
||||
});
|
||||
assert!(finite);
|
||||
assert_eq!(warp_test_images(&art).0, 1, "not cut");
|
||||
}
|
||||
|
||||
/// An image whose frame keeps its shape because the warp would pass the anchor budget keeps its
|
||||
/// pixels as they are; within the budget, both bend.
|
||||
#[test]
|
||||
@@ -2121,3 +2153,27 @@ fn color_halftones_radius_is_in_raster_pixels_not_a_distance() {
|
||||
crate::scale_effect(&mut e, 2.0);
|
||||
assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pathfinder_effects_precision_is_a_distance_that_scales_with_the_object() {
|
||||
for (id, _, _) in PATHFINDER_EFFECTS {
|
||||
assert!(is_length(id, "precision", false), "{id}");
|
||||
assert_eq!(length_range(id, "precision"), Some(PATHFINDER_EFFECT_PRECISION), "{id}");
|
||||
assert!(!is_length(id, "removeRedundantPoints", false) && !is_length(id, "removeUnpainted", false), "{id}");
|
||||
// Scale Strokes & Effects scales the tolerance with the geometry it is refit to.
|
||||
let mut e = crate::new_effect(id, &json!({"precision": 0.5, "removeUnpainted": true})).unwrap();
|
||||
crate::scale_effect(&mut e, 4.0);
|
||||
assert_eq!(e.params["precision"].as_f64(), Some(2.0), "{id}");
|
||||
assert_eq!(e.params["removeUnpainted"], json!(true), "{id}");
|
||||
// An effect saved without the options scales the precision it evaluates with.
|
||||
let mut e = crate::new_effect(id, &json!({})).unwrap();
|
||||
crate::scale_effect(&mut e, 3.0);
|
||||
let scaled = e.params["precision"].as_f64().unwrap_or(f64::NAN);
|
||||
assert!((scaled - PathfinderEffectOptions::default().precision * 3.0).abs() < 1e-12, "{id}: {scaled}");
|
||||
// A scale past the range and its inverse restore the precision, as with other distances.
|
||||
let mut e = crate::new_effect(id, &json!({"precision": 8.0})).unwrap();
|
||||
crate::scale_effect(&mut e, 2.0);
|
||||
crate::scale_effect(&mut e, 0.5);
|
||||
assert_eq!(e.params["precision"].as_f64(), Some(8.0), "{id}");
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ pub mod arrowheads;
|
||||
mod artboardalign;
|
||||
mod assets;
|
||||
mod attributes;
|
||||
pub mod bevels;
|
||||
pub mod brushlib;
|
||||
mod brushsym;
|
||||
mod buildcmds;
|
||||
@@ -321,6 +322,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(draw2::specs());
|
||||
v.extend(xform::specs());
|
||||
v.extend(effectcmd::specs());
|
||||
v.extend(bevels::specs());
|
||||
v.extend(wireframe::specs());
|
||||
v.extend(pathops::specs());
|
||||
v.extend(compoundshape::specs());
|
||||
@@ -890,6 +892,9 @@ pub use compoundshape::OPEN_PATHS_ADD_NO_AREA;
|
||||
/// Pathfinder Options (`Prefs::pathfinder`).
|
||||
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
|
||||
|
||||
/// The Pathfinder Options a new Pathfinder effect takes (`effect.apply`).
|
||||
pub use effectcmd::pathfinder_effect_options;
|
||||
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps.
|
||||
pub use attributes::RECENT_URLS;
|
||||
pub use overprint::AttributesInfo;
|
||||
@@ -906,6 +911,10 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry};
|
||||
/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets.
|
||||
pub use buildcmds::{TracePreset, TracePresetChange};
|
||||
|
||||
/// The `format`, extensions and largest size of the tracing presets files
|
||||
/// `imageTrace.presets.export` writes and `imageTrace.presets.import` reads.
|
||||
pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES};
|
||||
|
||||
/// An Image Trace made off the UI thread, and what it traced (#3098).
|
||||
pub use buildcmds::{TraceRun, Traced, image_trace_target};
|
||||
|
||||
|
||||
@@ -109,11 +109,11 @@ impl<'a> Reader<'a> {
|
||||
Ok(union(parts))
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let (w, h) = (f64::from(im.width), f64::from(im.height));
|
||||
let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| im.xf * p);
|
||||
self.polygon(&corners)
|
||||
}
|
||||
// A distorted image's frame joins its corners.
|
||||
NodeKind::Image(_) => match n.image_corners() {
|
||||
Some(corners) => self.polygon(&corners),
|
||||
None => Ok(None),
|
||||
},
|
||||
// An instance of a symbol the document doesn't have draws nothing.
|
||||
NodeKind::SymbolInstance { .. } => match vectorcraft_render::effects::outline_object(Some(self.doc), n) {
|
||||
Some(art) => self.node(&art, depth + 1),
|
||||
|
||||
@@ -663,6 +663,29 @@ fn an_image_is_measured_by_its_frame_as_turned() {
|
||||
assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_distorted_image_is_measured_by_the_frame_through_its_corners() {
|
||||
let mut s = session();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "image".into(),
|
||||
width: 100,
|
||||
height: 100,
|
||||
xf: Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
insert(&mut s, |id| {
|
||||
let mut n = Node::new(id, NodeKind::Image(Box::new(im)));
|
||||
n.set_image_corners([Point::new(40.0, 0.0), Point::new(60.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]).unwrap();
|
||||
n
|
||||
});
|
||||
let (b, end) = diamond_weeding(&mut s);
|
||||
assert!((b.x0 + 10.0).abs() < 1e-3 && (b.y1 - 110.0).abs() < 1e-3, "{b:?}");
|
||||
// A quarter of the box down (y = 20), the line meets the side from (40, 0) to (0, 100).
|
||||
assert!((end - 32.0).abs() < 0.01, "{end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_file_is_measured_by_the_art_it_shows() {
|
||||
let dir = crate::tests_links::Folder::new("weed-placed");
|
||||
|
||||
@@ -29,6 +29,7 @@ use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::appearance::SharedStack;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_tools::builder::{edges, faces, is_live_paint};
|
||||
|
||||
use super::edit::{outermost, roots_of, selected_roots};
|
||||
use super::opacitymask::percent;
|
||||
@@ -48,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). In the contents of a Live Paint group the fill goes on its faces only, and its hidden source paths, like every contents edit, are left as they are. With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -57,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. In the contents of a Live Paint group the stroke goes on its edges only, and its hidden source paths are left as they are. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -129,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; a whole Live Paint group (selected, in ids, or `source` with `reverse`) takes the fill attributes on its faces and the stroke attributes on its edges (a whole-appearance pick: every fill row on each face and every stroke row on each edge, which keep their rows of the other kind and their effects; `append` adds the source's rows but not its object effects to them), and its hidden source paths keep their paint; a whole Live Paint group picked up (`source`, or selected first with `reverse`) gives its first face's fills with its first edge's strokes above them and the group's own opacity, blend mode and effects; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -280,7 +281,8 @@ impl ItemTarget {
|
||||
|
||||
/// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a
|
||||
/// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
|
||||
/// ([`super::paint::live_paint_parts_skipped`]).
|
||||
/// ([`super::paint::live_paint_parts_skipped`]); an item edit with `target: "contents"` leaves out
|
||||
/// the parts of the other kind the same way ([`contents_skipped`]).
|
||||
pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result<Vec<NodeId>> {
|
||||
Ok(self.targets_and_skipped(s, p, fill)?.0)
|
||||
}
|
||||
@@ -290,13 +292,16 @@ impl ItemTarget {
|
||||
/// to new art.
|
||||
pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec<NodeId>, bool)> {
|
||||
let mut ids = self.targets(s, p)?;
|
||||
let mut skipped_any = false;
|
||||
if self == ItemTarget::Top {
|
||||
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill);
|
||||
let before = ids.len();
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
skipped_any = ids.len() != before;
|
||||
}
|
||||
// An item edit of the contents of a Live Paint group goes to its parts of the edited kind too.
|
||||
let skipped = if self == ItemTarget::Top {
|
||||
super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill)
|
||||
} else {
|
||||
contents_skipped(s, p, fill)?
|
||||
};
|
||||
let before = ids.len();
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
// A contents edit already leaves hidden source paths out of `ids`, so `skipped` is checked on its own too.
|
||||
let skipped_any = ids.len() != before || !skipped.is_empty();
|
||||
Ok((ids, skipped_any))
|
||||
}
|
||||
|
||||
@@ -491,15 +496,37 @@ pub(crate) fn subject_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
|
||||
/// Objects whose own appearance stack a command edits: `ids`/`id` (layers too; an id inside
|
||||
/// another given one is dropped), else the [`subject_roots`]; with `target: "contents"` the painted
|
||||
/// objects inside the groups and layers among them ([`leaf_targets`]).
|
||||
/// objects inside the groups and layers among them ([`leaf_targets`]), without the hidden source paths
|
||||
/// of Live Paint groups.
|
||||
pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let roots = if p.get("ids").is_none() && p.get("id").is_none() {
|
||||
subject_roots(s)?
|
||||
let roots = appearance_roots(s, p)?;
|
||||
if !targets_contents(p)? {
|
||||
return Ok(roots);
|
||||
}
|
||||
let (_, _, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
|
||||
let mut ids = leaf_targets(s, &roots)?;
|
||||
ids.retain(|id| !hidden.contains(id));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The objects [`appearance_targets`] starts from: `ids`/`id`, else the [`subject_roots`].
|
||||
fn appearance_roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
if p.get("ids").is_none() && p.get("id").is_none() {
|
||||
subject_roots(s)
|
||||
} else {
|
||||
let d = &s.doc()?.doc;
|
||||
outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect())
|
||||
};
|
||||
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
|
||||
Ok(outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of the Live Paint groups whose contents `p` targets (`target: "contents"`) that a fill
|
||||
/// (`fill`) or stroke edit of those contents leaves as they are: their edges or faces. Empty without
|
||||
/// `target: "contents"`.
|
||||
pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result<HashSet<NodeId>> {
|
||||
if !targets_contents(p)? {
|
||||
return Ok(HashSet::new());
|
||||
}
|
||||
Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill))
|
||||
}
|
||||
|
||||
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
|
||||
@@ -897,7 +924,26 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?;
|
||||
let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" };
|
||||
let mut ids = row_targets(s, p, cmd)?;
|
||||
if ids.is_empty() {
|
||||
// A selected Live Paint group left with only its hidden source paths has nothing to edit: it is
|
||||
// still a selection, so the edit changes nothing.
|
||||
let roots = appearance_roots(s, p)?;
|
||||
if targets_contents(p)? && !roots.is_empty() && !super::paint::live_paint_split(&s.doc()?.doc, &roots).2.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
// In the contents of a Live Paint group, a new fill goes on its faces and a new stroke on its edges;
|
||||
// with no part of that kind, nothing changes.
|
||||
let skipped = contents_skipped(s, p, fill)?;
|
||||
if !skipped.is_empty() {
|
||||
ids.retain(|id| !skipped.contains(id));
|
||||
if ids.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
let defaults = s.paint.clone();
|
||||
// The panel's active Fill row, when the new fill goes on the selection: the new fill takes that
|
||||
// row's paint, right above it in each target that has it (others take their top fill's paint).
|
||||
@@ -1779,7 +1825,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Reversed, the first selected object's attributes go onto the clicked object; with nothing
|
||||
// selected, what the Eyedropper picked up last does (#4382).
|
||||
let (source, mut targets) = if reverse {
|
||||
let source = match leaf_targets(s, &selected)?.into_iter().next() {
|
||||
// The selected objects are tried in order: a Live Paint group with a look is picked up as a whole
|
||||
// ([`live_paint_look`]), any other object gives its first painted leaf, and a group with nothing to pick
|
||||
// up (its hidden source paths are not what it draws) passes to the next object.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut first = None;
|
||||
for root in &selected {
|
||||
if d.node(*root).and_then(live_paint_look).is_some() {
|
||||
first = Some(*root);
|
||||
break;
|
||||
}
|
||||
let (_, _, hidden) = super::paint::live_paint_split(d, &[*root]);
|
||||
if let Some(leaf) = leaf_targets(s, &[*root])?.into_iter().find(|id| !hidden.contains(id)) {
|
||||
first = Some(leaf);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let source = match first {
|
||||
Some(first) => Some(first),
|
||||
None if s.eyedropper_sample.is_some() => None,
|
||||
None => return Err(bad(C, "select the object to copy from")),
|
||||
@@ -1788,10 +1850,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
(Some(clicked), leaf_targets(s, &selected)?)
|
||||
};
|
||||
targets.retain(|id| Some(*id) != source);
|
||||
// A whole Live Paint group takes the fill attributes on its faces and the stroke attributes on its edges, and its
|
||||
// hidden source paths keep their paint.
|
||||
let roots = if reverse { vec![clicked] } else { selected };
|
||||
let (faces, edges, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
|
||||
// Some(true) for a face, Some(false) for an edge.
|
||||
let part_of = |id: &NodeId| {
|
||||
if faces.contains(id) {
|
||||
Some(true)
|
||||
} else if edges.contains(id) {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let attrs_for = |id: &NodeId| {
|
||||
let mut a = attrs;
|
||||
match part_of(id) {
|
||||
Some(true) => a.appearance.stroke = StrokeAttrs::NONE,
|
||||
Some(false) => a.appearance.fill = FillAttrs::NONE,
|
||||
None => {}
|
||||
}
|
||||
a
|
||||
};
|
||||
// A pick of the whole appearance gives a face every fill row and an edge every stroke row.
|
||||
let whole = attrs.appearance.fill == FillAttrs::ALL && attrs.appearance.stroke == StrokeAttrs::ALL;
|
||||
// A source that is a Live Paint group is not one of its own targets: neither are its faces and edges.
|
||||
let mut inside_source = HashSet::new();
|
||||
if let Some(n) = source.and_then(|id| s.doc().ok()?.doc.node(id)).filter(|n| is_live_paint(n)) {
|
||||
n.walk(&mut |c| {
|
||||
inside_source.insert(c.id);
|
||||
});
|
||||
}
|
||||
targets.retain(|id| Some(*id) != source && !hidden.contains(id) && !inside_source.contains(id));
|
||||
let mut targets = without_design_art(&s.doc()?.doc, targets, C)?;
|
||||
let node = match source {
|
||||
Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()),
|
||||
Some(id) => {
|
||||
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
Arc::new(live_paint_look(n).unwrap_or_else(|| n.clone()))
|
||||
}
|
||||
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
|
||||
};
|
||||
let picked = Picked::of(&node);
|
||||
@@ -1919,7 +2016,17 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::overprint::edit_counted(s, "Eyedropper", |d| {
|
||||
for id in &targets {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
picked.apply(n, &attrs, append, characters.get(id));
|
||||
match part_of(id) {
|
||||
Some(fill) if whole && !append => picked.apply_rows(n, &attrs, fill),
|
||||
// `append` does not add the picked object effects to a face or edge, as a whole pick keeps the part's
|
||||
// own; a row's effects go with the row.
|
||||
Some(_) => {
|
||||
let effects = n.appearance.effects.len();
|
||||
picked.apply(n, &attrs_for(id), append, characters.get(id));
|
||||
n.appearance.effects.truncate(effects);
|
||||
}
|
||||
None => picked.apply(n, &attrs_for(id), append, characters.get(id)),
|
||||
}
|
||||
}
|
||||
}
|
||||
check_text_bounds(d)?;
|
||||
@@ -2170,6 +2277,52 @@ impl Picked {
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
|
||||
/// A whole pick ([`Self::apply`] with every fill and stroke attribute) onto a Live Paint face
|
||||
/// (`fill`) or edge: the face's fills (the edge's strokes) become the picked ones, and its rows of
|
||||
/// the other kind and its effects stay as they are.
|
||||
fn apply_rows(&self, n: &mut Node, a: &EyedropperAttrs, fill: bool) {
|
||||
if a.appearance.transparency {
|
||||
n.opacity = self.opacity;
|
||||
n.blend = self.blend;
|
||||
}
|
||||
let taken: Vec<AppearanceItem> = self.placed(n.geometric_bounds()).items.into_iter().filter(|it| it.is_fill() == fill).collect();
|
||||
// The picked rows go where the part's first row of that kind was, the other rows keep their order; without
|
||||
// such a row, fills go to the bottom and strokes to the top.
|
||||
let items = &n.appearance.items;
|
||||
let at = items.iter().position(|it| it.is_fill() == fill);
|
||||
let at = at.map_or(if fill { 0 } else { items.iter().filter(|it| it.is_fill() != fill).count() }, |i| {
|
||||
items.iter().take(i).filter(|it| it.is_fill() != fill).count()
|
||||
});
|
||||
let mut kept: Vec<AppearanceItem> = items.iter().filter(|it| it.is_fill() != fill).cloned().collect();
|
||||
kept.splice(at..at, taken);
|
||||
n.appearance.items = kept;
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Eyedropper picks up from a whole Live Paint group `n`: its first face (else its first edge) with that
|
||||
/// face's fills and the first edge's strokes above them, their gradients placed as on those parts, and the group's
|
||||
/// own opacity, blend mode and effects. None for any other object, and for a group with no face and no edge.
|
||||
fn live_paint_look(n: &Node) -> Option<Node> {
|
||||
if !is_live_paint(n) {
|
||||
return None;
|
||||
}
|
||||
let (face, edge) = (faces(n).first().copied(), edges(n).first().copied());
|
||||
let mut look = (**face.or(edge)?).clone();
|
||||
let rows = |part: Option<&Arc<Node>>, fill: bool| -> Vec<AppearanceItem> {
|
||||
part.map(|p| p.appearance.items.iter().filter(|it| it.is_fill() == fill).cloned().collect()).unwrap_or_default()
|
||||
};
|
||||
// The edge's stroke gradients, placed relative to the look's bounds as they are to the edge's.
|
||||
let mut strokes = Appearance { items: rows(edge, false), ..Default::default() };
|
||||
if let (Some(from), Some(to)) = (edge.and_then(|e| e.geometric_bounds()), look.geometric_bounds()) {
|
||||
strokes.rebase_gradients(from, to);
|
||||
}
|
||||
look.appearance.items = rows(face, true).into_iter().chain(strokes.items).collect();
|
||||
look.appearance.effects = n.appearance.effects.clone();
|
||||
look.opacity = n.opacity;
|
||||
look.blend = n.blend;
|
||||
Some(look)
|
||||
}
|
||||
|
||||
/// The focal (topmost) fill and stroke attributes `a` of `from` onto `to`. Taking a colour creates
|
||||
|
||||
@@ -378,13 +378,14 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn same_file(a: &str, b: &str) -> bool {
|
||||
pub(super) fn same_file(a: &str, b: &str) -> bool {
|
||||
let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| std::path::PathBuf::from(p));
|
||||
std::path::Path::new(a) == std::path::Path::new(b) || canon(a) == canon(b)
|
||||
}
|
||||
|
||||
/// The document in the arrowheads file at `path`; `None` when there is no file.
|
||||
fn read(path: &str) -> std::result::Result<Option<Document>, String> {
|
||||
/// The document in the arrowheads file at `path` (or another such file of the user's, as the
|
||||
/// bevels file); `None` when there is no file.
|
||||
pub(super) fn read(path: &str) -> std::result::Result<Option<Document>, String> {
|
||||
let size = match std::fs::metadata(path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(format!("{path}: {e}")),
|
||||
@@ -412,13 +413,13 @@ fn skipped(s: &Session) -> Vec<Value> {
|
||||
/// The arrowheads file at `path` checked for reading against the automation roots in force: an agent
|
||||
/// confined to read roots reaches the file only inside them. The error names the file by its file
|
||||
/// name outside them.
|
||||
fn may_reach(path: &str) -> Result<()> {
|
||||
pub(super) fn may_reach(path: &str) -> Result<()> {
|
||||
crate::file_access::check_read(path).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), path))
|
||||
}
|
||||
|
||||
/// `msg`, an error about the arrowheads file at `path`, as the request being served may see it: the
|
||||
/// file named whole inside the read roots, else by its file name.
|
||||
fn shown_error(msg: &str, path: Option<&str>) -> String {
|
||||
pub(super) fn shown_error(msg: &str, path: Option<&str>) -> String {
|
||||
let Some(path) = path else { return msg.to_string() };
|
||||
match super::fileio::naming_in_error(EngineError::Other(msg.to_string()), path) {
|
||||
EngineError::Other(m) => m,
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
//! Custom bevels for Extrude & Bevel and Extrude & Bevel (Classic). The bevels file is a native
|
||||
//! document kept next to the preferences ([`Session::attach_bevels_file`]). Each of its symbols
|
||||
//! whose art is one open path is one bevel, listed by the symbol's name after the built-in shapes
|
||||
//! in the Bevel Shape menus. The path runs from its first anchor, at the cap's edge, to its last,
|
||||
//! at the side wall: across the page is across the bevel's width and down the page is along its
|
||||
//! height, whichever way the path is drawn, and points past its ends are held to them. Curves are
|
||||
//! cut into straight lines, at most [`BevelProfile::MAX_POINTS`] points in all. Saving the file
|
||||
//! reloads the bevels. An effect that uses a custom bevel carries a copy of its points
|
||||
//! (`bevelProfile`), so its document draws it anywhere.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol};
|
||||
use vectorcraft_geom::{Affine, PathData, PathEl, Point, SubPath};
|
||||
use vectorcraft_render::effects::{BEVEL_NAME, BEVEL_PROFILE, BevelProfile};
|
||||
|
||||
use super::arrowheads::{may_reach, read, same_file, shown_error};
|
||||
use super::{CommandSpec, Result, Session, always, bad, cmd};
|
||||
|
||||
/// The bevels file's name, in the folder of the preferences.
|
||||
pub const FILE_NAME: &str = "Bevels.vectorcraft";
|
||||
/// The most bevels read from the file; symbols past it are skipped.
|
||||
pub const MAX_BEVELS: usize = 256;
|
||||
/// The most anchors a bevel's path may have; a symbol past it is skipped.
|
||||
pub const MAX_ANCHORS: usize = 4096;
|
||||
/// The most points a bevel's path is cut into before it is simplified; a symbol past it is skipped.
|
||||
pub const MAX_LINE_POINTS: usize = 8192;
|
||||
/// The most point-to-line distances simplifying the bevels of one file may measure; a symbol that
|
||||
/// needs more than is left is skipped as too detailed.
|
||||
pub const MAX_SIMPLIFY_WORK: u64 = 40_000_000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "threeD.bevels.list",
|
||||
"Bevels",
|
||||
[],
|
||||
None,
|
||||
"{} → {bevels: [{name (effect.apply and effect.setParams take Extrude & Bevel's and Extrude & Bevel (Classic)'s `bevel` as {custom: name}), points: [[x, y]…] (shares of the bevel's width and height from the cap's edge [0, 0] to the side wall [1, 1])}], file: the bevels file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not bevels, error: why the file could not be read, or null} the custom bevels, listed after the built-in shapes in the Bevel Shape menus",
|
||||
always,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
"threeD.bevels.edit",
|
||||
"Edit Bevels",
|
||||
[],
|
||||
None,
|
||||
"{} open the bevels file (a native document next to the preferences; created first with one example bevel when it is missing). Each symbol in it whose art is one open path is one custom bevel named after the symbol: the path runs from its first anchor at the cap's edge to its last at the side wall, across the page across the bevel's width and down the page along its height. Saving the file reloads the bevels → {path, created: whether the file was made now}",
|
||||
has_file,
|
||||
edit
|
||||
),
|
||||
cmd!(
|
||||
"threeD.bevels.reload",
|
||||
"Reload Bevels",
|
||||
[],
|
||||
None,
|
||||
"{} read the bevels file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}",
|
||||
has_file,
|
||||
reload
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// A custom bevel: its name and its points, (share of the width, share of the height).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CustomBevel {
|
||||
pub name: String,
|
||||
pub points: Vec<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl CustomBevel {
|
||||
/// The points as `bevelProfile` holds them.
|
||||
pub fn profile_json(&self) -> Value {
|
||||
json!(self.points.iter().map(|&(x, y)| [x, y]).collect::<Vec<_>>())
|
||||
}
|
||||
}
|
||||
|
||||
/// The custom bevels read from the bevels file.
|
||||
#[derive(Default)]
|
||||
pub struct Bevels {
|
||||
path: Option<String>,
|
||||
bevels: Vec<Arc<CustomBevel>>,
|
||||
skipped: Vec<(String, String)>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
impl Bevels {
|
||||
/// The bevels file's path; `None` without one (the web, runs without preferences).
|
||||
pub fn path(&self) -> Option<&str> {
|
||||
self.path.as_deref()
|
||||
}
|
||||
/// The bevels, in the order of the file's symbols.
|
||||
pub fn bevels(&self) -> &[Arc<CustomBevel>] {
|
||||
&self.bevels
|
||||
}
|
||||
/// Bevel `name`.
|
||||
pub fn get(&self, name: &str) -> Option<Arc<CustomBevel>> {
|
||||
self.bevels.iter().find(|b| b.name == name).cloned()
|
||||
}
|
||||
fn set(&mut self, read: Read) {
|
||||
(self.bevels, self.skipped) = (read.bevels.into_iter().map(Arc::new).collect(), read.skipped);
|
||||
self.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The bevels a document holds, and the symbols that are not bevels with the reason.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Read {
|
||||
pub bevels: Vec<CustomBevel>,
|
||||
pub skipped: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// The bevels of document `doc`: one per symbol, up to [`MAX_BEVELS`] (see the module docs).
|
||||
pub fn bevels_of(doc: &Document) -> Read {
|
||||
bevels_within(doc, MAX_SIMPLIFY_WORK)
|
||||
}
|
||||
|
||||
/// [`bevels_of`] with `work` point-to-line distances to simplify the paths with.
|
||||
pub fn bevels_within(doc: &Document, mut work: u64) -> Read {
|
||||
let mut out = Read::default();
|
||||
for (i, sym) in doc.symbols.iter().enumerate() {
|
||||
if i >= MAX_BEVELS {
|
||||
out.skipped.push((sym.name.clone(), format!("only the first {MAX_BEVELS} symbols are read")));
|
||||
continue;
|
||||
}
|
||||
if out.bevels.iter().any(|b| b.name == sym.name) {
|
||||
out.skipped.push((sym.name.clone(), "another symbol has this name".into()));
|
||||
continue;
|
||||
}
|
||||
match points_of(&sym.art, &mut work) {
|
||||
Ok(points) => out.bevels.push(CustomBevel { name: sym.name.clone(), points }),
|
||||
Err(why) => out.skipped.push((sym.name.clone(), why.into())),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The one open path of art `n`: `n` itself, or the one member of groups that hold one member each.
|
||||
fn open_path(n: &Node) -> Option<&PathData> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, .. } if path.subpaths.len() == 1 && !path.subpaths[0].closed => Some(path),
|
||||
NodeKind::Group { children, clip: false } if children.len() == 1 => open_path(&children[0]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The profile points of a bevel symbol's art `n` (see the module docs), simplified within `work`
|
||||
/// point-to-line distances, which it uses up.
|
||||
fn points_of(n: &Node, work: &mut u64) -> std::result::Result<Vec<(f64, f64)>, &'static str> {
|
||||
let path = open_path(n).ok_or("its art is not one open path")?;
|
||||
if path.anchor_count() > MAX_ANCHORS {
|
||||
return Err("its path has too many anchors for a bevel");
|
||||
}
|
||||
let mut line: Vec<Point> = vec![];
|
||||
let tolerance = path.bounds().map_or(1.0, |b| b.width().hypot(b.height()) / 2000.0).max(1e-9);
|
||||
// One segment at a time, so a path past the limit stops being cut at the segment that passes it.
|
||||
let mut at: Option<Point> = None;
|
||||
for &el in path.to_bezpath().elements() {
|
||||
if line.len() > MAX_LINE_POINTS {
|
||||
return Err("its path is too detailed for a bevel");
|
||||
}
|
||||
match (el, at) {
|
||||
(PathEl::MoveTo(p), _) => line.push(p),
|
||||
(_, Some(start)) => vectorcraft_geom::flatten([PathEl::MoveTo(start), el], tolerance, |e| {
|
||||
if let PathEl::LineTo(p) = e {
|
||||
line.push(p);
|
||||
}
|
||||
}),
|
||||
(_, None) => {}
|
||||
}
|
||||
at = el.end_point().or(at);
|
||||
}
|
||||
if line.len() > MAX_LINE_POINTS {
|
||||
return Err("its path is too detailed for a bevel");
|
||||
}
|
||||
let (Some(&first), Some(&last)) = (line.first(), line.last()) else { return Err("its path has no length") };
|
||||
let (dx, dy) = (last.x - first.x, last.y - first.y);
|
||||
let size = path.bounds().map_or(0.0, |b| b.width().hypot(b.height()));
|
||||
if !(dx.abs() > size * 1e-6 && dy.abs() > size * 1e-6 && size.is_finite()) {
|
||||
return Err("its ends are not apart both across and down");
|
||||
}
|
||||
let mut pts: Vec<(f64, f64)> = line.iter().map(|p| (((p.x - first.x) / dx).clamp(0.0, 1.0), ((p.y - first.y) / dy).clamp(0.0, 1.0))).collect();
|
||||
pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9);
|
||||
if pts.len() < 2 {
|
||||
return Err("its ends are not apart both across and down");
|
||||
}
|
||||
// The ends map to the corners exactly.
|
||||
let last = pts.len() - 1;
|
||||
(pts[0], pts[last]) = ((0.0, 0.0), (1.0, 1.0));
|
||||
let pts = simplified(&pts, work).ok_or("its path is too detailed for a bevel")?;
|
||||
BevelProfile::new(&pts).ok_or("its path is too detailed for a bevel")?;
|
||||
Ok(pts)
|
||||
}
|
||||
|
||||
/// `pts` with the fewest points the Ramer-Douglas-Peucker rule keeps at a tolerance (from a
|
||||
/// thousandth of the bevel, doubled until they fit) that leaves at most
|
||||
/// [`BevelProfile::MAX_POINTS`]. The first and last points are always kept. `None` when that
|
||||
/// measures more point-to-line distances than `work` has left.
|
||||
fn simplified(pts: &[(f64, f64)], work: &mut u64) -> Option<Vec<(f64, f64)>> {
|
||||
let mut eps = 1e-3;
|
||||
loop {
|
||||
let out = rdp(pts, eps, work)?;
|
||||
if out.len() <= BevelProfile::MAX_POINTS || eps > 2.0 {
|
||||
return Some(out);
|
||||
}
|
||||
eps *= 2.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The points of `pts` Ramer-Douglas-Peucker keeps at tolerance `eps`; `None` when that measures
|
||||
/// more point-to-line distances than `work` has left.
|
||||
fn rdp(pts: &[(f64, f64)], eps: f64, work: &mut u64) -> Option<Vec<(f64, f64)>> {
|
||||
if pts.len() < 3 {
|
||||
return Some(pts.to_vec());
|
||||
}
|
||||
let mut keep = vec![false; pts.len()];
|
||||
keep[0] = true;
|
||||
keep[pts.len() - 1] = true;
|
||||
let mut stack = vec![(0, pts.len() - 1)];
|
||||
while let Some((a, b)) = stack.pop() {
|
||||
*work = work.checked_sub((b - a).saturating_sub(1) as u64)?;
|
||||
let (p, q) = (pts[a], pts[b]);
|
||||
let (vx, vy) = (q.0 - p.0, q.1 - p.1);
|
||||
let len = vx.hypot(vy);
|
||||
let far = (a + 1..b)
|
||||
.map(|i| {
|
||||
let (wx, wy) = (pts[i].0 - p.0, pts[i].1 - p.1);
|
||||
let d = if len > 0.0 { (vx * wy - vy * wx).abs() / len } else { wx.hypot(wy) };
|
||||
(i, d)
|
||||
})
|
||||
.fold(None, |best: Option<(usize, f64)>, (i, d)| if best.is_none_or(|(_, bd)| d > bd) { Some((i, d)) } else { best });
|
||||
if let Some((i, d)) = far
|
||||
&& d > eps
|
||||
{
|
||||
keep[i] = true;
|
||||
stack.push((a, i));
|
||||
stack.push((i, b));
|
||||
}
|
||||
}
|
||||
Some(pts.iter().zip(keep).filter_map(|(p, k)| k.then_some(*p)).collect())
|
||||
}
|
||||
|
||||
/// The document a missing bevels file starts as: one example bevel, a chamfer with a notch.
|
||||
pub fn starter() -> Document {
|
||||
let mut doc = Document::new(612.0, 792.0);
|
||||
doc.title = "Bevels".into();
|
||||
let name = "Example Bevel";
|
||||
let pts = [Point::new(0.0, 0.0), Point::new(10.0, 40.0), Point::new(55.0, 30.0), Point::new(100.0, 100.0)];
|
||||
let art =
|
||||
Node::path(NodeId(0), PathData::single(SubPath::polyline(&pts, false)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
|
||||
let art = doc.reid(&art);
|
||||
doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false });
|
||||
let id = doc.alloc_id();
|
||||
let instance = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate((256.0, 346.0)) });
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let _ = doc.insert(layer, 0, instance);
|
||||
doc
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Keep the custom bevels in the file at `path` and read the bevels it holds (none while it is
|
||||
/// missing; an unreadable file is reported by `threeD.bevels.list`).
|
||||
pub fn attach_bevels_file(&mut self, path: String) {
|
||||
self.bevels.path = Some(path);
|
||||
self.reload_bevels();
|
||||
}
|
||||
|
||||
/// Read the bevels file again.
|
||||
fn reload_bevels(&mut self) {
|
||||
let Some(path) = self.bevels.path.clone() else { return };
|
||||
match read(&path) {
|
||||
Ok(Some(doc)) => self.bevels.set(bevels_of(&doc)),
|
||||
Ok(None) => self.bevels.set(Read::default()),
|
||||
Err(e) => {
|
||||
self.bevels.set(Read::default());
|
||||
self.bevels.error = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document was saved to `path`: when that is the bevels file, its bevels are read back from
|
||||
/// what was written.
|
||||
pub(crate) fn bevels_saved(&mut self, path: &str) {
|
||||
if self.bevels.path.as_deref().is_some_and(|b| same_file(b, path)) {
|
||||
self.reload_bevels();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The command parameter that holds the points a custom bevel given by name had when the command
|
||||
/// ran. The journal records it, so a replay draws the same bevel after the bevels file changes or
|
||||
/// loses that name.
|
||||
pub const SAVED_BEVEL: &str = "savedBevel";
|
||||
|
||||
/// `params` of an effect with `bevel` given as `{custom: name}`: the bevel of the bevels file named
|
||||
/// so, stored as `bevel` `"custom"` with its `bevelName` and `bevelProfile`. The command's
|
||||
/// [`SAVED_BEVEL`] points (`p`), when given, are used in place of the file's, and the points used
|
||||
/// join the journal entry as [`SAVED_BEVEL`]. Other values are left for the effect to check.
|
||||
pub(crate) fn resolve_custom(s: &mut Session, p: &Value, params: &mut Value, cmd: &str) -> Result<()> {
|
||||
let Some(Value::Object(o)) = params.get("bevel") else { return Ok(()) };
|
||||
let name = match (o.len(), o.get("custom")) {
|
||||
(1, Some(Value::String(name))) => name.clone(),
|
||||
_ => return Err(bad(cmd, "bevel: give a shape id, or {custom: name} for a bevel of the bevels file (threeD.bevels.list)")),
|
||||
};
|
||||
let points = match p.get(SAVED_BEVEL).filter(|v| !v.is_null()) {
|
||||
Some(saved) => saved.clone(),
|
||||
None => s.bevels.get(&name).ok_or_else(|| bad(cmd, format!("no custom bevel {name} (see threeD.bevels.list)")))?.profile_json(),
|
||||
};
|
||||
s.note_journal(SAVED_BEVEL, points.clone());
|
||||
params["bevel"] = json!("custom");
|
||||
params[BEVEL_NAME] = json!(name);
|
||||
params[BEVEL_PROFILE] = points;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_file(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.bevels.path.is_some() { Ok(()) } else { Err("no bevels file here".into()) }
|
||||
}
|
||||
|
||||
fn skipped(s: &Session) -> Vec<Value> {
|
||||
s.bevels.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect()
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let bevels: Vec<Value> = s.bevels.bevels.iter().map(|b| json!({"name": b.name, "points": b.profile_json()})).collect();
|
||||
// Under automation read roots, a file outside them is not shown and its error names it by its file name.
|
||||
let path = s.bevels.path.as_deref();
|
||||
let file = path.filter(|p| crate::file_access::check_read(p).is_ok());
|
||||
let error = s.bevels.error.as_deref().map(|e| shown_error(e, path));
|
||||
Ok(json!({"bevels": bevels, "file": file, "skipped": skipped(s), "error": error}))
|
||||
}
|
||||
|
||||
fn reload(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const C: &str = "threeD.bevels.reload";
|
||||
if let Some(path) = &s.bevels.path {
|
||||
may_reach(path)?;
|
||||
}
|
||||
s.reload_bevels();
|
||||
if let Some(e) = &s.bevels.error {
|
||||
return Err(bad(C, e.clone()));
|
||||
}
|
||||
Ok(json!({"count": s.bevels.bevels.len(), "skipped": skipped(s)}))
|
||||
}
|
||||
|
||||
fn edit(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const C: &str = "threeD.bevels.edit";
|
||||
let path = s.bevels.path.clone().ok_or_else(|| bad(C, "no bevels file here"))?;
|
||||
// Checked before anything is made, brought to the front or opened.
|
||||
may_reach(&path)?;
|
||||
if let Some(dir) = std::path::Path::new(&path).parent() {
|
||||
let dir = dir.to_string_lossy();
|
||||
std::fs::create_dir_all(&*dir).map_err(|e| super::fileio::naming_in_error(bad(C, format!("{dir}: {e}")), &dir))?;
|
||||
}
|
||||
// Made only when no file is there, also when another run makes one at the same moment.
|
||||
let bytes = vectorcraft_format::save_file(&starter());
|
||||
let created = match crate::file_access::unconfined(|| super::fileio::write_new_file(&path, &bytes)) {
|
||||
Ok(()) => true,
|
||||
Err(_) if std::path::Path::new(&path).exists() => false,
|
||||
Err(e) => return Err(bad(C, e.to_string())),
|
||||
};
|
||||
if created {
|
||||
s.reload_bevels();
|
||||
}
|
||||
// Already open: that document comes to the front.
|
||||
let open = s.documents().iter().position(|st| st.path.as_deref().is_some_and(|p| same_file(p, &path)));
|
||||
match open {
|
||||
Some(i) => {
|
||||
s.set_active(i);
|
||||
}
|
||||
None => {
|
||||
// Opened in the request's own scope, so the document keeps the roots it was opened under.
|
||||
s.execute("document.open", &json!({ "path": path }))?;
|
||||
}
|
||||
}
|
||||
Ok(json!({"path": path, "created": created}))
|
||||
}
|
||||
@@ -177,6 +177,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
|
||||
BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
@@ -186,6 +187,8 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving },
|
||||
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
|
||||
BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush },
|
||||
BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic },
|
||||
BuiltinBrushLibrary { id: "vector-packs", name: "Vector Packs", make: vector_packs },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -239,6 +242,42 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// Artistic: four original vector compositions that stretch along a path and take its color.
|
||||
fn artistic() -> BrushLibrary {
|
||||
let orbit = group(vec![
|
||||
black(band(100.0, 1.4, 64, |x| 3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
|
||||
black(band(100.0, 1.4, 64, |x| -3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
|
||||
]);
|
||||
let mut petals = vec![black(band(100.0, 0.8, 4, |_| 0.0))];
|
||||
for i in 0..6 {
|
||||
let x = 9.0 + 16.0 * i as f64;
|
||||
let side = if i % 2 == 0 { 1.0 } else { -1.0 };
|
||||
petals.push(black(polygon(&[(x - 6.0, 0.0), (x - 2.0, 5.0 * side), (x + 5.0, 7.0 * side), (x + 2.0, 2.0 * side)])));
|
||||
}
|
||||
let mut lattice = vec![black(band(100.0, 0.9, 4, |_| 0.0))];
|
||||
for i in 0..5 {
|
||||
let x = 20.0 * i as f64;
|
||||
lattice.push(black(polygon(&[(x, -4.0), (x + 1.0, -4.0), (x + 20.0, 4.0), (x + 19.0, 4.0)])));
|
||||
lattice.push(black(polygon(&[(x, 4.0), (x + 1.0, 4.0), (x + 20.0, -4.0), (x + 19.0, -4.0)])));
|
||||
}
|
||||
let mut facets = Vec::new();
|
||||
for i in 0..8 {
|
||||
let x = 12.5 * i as f64;
|
||||
let high = if i % 2 == 0 { 6.0 } else { 3.5 };
|
||||
facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)])));
|
||||
}
|
||||
built(
|
||||
"Artistic Brushes",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
art("Orbit Lines", orbit, Colorization::Tints),
|
||||
art("Petal Garland", group(petals), Colorization::Tints),
|
||||
art("Lattice Braid", group(lattice), Colorization::Tints),
|
||||
art("Facet Sweep", group(facets), Colorization::Tints),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Original fine-line art for an engraving-style brush library.
|
||||
fn engraving() -> BrushLibrary {
|
||||
let lines = |count: usize, width: f64, spacing: f64| {
|
||||
@@ -653,6 +692,47 @@ fn pattern_borders() -> BrushLibrary {
|
||||
built("Pattern Borders", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// Decorative: repeating plant, flower and hanging ornaments drawn as original vector tiles.
|
||||
/// Every tile joins the next at x = 0 and 48 so open and closed paths stay continuous.
|
||||
fn decorative() -> BrushLibrary {
|
||||
let stem = || black(shapes::rectangle(Rect::new(0.0, -0.65, 48.0, 0.65)));
|
||||
let vine = group(vec![
|
||||
stem(),
|
||||
black(polygon(&[(8.0, -0.2), (12.0, -5.0), (24.0, -8.0), (20.0, -1.0)])),
|
||||
black(polygon(&[(28.0, 0.2), (32.0, 5.0), (44.0, 8.0), (40.0, 1.0)])),
|
||||
]);
|
||||
let mut blossoms = vec![stem()];
|
||||
for x in [12.0, 36.0] {
|
||||
for (dx, dy) in [(0.0, -4.0), (4.0, 0.0), (0.0, 4.0), (-4.0, 0.0)] {
|
||||
blossoms.push(black(shapes::ellipse(Rect::new(x + dx - 2.5, dy - 2.5, x + dx + 2.5, dy + 2.5))));
|
||||
}
|
||||
blossoms.push(black(shapes::ellipse(Rect::new(x - 1.3, -1.3, x + 1.3, 1.3))));
|
||||
}
|
||||
let flowers = group(blossoms);
|
||||
let pennants = group(vec![
|
||||
black(shapes::rectangle(Rect::new(0.0, -5.2, 48.0, -4.2))),
|
||||
black(polygon(&[(4.0, -4.2), (20.0, -4.2), (12.0, 10.0)])),
|
||||
black(polygon(&[(28.0, -4.2), (44.0, -4.2), (36.0, 10.0)])),
|
||||
]);
|
||||
let lanterns = group(vec![
|
||||
black(shapes::rectangle(Rect::new(0.0, -5.0, 48.0, -4.0))),
|
||||
black(shapes::rectangle(Rect::new(11.4, -4.0, 12.6, -1.0))),
|
||||
black(shapes::ellipse(Rect::new(7.0, -1.0, 17.0, 9.0))),
|
||||
black(shapes::rectangle(Rect::new(35.4, -4.0, 36.6, -1.0))),
|
||||
black(shapes::ellipse(Rect::new(31.0, -1.0, 41.0, 9.0))),
|
||||
]);
|
||||
built(
|
||||
"Decorative",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
border("Leaf Vine", vine, None, PatternFit::Stretch),
|
||||
border("Blossom Chain", flowers, None, PatternFit::Stretch),
|
||||
border("Pennant Garland", pennants, None, PatternFit::Stretch),
|
||||
border("Lantern String", lanterns, None, PatternFit::Stretch),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
|
||||
}
|
||||
@@ -787,6 +867,38 @@ fn scatter_shapes() -> BrushLibrary {
|
||||
built("Scatter Shapes", doc, brushes)
|
||||
}
|
||||
|
||||
/// Vector Packs: four original, editable vector marks that follow the stroke color.
|
||||
fn vector_packs() -> BrushLibrary {
|
||||
let compass = group(vec![black(shapes::star(Point::ZERO, 10.0, 3.0, 8, 0.0)), black(shapes::ellipse(Rect::new(-1.5, -1.5, 1.5, 1.5)))]);
|
||||
let sprig = group(vec![
|
||||
black(polygon(&[(-0.7, 10.0), (0.7, 10.0), (0.7, -10.0), (-0.7, -10.0)])),
|
||||
black(polygon(&[(0.0, 5.0), (5.0, 2.0), (7.0, -1.0), (3.0, 0.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (-5.0, -3.0), (-7.0, -6.0), (-3.0, -5.0)])),
|
||||
black(polygon(&[(0.0, -5.0), (5.0, -8.0), (7.0, -10.0), (3.0, -9.0)])),
|
||||
]);
|
||||
let diamond = group(vec![
|
||||
black(polygon(&[(-9.0, 0.0), (-1.0, -9.0), (-1.0, -1.0)])),
|
||||
black(polygon(&[(1.0, -9.0), (9.0, 0.0), (1.0, -1.0)])),
|
||||
black(polygon(&[(9.0, 0.0), (1.0, 9.0), (1.0, 1.0)])),
|
||||
black(polygon(&[(-1.0, 9.0), (-9.0, 0.0), (-1.0, 1.0)])),
|
||||
]);
|
||||
let tide = group(vec![
|
||||
black(band(20.0, 1.2, 32, |x| -3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())),
|
||||
black(band(20.0, 1.2, 32, |x| 3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())),
|
||||
]);
|
||||
let settings = Scatter { size: (90.0, 110.0), spacing: (130.0, 160.0), colorization: Colorization::Tints, ..Default::default() };
|
||||
built(
|
||||
"Vector Packs",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
scatter("Compass Rose", compass, settings.clone()),
|
||||
scatter("Botanical Sprig", sprig, settings.clone()),
|
||||
scatter("Facet Diamond", diamond, settings.clone()),
|
||||
scatter("Tide Crest", tide, settings),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Stipple: original dot-based scatter brushes for fine and broad shading along a path.
|
||||
fn stipple() -> BrushLibrary {
|
||||
let dot = |x: f64, y: f64, r: f64, opacity: f32| {
|
||||
@@ -1076,10 +1188,14 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary>
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_library(key)?));
|
||||
return Some((builtin_info(b), builtin_library(b.id)?));
|
||||
}
|
||||
let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id;
|
||||
library(s, &id)
|
||||
if let Some(id) = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key)).map(|l| l.id) {
|
||||
return library(s, &id);
|
||||
}
|
||||
// Keep the short built-in alias, but let a user or loaded library own its display name.
|
||||
let b = key.eq_ignore_ascii_case("Artistic").then(|| BUILTIN.iter().find(|b| b.id == "artistic")).flatten()?;
|
||||
Some((builtin_info(b), builtin_library(b.id)?))
|
||||
}
|
||||
|
||||
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<BrushLibrary>)> {
|
||||
|
||||
@@ -362,7 +362,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Sprayer",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
|
||||
"{points: [[x,y]…] (a third value is a number or null and is not used), name?, radius?: 40, density?: 1..10 (5; a number outside 1..10 is taken as the nearer end), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one with an amount above 0, at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
|
||||
has_doc,
|
||||
symbol_spray
|
||||
),
|
||||
@@ -380,7 +380,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbolism Tool",
|
||||
[],
|
||||
None,
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error",
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way; style without `shift`: from none to the userDefined amount); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size as it is. With `proportional` false a drag resizes along its own direction, the width by the drag's horizontal share and the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. The style goes on by the brush's strength at each sample, and a stroke's samples add up. With `alt` and without `shift`, userDefined and random style remove all of an instance's appearance items under the brush at once, whatever the brush's strength. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, each already at the tool's limit, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error",
|
||||
has_doc,
|
||||
symbol_adjust
|
||||
),
|
||||
|
||||
@@ -86,8 +86,9 @@ pub(super) fn spacing(density: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written
|
||||
/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it.
|
||||
const SET_DENSITY_KEY: &str = "symbolSetDensity";
|
||||
/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it, and copied to a
|
||||
/// copy of a set by [`Document::reid`].
|
||||
const SET_DENSITY_KEY: &str = Document::SYMBOL_SET_DENSITY_KEY;
|
||||
|
||||
/// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded).
|
||||
fn set_density_of(d: &Document, set: NodeId) -> Option<f64> {
|
||||
@@ -261,7 +262,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option<Mean> {
|
||||
cos += l.angle.cos();
|
||||
opacity += l.opacity;
|
||||
middle += l.center.to_vec2();
|
||||
if let Some((p, o)) = &l.fill {
|
||||
// A fill at no opacity shows nothing: it is no stain or style, and its paint is not taken.
|
||||
if let Some((p, o)) = &l.fill
|
||||
&& *o > 0.0
|
||||
{
|
||||
amount += o;
|
||||
let far = l.center.distance(at);
|
||||
if paint.is_none_or(|(_, nearest)| far < nearest) {
|
||||
|
||||
@@ -118,6 +118,20 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The symbol instances in `nodes` and inside them, each once, in the order a walk of each node in
|
||||
/// turn first reaches them.
|
||||
fn instances_in<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> Vec<NodeId> {
|
||||
let (mut v, mut seen) = (vec![], std::collections::HashSet::new());
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && seen.insert(c.id) {
|
||||
v.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`.
|
||||
fn art_symbols(n: &Node, out: &mut Vec<String>) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
@@ -917,11 +931,12 @@ fn samples(p: &Value, cmd: &str) -> Result<Vec<(Point, f64)>> {
|
||||
let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?;
|
||||
let mut v = Vec::with_capacity(a.len());
|
||||
for q in a {
|
||||
let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
|
||||
// The pressure is checked first: a point skipped for its coordinates still has a bad one refused.
|
||||
let pressure = match q.get(2) {
|
||||
None | Some(Value::Null) => 1.0,
|
||||
Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?,
|
||||
};
|
||||
let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
|
||||
v.push((Point::new(x, y), pressure.clamp(0.0, 1.0)));
|
||||
}
|
||||
if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) {
|
||||
@@ -930,13 +945,15 @@ fn samples(p: &Value, cmd: &str) -> Result<Vec<(Point, f64)>> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The fill of the graphic style `p` names with `style`, else of the document's first style after
|
||||
/// the default one.
|
||||
/// The fill of the graphic style `p` names with `style`, else (no name, or one the document has no
|
||||
/// style for, such as the Symbol Styler's style from another document) of the document's first
|
||||
/// style after the default one.
|
||||
fn style_paint(d: &Document, p: &Value) -> Option<Paint> {
|
||||
match str_param(p, "style") {
|
||||
Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()),
|
||||
None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()),
|
||||
}
|
||||
str_param(p, "style")
|
||||
.and_then(|n| d.graphic_styles.iter().find(|g| g.name == n))
|
||||
.or(d.graphic_styles.get(1))
|
||||
.or(d.graphic_styles.first())
|
||||
.map(|g| g.appearance.fill_paint())
|
||||
}
|
||||
|
||||
/// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree).
|
||||
@@ -976,7 +993,7 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let style = style_paint(&st.doc, p);
|
||||
// Style: User Defined uses the style `style` names, so one the document does not have is an error.
|
||||
if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) {
|
||||
if let Some(n) = str_param(p, "style").filter(|n| !modes.style && !st.doc.graphic_styles.iter().any(|g| g.name == *n)) {
|
||||
return Err(bad(C, format!("unknown graphic style `{n}`")));
|
||||
}
|
||||
let size = natural_size(&st.doc, &name);
|
||||
@@ -1129,6 +1146,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let use_pressure = switch_or(p, "usePressure", false, C)?;
|
||||
let proportional = switch_or(p, "proportional", true, C)?;
|
||||
let affects_density = switch_or(p, "affectsDensity", false, C)?;
|
||||
let shift = switch_or(p, "shift", false, C)?;
|
||||
// The Symbol Shifter has no Method.
|
||||
let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? };
|
||||
// Refused while an object of a dynamic instance's art is selected: the instance stays as it is.
|
||||
@@ -1141,20 +1159,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let style_paint = style_paint(&st.doc, p);
|
||||
let candidates: Vec<NodeId> = {
|
||||
let d = &st.doc;
|
||||
let mut v = vec![];
|
||||
if st.selection.is_empty() {
|
||||
v = instances_of(d, None);
|
||||
} else {
|
||||
for id in &st.selection.objects {
|
||||
if let Some(n) = d.node(*id) {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) {
|
||||
v.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut v =
|
||||
if st.selection.is_empty() { instances_of(d, None) } else { instances_in(st.selection.objects.iter().filter_map(|id| d.node(*id))) };
|
||||
let editable = d.editable();
|
||||
v.retain(|id| editable(*id));
|
||||
v
|
||||
@@ -1172,12 +1178,39 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// for the whole stroke (and for every preview of it).
|
||||
let first = pts.first().map_or(Point::ZERO, |(q, _)| *q);
|
||||
let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 };
|
||||
// Shift with the Symbol Shifter: the instances under the brush come one place forward among
|
||||
// their siblings (with `alt`, go one place backward), once for the whole stroke.
|
||||
if tool == "shift" && shift {
|
||||
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| {
|
||||
let under: std::collections::HashSet<NodeId> = candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
d.node(*id).and_then(instance_center).is_some_and(|c| {
|
||||
pts.iter().any(|(q, pressure)| (if use_pressure { *pressure } else { intensity }) > 0.0 && c.distance(*q) < radius)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let moved = restack(d, &under, alt)?;
|
||||
Ok((moved, moved > 0))
|
||||
})?;
|
||||
return Ok(json!({ "count": count }));
|
||||
}
|
||||
// Shift with the Symbol Stainer or the Symbol Styler: the paint an instance's stain or style
|
||||
// moves toward, and the share of the brush's strength it moves by. Shift with the Symbol Sizer
|
||||
// keeps the instances where they are, Resizing Affects Density included.
|
||||
let recolor = match tool.as_str() {
|
||||
"stain" if shift => Some((Paint::solid(color), 0.15)),
|
||||
"style" if shift => Some((style_paint.clone().unwrap_or(Paint::solid(color)), 1.0)),
|
||||
_ => None,
|
||||
};
|
||||
let spread = affects_density && !shift;
|
||||
// No undo step when no instance changes (none under the brush, or Average with each at the mean).
|
||||
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| {
|
||||
let mut touched = std::collections::BTreeSet::new();
|
||||
let mut sides = Sides::new();
|
||||
for (j, (q, pressure)) in pts.iter().enumerate() {
|
||||
let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO };
|
||||
let delta = j.checked_sub(1).and_then(|i| pts.get(i)).map_or(Vec2::ZERO, |(prev, _)| *q - *prev);
|
||||
// Use Pressure Pen: the pen's pressure at the point is the intensity there.
|
||||
let strength = if use_pressure { *pressure } else { intensity };
|
||||
// Average: the mean of the instances under the brush, as they are at this point.
|
||||
@@ -1198,6 +1231,14 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if w <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
// Shift with the Symbol Stainer or the Symbol Styler: the instance keeps the amount
|
||||
// of its stain or style, and its paint moves toward the color or the style. An
|
||||
// instance without one, or without a size, is left as it is.
|
||||
if let Some((to, step)) = &recolor {
|
||||
let fill = d.node(*id).and_then(|n| look(d, n, &mut sides)).and_then(|l| l.fill);
|
||||
touched.extend(recolor_keeping_amount(d, *id, fill, to, step * w).then_some(*id));
|
||||
continue;
|
||||
}
|
||||
// Average needs the instance's own values, so it leaves an instance without a size
|
||||
// as it is; the other methods change it as before.
|
||||
// The instance's own values are read for Average only.
|
||||
@@ -1261,8 +1302,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
n.transform(about(Affine::scale_non_uniform(kx, ky)), false);
|
||||
// Resizing Affects Density: instances move away from the brush's center as
|
||||
// they grow and toward it as they shrink.
|
||||
if affects_density {
|
||||
// they grow and toward it as they shrink. Shift keeps the instances where
|
||||
// they are, so the set's density stays as it was.
|
||||
if spread {
|
||||
n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false);
|
||||
}
|
||||
}
|
||||
@@ -1280,9 +1322,10 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"stain" | "style" => {
|
||||
let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) };
|
||||
let (paint, o) = match &avg {
|
||||
// Toward the mean amount, keeping the stain or style the instance has.
|
||||
// Toward the mean amount, keeping the stain or style the instance has
|
||||
// (one at no opacity is none).
|
||||
Some((t, look)) => {
|
||||
let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o));
|
||||
let (own, cur) = look.fill.clone().filter(|(_, o)| *o > 0.0).map_or((None, 0.0), |(p, o)| (Some(p), o));
|
||||
(own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32)
|
||||
}
|
||||
// Alt with the Symbol Styler removes the instance's appearance.
|
||||
@@ -1292,11 +1335,11 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => {
|
||||
let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0);
|
||||
// The style goes on gradually, by the brush's strength there: in
|
||||
// full at the center at full intensity or pressure.
|
||||
let step = match (tool.as_str(), method) {
|
||||
// Random: the instance's share of the style, scaled by the
|
||||
// brush strength there.
|
||||
("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32,
|
||||
("style", _) => 1.0,
|
||||
("style", Method::Random) => (w * share / 2.0) as f32,
|
||||
("style", _) => w as f32,
|
||||
_ => (0.15 * w * share) as f32,
|
||||
};
|
||||
(paint, if alt { cur - step } else { cur + step })
|
||||
@@ -1324,9 +1367,108 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// An instance the stroke moved away and back again is not counted.
|
||||
// An instance the stroke moved away and back again, or reached but left as it was (at a
|
||||
// limit already), is not counted.
|
||||
touched.retain(|id| d.node(*id) != orig.node(*id));
|
||||
Ok((touched.len(), !touched.is_empty()))
|
||||
})?;
|
||||
Ok(json!({ "count": count }))
|
||||
}
|
||||
|
||||
/// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount)
|
||||
/// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's
|
||||
/// other appearance items stay as they are. A paint with no form between it and `to` (a solid
|
||||
/// color and a pattern, say) takes `to` at once, so repeated strokes below half strength still
|
||||
/// reach it. An instance without a stain or style, or one whose paint does not change, is left as
|
||||
/// it is. Returns whether it changed.
|
||||
fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool {
|
||||
use vectorcraft_doc::blend::lerp_paint;
|
||||
let Some((own, _)) = fill.filter(|(_, o)| *o > 0.0) else { return false };
|
||||
let t = t.clamp(0.0, 1.0) as f32;
|
||||
let mut paint = lerp_paint(&own, to, t);
|
||||
// `lerp_paint` switches such a pair halfway, so just below half it still gives `own`.
|
||||
if paint == own && t > 0.0 && lerp_paint(&own, to, 0.49) == own {
|
||||
paint = to.clone();
|
||||
}
|
||||
if paint == own {
|
||||
return false;
|
||||
}
|
||||
let Some(f) = d.node_mut(id).and_then(|n| n.appearance.fill_mut()) else { return false };
|
||||
f.paint = paint;
|
||||
true
|
||||
}
|
||||
|
||||
/// Bring each of `ids` one place forward among its siblings past a sibling that is not one of them
|
||||
/// (`back`: one place backward). Ones already in front of (behind) every other sibling stay, and
|
||||
/// so do the clipping path of a clip group and the ruler guides above a layer's art. Returns how
|
||||
/// many moved.
|
||||
fn restack(d: &mut Document, ids: &std::collections::HashSet<NodeId>, back: bool) -> Result<usize> {
|
||||
let parents: std::collections::BTreeSet<Option<NodeId>> = ids.iter().map(|id| d.parent_of(*id)).collect();
|
||||
let mut moved = 0;
|
||||
for par in parents {
|
||||
let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips));
|
||||
let ch = d.children_mut(par)?;
|
||||
let len = Node::guide_run_start(ch);
|
||||
if len <= floor + 1 {
|
||||
continue;
|
||||
}
|
||||
let picked = |n: &Arc<Node>| ids.contains(&n.id);
|
||||
if back {
|
||||
for i in floor + 1..len {
|
||||
if picked(&ch[i]) && !picked(&ch[i - 1]) {
|
||||
ch.swap(i - 1, i);
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i in (floor..len - 1).rev() {
|
||||
if picked(&ch[i]) && !picked(&ch[i + 1]) {
|
||||
ch.swap(i, i + 1);
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn instance(id: u64) -> Arc<Node> {
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }))
|
||||
}
|
||||
|
||||
/// The instances come out in the order a search of the list built so far gives: nested
|
||||
/// groups, a group listed twice, a member listed after its group and one listed before it.
|
||||
#[test]
|
||||
fn instances_in_matches_searching_the_list_so_far() {
|
||||
let groups: Vec<Node> = (0..40u64)
|
||||
.map(|g| {
|
||||
let base = g * 100;
|
||||
let mut children: Vec<Arc<Node>> = (0..40).map(|i| instance(base + i)).collect();
|
||||
let inner = (40..50).map(|i| instance(base + i)).collect();
|
||||
children.insert(20, Arc::new(Node::group(NodeId(base + 90), inner)));
|
||||
children.push(Arc::new(Node::group(NodeId(base + 91), vec![])));
|
||||
Node::group(NodeId(base + 99), children)
|
||||
})
|
||||
.collect();
|
||||
let early = Node::new(NodeId(1_245), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
|
||||
let late = Node::new(NodeId(305), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
|
||||
let nodes: Vec<&Node> = std::iter::once(&early).chain(&groups).chain([&groups[0], &late, &groups[7]]).collect();
|
||||
let mut searched = vec![];
|
||||
for n in &nodes {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !searched.contains(&c.id) {
|
||||
searched.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
let found = instances_in(nodes.iter().copied());
|
||||
assert_eq!(found, searched);
|
||||
assert_eq!(found.len(), 2_000);
|
||||
assert_eq!(found[0], NodeId(1_245));
|
||||
assert!(instances_in([]).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -42,8 +42,12 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target};
|
||||
use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view};
|
||||
pub use trace::{
|
||||
TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target,
|
||||
};
|
||||
use trace::{
|
||||
trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view,
|
||||
};
|
||||
|
||||
/// Name of an Image Trace group.
|
||||
pub const TRACE_NAME: &str = "Image Trace";
|
||||
@@ -208,6 +212,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
trace_presets_delete
|
||||
),
|
||||
cmd!(
|
||||
query "imageTrace.presets.import",
|
||||
"Import Image Trace Presets",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, replace?: false (true: a preset whose name a saved preset has replaces that preset's settings; false: it is skipped)} add the presets of a .vctracepresets file (as imageTrace.presets.export writes, at most 4 MiB and 1,000 presets) to the saved ones → {imported: [names added], replaced: [names], skipped: [names]}; every preset is checked first, and a file with a built-in preset's or Custom's name, two presets of one name, a preset without a name or with settings imageTrace.presets.save refuses, or a newer version changes nothing",
|
||||
always,
|
||||
trace_presets_import
|
||||
),
|
||||
cmd!(
|
||||
query "imageTrace.presets.export",
|
||||
"Export Image Trace Presets",
|
||||
[],
|
||||
None,
|
||||
"{names?: [saved preset names] (default: every saved preset; built-in ones are refused), path?} write the saved tracing presets as a .vctracepresets file (JSON: format, version 1, presets: [{name, params}]) → {path, count}; without path → {data: the file's text, count}; more than 1,000 presets, or a file over 4 MiB, is refused, as imageTrace.presets.import would refuse it",
|
||||
always,
|
||||
trace_presets_export
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -58,9 +58,10 @@ fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
|
||||
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
|
||||
}
|
||||
|
||||
/// The `split` param (the Split view's divider, 0 to 1), if given.
|
||||
/// The `split` param (the Split view's divider, 0 to 1), if given. A null divider is an error, as
|
||||
/// any other value that is not such a number is; only an omitted one keeps the divider.
|
||||
fn split_param(cmd: &str, p: &Value) -> Result<Option<f64>> {
|
||||
let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let Some(v) = p.get("split") else { return Ok(None) };
|
||||
v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1"))
|
||||
}
|
||||
|
||||
@@ -167,6 +168,9 @@ pub(super) fn trace_presets_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if old.is_none() && new_name.is_some() {
|
||||
return Err(bad(C, format!("no saved preset named `{name}` to rename")));
|
||||
}
|
||||
if old.is_none() && s.prefs.trace_presets.len() >= TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(C, format!("{TRACE_PRESET_MAX_COUNT} tracing presets are saved, the most there can be: delete one first")));
|
||||
}
|
||||
// A saved preset changes from its own settings unless `preset` says where to start.
|
||||
let mut q = p.clone();
|
||||
if let (Some(old), Some(o), None) = (&old, q.as_object_mut(), preset) {
|
||||
@@ -202,6 +206,162 @@ pub(super) fn trace_presets_delete(s: &mut Session, p: &Value) -> Result<Value>
|
||||
Ok(json!({ "deleted": deleted }))
|
||||
}
|
||||
|
||||
/// The `format` of a tracing presets file, also its extension.
|
||||
pub const TRACE_PRESET_FORMAT: &str = "vctracepresets";
|
||||
|
||||
/// The extensions of tracing presets files (opening one imports it).
|
||||
pub const TRACE_PRESET_EXTS: &[&str] = &[TRACE_PRESET_FORMAT];
|
||||
|
||||
/// The `version` `imageTrace.presets.export` writes; `imageTrace.presets.import` reads files of
|
||||
/// this version and earlier ones.
|
||||
const TRACE_PRESET_VERSION: u64 = 1;
|
||||
|
||||
/// The largest tracing presets file `imageTrace.presets.import` reads.
|
||||
pub const TRACE_PRESET_MAX_BYTES: usize = 4 << 20;
|
||||
|
||||
/// The most presets one tracing presets file may hold, and the most tracing presets that can be
|
||||
/// saved (so every saved preset fits in one exported file).
|
||||
const TRACE_PRESET_MAX_COUNT: usize = 1000;
|
||||
|
||||
pub(super) fn trace_presets_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.presets.export";
|
||||
let presets: Vec<&TracePreset> = match p.get("names").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(names)) => {
|
||||
let mut out: Vec<&TracePreset> = vec![];
|
||||
for n in names {
|
||||
let n = n.as_str().ok_or_else(|| bad(C, "`names` must hold preset names"))?;
|
||||
if tr::preset(n).is_some() {
|
||||
return Err(bad(C, format!("`{n}` is a built-in preset: only saved presets are exported")));
|
||||
}
|
||||
let q = s.trace_preset(n).ok_or_else(|| bad(C, format!("no saved preset named `{n}`")))?;
|
||||
if !out.iter().any(|o| o.name == q.name) {
|
||||
out.push(q);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
Some(_) => return Err(bad(C, "`names` must be an array of preset names")),
|
||||
None => s.prefs.trace_presets.iter().collect(),
|
||||
};
|
||||
if presets.is_empty() {
|
||||
return Err(bad(C, "no saved tracing presets to export"));
|
||||
}
|
||||
// A file is written only when `imageTrace.presets.import` can read it back.
|
||||
let count = presets.len();
|
||||
if count > TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(C, format!("{count} presets are more than one file holds ({TRACE_PRESET_MAX_COUNT}): export fewer with `names`")));
|
||||
}
|
||||
let rows: Vec<Value> = presets.iter().map(|q| json!({"name": q.name, "params": q.params})).collect();
|
||||
let file = json!({"format": TRACE_PRESET_FORMAT, "version": TRACE_PRESET_VERSION, "presets": rows});
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if text.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(bad(C, format!("the file would be larger than {} MiB: export fewer with `names`", TRACE_PRESET_MAX_BYTES >> 20)));
|
||||
}
|
||||
match opt_str(C, p, "path")? {
|
||||
Some(path) => {
|
||||
crate::cmd::fileio::write_file(path, text.as_bytes())?;
|
||||
Ok(json!({"path": path, "count": count}))
|
||||
}
|
||||
None => Ok(json!({"data": text, "count": count})),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of the tracing presets file `p` names (`path`, `data` or `dataBase64`), at most
|
||||
/// [`TRACE_PRESET_MAX_BYTES`] of them.
|
||||
fn trace_preset_file(c: &str, p: &Value) -> Result<Vec<u8>> {
|
||||
let too_big = || bad(c, format!("the file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20));
|
||||
let bytes = match (opt_str(c, p, "path")?, opt_str(c, p, "data")?, opt_str(c, p, "dataBase64")?) {
|
||||
(Some(path), ..) => crate::cmd::fileio::read_file_head(path, TRACE_PRESET_MAX_BYTES + 1)?,
|
||||
(None, Some(text), _) => {
|
||||
if text.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(too_big());
|
||||
}
|
||||
text.as_bytes().to_vec()
|
||||
}
|
||||
(None, None, Some(b64)) => {
|
||||
if vectorcraft_format::base64_decoded_len(b64) > TRACE_PRESET_MAX_BYTES as u64 {
|
||||
return Err(too_big());
|
||||
}
|
||||
vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?
|
||||
}
|
||||
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > TRACE_PRESET_MAX_BYTES {
|
||||
return Err(too_big());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub(super) fn trace_presets_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.presets.import";
|
||||
let replace = switch_or(p, "replace", false, C)?;
|
||||
let bytes = trace_preset_file(C, p)?;
|
||||
let not_file = |why: String| bad(C, format!("not a tracing presets file: {why}"));
|
||||
let file: Value = serde_json::from_slice(&bytes).map_err(|e| not_file(e.to_string()))?;
|
||||
if file["format"] != TRACE_PRESET_FORMAT {
|
||||
return Err(not_file(format!("format `{}`", file["format"].as_str().unwrap_or_default())));
|
||||
}
|
||||
match file["version"].as_u64() {
|
||||
Some(v) if (1..=TRACE_PRESET_VERSION).contains(&v) => {}
|
||||
Some(v) => return Err(bad(C, format!("the file's version {v} is newer than this version of VectorCraft reads ({TRACE_PRESET_VERSION})"))),
|
||||
None => return Err(not_file("no `version`".into())),
|
||||
}
|
||||
let rows = file["presets"].as_array().ok_or_else(|| not_file("no `presets` list".into()))?;
|
||||
if rows.len() > TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(C, format!("the file holds {} presets, more than {TRACE_PRESET_MAX_COUNT}", rows.len())));
|
||||
}
|
||||
// Every preset is checked before any is saved, so a file with a fault changes nothing.
|
||||
let mut presets: Vec<TracePreset> = Vec::with_capacity(rows.len());
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
let name = row["name"].as_str().map(str::trim).unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
return Err(bad(C, format!("preset {} has no name", i + 1)));
|
||||
}
|
||||
if tr::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") {
|
||||
return Err(bad(C, format!("`{name}` is the name of a built-in preset: rename it in the file")));
|
||||
}
|
||||
if presets.iter().any(|q| q.name.eq_ignore_ascii_case(name)) {
|
||||
return Err(bad(C, format!("the file holds two presets named `{name}`")));
|
||||
}
|
||||
let params = match row.get("params").filter(|v| v.is_object()) {
|
||||
Some(params) => trace_params(s, C, &json!({"preset": "Default", "params": params})).map_err(|e| match e {
|
||||
EngineError::BadParams { msg, .. } => bad(C, format!("`{name}`: {msg}")),
|
||||
e => e,
|
||||
})?,
|
||||
None => return Err(bad(C, format!("`{name}` has no `params`"))),
|
||||
};
|
||||
presets.push(TracePreset { name: name.to_string(), params });
|
||||
}
|
||||
let added = presets.iter().filter(|q| s.trace_preset_index(&q.name).is_none()).count();
|
||||
if s.prefs.trace_presets.len() + added > TRACE_PRESET_MAX_COUNT {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("the file's {added} new presets would make more than {TRACE_PRESET_MAX_COUNT} saved tracing presets: delete some first"),
|
||||
));
|
||||
}
|
||||
let (mut imported, mut replaced, mut skipped) = (vec![], vec![], vec![]);
|
||||
for preset in presets {
|
||||
let name = preset.name.clone();
|
||||
match s.trace_preset_index(&name) {
|
||||
Some(i) if replace => {
|
||||
let Some(slot) = s.prefs.trace_presets.get_mut(i) else { continue };
|
||||
// The saved preset keeps its name as it was saved.
|
||||
let kept = slot.name.clone();
|
||||
*slot = TracePreset { name: kept.clone(), params: preset.params };
|
||||
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: kept.clone(), renamed_from: None, deleted: false });
|
||||
replaced.push(kept);
|
||||
}
|
||||
Some(_) => skipped.push(name),
|
||||
None => {
|
||||
s.prefs.trace_presets.push(preset);
|
||||
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: name.clone(), renamed_from: None, deleted: false });
|
||||
imported.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({"imported": imported, "replaced": replaced, "skipped": skipped}))
|
||||
}
|
||||
|
||||
/// The string `key` of `p` (`None` when it is missing or null); any other type is an error of
|
||||
/// command `c`.
|
||||
fn opt_str<'a>(c: &str, p: &'a Value, key: &str) -> Result<Option<&'a str>> {
|
||||
@@ -649,7 +809,16 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(),
|
||||
None => "Custom".to_string(),
|
||||
};
|
||||
// The image (inside a trace group, or selected directly).
|
||||
let (target, image) = target_image(s, c, p)?;
|
||||
// The traced shapes are placed by the image's transform, which a distortion overrides: the
|
||||
// command stops before any pixels are read.
|
||||
let distorted = s.doc()?.doc.node(target).is_some_and(|n| {
|
||||
n.is_distorted_image() || (is_trace_group(n) && n.children().and_then(|c| c.first()).is_some_and(|i| i.is_distorted_image()))
|
||||
});
|
||||
if distorted {
|
||||
return Err(crate::cmd::xform::distorted_image_error(c, target));
|
||||
}
|
||||
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
|
||||
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::Swatch;
|
||||
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
|
||||
use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
|
||||
use vectorcraft_geom::{PathData, Rect};
|
||||
|
||||
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
|
||||
@@ -94,6 +94,9 @@ pub struct Clipboard {
|
||||
pub para_styles: Vec<TextStyleDef>,
|
||||
/// Brushes the objects' strokes use.
|
||||
pub brushes: Vec<Brush>,
|
||||
/// Graph designs the copied graphs draw their columns, bars or markers with. Pasting adds the
|
||||
/// ones the document lacks; a design the document has under the same name stays as it is.
|
||||
pub graph_designs: Vec<GraphDesign>,
|
||||
/// The artboard the objects were copied from (none when they lie on no artboard; the first of
|
||||
/// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it.
|
||||
pub source_artboard: Option<Rect>,
|
||||
@@ -109,6 +112,9 @@ pub struct Clipboard {
|
||||
/// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on
|
||||
/// no layer: pasting puts them on the layer new art goes to, moved as the objects are.
|
||||
pub guides: Vec<vectorcraft_doc::Guide>,
|
||||
/// The Symbol Set Density recorded at Copy for each copied symbol set, by its id in
|
||||
/// [`Self::nodes`]: a pasted set packs from it.
|
||||
pub set_densities: BTreeMap<NodeId, Value>,
|
||||
/// The RGB and CMYK profiles the objects' colors showed through in the document they were
|
||||
/// copied from (its assigned profiles, else the working spaces then), by name; none for objects
|
||||
/// from outside an open document. Paste compares them with the destination's
|
||||
@@ -392,7 +398,7 @@ impl Clipboard {
|
||||
if self.source_doc == Some(st.uid) && !self.colors_converted {
|
||||
return vec![];
|
||||
}
|
||||
self.conflicts(&st.doc, &self.used())
|
||||
self.conflicts(&st.doc, &self.used(&st.doc))
|
||||
}
|
||||
|
||||
/// A standalone document holding the objects and their resources (SVG export).
|
||||
@@ -405,6 +411,7 @@ impl Clipboard {
|
||||
d.graphic_styles.extend(self.graphic_styles.iter().cloned());
|
||||
d.char_styles = self.char_styles.clone().into();
|
||||
d.para_styles = self.para_styles.clone().into();
|
||||
d.graph_designs = self.graph_designs.clone();
|
||||
if !self.brushes.is_empty() {
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
// Each brush's place in the library by name: finding it by scanning the growing list
|
||||
@@ -466,6 +473,7 @@ impl Clipboard {
|
||||
char_styles: d.char_styles.to_vec(),
|
||||
para_styles: d.para_styles.to_vec(),
|
||||
brushes: vectorcraft_brush::library(&d),
|
||||
graph_designs: d.graph_designs.clone(),
|
||||
images: self.images.clone(),
|
||||
symbol_options: self.symbol_options.clone(),
|
||||
source_artboard: self.source_artboard,
|
||||
@@ -484,6 +492,7 @@ impl Clipboard {
|
||||
})
|
||||
.collect(),
|
||||
guides: self.guides.clone(),
|
||||
set_densities: self.set_densities.clone(),
|
||||
source_profiles: self.source_profiles.clone(),
|
||||
colors_converted: self.colors_converted,
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The document resources copied objects use, and adding them to the document they're pasted into.
|
||||
//!
|
||||
//! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and
|
||||
//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also
|
||||
//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to.
|
||||
//! paragraph styles, brushes, graph designs) and to graphic styles by id. Copy follows those
|
||||
//! references, also through the symbols, patterns, styles, brush art and graph design art it finds,
|
||||
//! and keeps what they lead to.
|
||||
//!
|
||||
//! Pasting matches each resource by name: an identical one in the document is used, a missing one
|
||||
//! is added, and a different one of the same name is added under a free name, which the pasted
|
||||
@@ -22,8 +23,8 @@ use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType,
|
||||
SymbolNineSlice, SymbolRegistration, TextStyleDef,
|
||||
Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol,
|
||||
SymbolExportType, SymbolNineSlice, SymbolRegistration, TextStyleDef,
|
||||
};
|
||||
|
||||
use super::super::brushsym::{set_natural_size, stored_natural_size};
|
||||
@@ -44,6 +45,7 @@ enum Res {
|
||||
ParaStyle,
|
||||
Brush,
|
||||
GraphicStyle,
|
||||
GraphDesign,
|
||||
}
|
||||
|
||||
impl Res {
|
||||
@@ -57,6 +59,7 @@ impl Res {
|
||||
Res::ParaStyle => "paraStyle",
|
||||
Res::Brush => "brush",
|
||||
Res::GraphicStyle => "graphicStyle",
|
||||
Res::GraphDesign => "graphDesign",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,6 +142,10 @@ fn node_refs(n: &Node, f: Visit) {
|
||||
for s in [&l.values_para, &l.categories_para, &l.legend_para].into_iter().flatten().filter_map(|pa| pa.style_name.as_ref()) {
|
||||
f(Ref::Name(Res::ParaStyle, s));
|
||||
}
|
||||
// The designs its series draw their markers, columns or bars with.
|
||||
for d in g.series_markers.iter().flatten().chain(g.series_columns.iter().flatten().map(|c| &c.design)) {
|
||||
f(Ref::Name(Res::GraphDesign, d));
|
||||
}
|
||||
}
|
||||
match &m.kind {
|
||||
NodeKind::Text(t) => {
|
||||
@@ -217,6 +224,7 @@ struct Defs<'a> {
|
||||
char_styles: &'a [TextStyleDef],
|
||||
para_styles: &'a [TextStyleDef],
|
||||
brushes: Brushes<'a>,
|
||||
graph_designs: &'a [GraphDesign],
|
||||
/// Where each name is defined, built the first time a kind is followed.
|
||||
index: DefIndex,
|
||||
}
|
||||
@@ -236,6 +244,7 @@ struct DefIndex {
|
||||
char_styles: OnceCell<NameIndex>,
|
||||
para_styles: OnceCell<NameIndex>,
|
||||
brushes: OnceCell<NameIndex>,
|
||||
graph_designs: OnceCell<NameIndex>,
|
||||
}
|
||||
|
||||
/// The items of `list` named `name`, in order, `index` holding their positions (built from
|
||||
@@ -279,6 +288,7 @@ impl<'a> Defs<'a> {
|
||||
char_styles: &d.char_styles,
|
||||
para_styles: &d.para_styles,
|
||||
brushes: Brushes::Lazy(d, brushes),
|
||||
graph_designs: &d.graph_designs,
|
||||
index: DefIndex::default(),
|
||||
}
|
||||
}
|
||||
@@ -376,6 +386,7 @@ impl Used {
|
||||
Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))),
|
||||
// A scatter or art brush's art, a pattern brush's tiles.
|
||||
Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))),
|
||||
Res::GraphDesign => todo.extend(named(&ix.graph_designs, defs.graph_designs, |g| &g.name, name).map(|g| Source::Node(&g.art))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -406,7 +417,7 @@ pub struct ArtResources {
|
||||
/// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them
|
||||
/// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked
|
||||
/// colours, tints, gradient swatches; colour groups' included), character and paragraph styles,
|
||||
/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count
|
||||
/// brushes, graph designs and graphic styles, and the document's Spot Colors option. Art and image bytes count
|
||||
/// by identity, the other definitions by their saved form: working the key out walks `art` and
|
||||
/// the definitions it leads to, and never reads an image's bytes.
|
||||
pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a Node>) -> ArtResources {
|
||||
@@ -451,6 +462,7 @@ pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a No
|
||||
Res::CharStyle => doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)),
|
||||
Res::GraphDesign => doc.graph_designs.iter().filter(|g| g.name == *name).for_each(|g| node(&mut h, &mut kept.0, &g.art)),
|
||||
// Swatches below (tints count too); graphic styles go by id.
|
||||
Res::Swatch | Res::GraphicStyle => {}
|
||||
}
|
||||
@@ -824,6 +836,22 @@ fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
|
||||
ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b))
|
||||
}
|
||||
|
||||
/// `n` with the ids of its objects, those of opacity-mask art included, all 0: art drawn again
|
||||
/// compares equal to art drawn the same way, whatever ids each drawing gave it.
|
||||
fn without_ids(n: &Node) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = vectorcraft_doc::NodeId(0);
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
|
||||
mask.art = Arc::new(without_ids(&mask.art));
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
*c = Arc::new(without_ids(c));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by
|
||||
/// `r`? Graphic style links don't count, as in [`same_art`].
|
||||
fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
|
||||
@@ -1106,6 +1134,17 @@ pub(crate) struct Imported {
|
||||
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
|
||||
/// renamed, or a copy added renamed by an earlier paste.
|
||||
pub renamed: Vec<Value>,
|
||||
/// The graph designs the pasted graphs draw with that the document has under the same name
|
||||
/// and that would draw them otherwise than the art they were pasted with: the document keeps
|
||||
/// its own, and the pasted graphs are drawn again with it.
|
||||
pub kept_designs: BTreeSet<String>,
|
||||
/// The names of the symbols added to the document, whose art may hold graphs that draw with
|
||||
/// [`Self::kept_designs`].
|
||||
pub added_symbols: BTreeSet<String>,
|
||||
/// The names of the graph designs added to the document.
|
||||
pub added_designs: BTreeSet<String>,
|
||||
/// The global and spot colors that took the document's color (merged).
|
||||
merged_swatches: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Imported {
|
||||
@@ -1161,14 +1200,24 @@ impl Clipboard {
|
||||
char_styles: pick(Res::CharStyle, &src.char_styles),
|
||||
para_styles: pick(Res::ParaStyle, &src.para_styles),
|
||||
brushes,
|
||||
graph_designs: src.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)).cloned().collect(),
|
||||
set_densities: src.set_densities_of(&nodes),
|
||||
nodes,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The resources the objects use now (Paste without Formatting leaves text styles behind).
|
||||
pub(super) fn used(&self) -> Used {
|
||||
let defs = Defs {
|
||||
/// The resources the objects use now (Paste without Formatting leaves text styles behind),
|
||||
/// pasted into `d`: the art of a graph design `d` has under the same name is not followed, as
|
||||
/// `d` keeps its own design.
|
||||
pub(super) fn used(&self, d: &Document) -> Used {
|
||||
let designs: Vec<GraphDesign> = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect();
|
||||
Used::of(&self.defs(&designs), &self.nodes)
|
||||
}
|
||||
|
||||
/// The clipboard's definitions, with graph designs `designs`.
|
||||
fn defs<'a>(&'a self, designs: &'a [GraphDesign]) -> Defs<'a> {
|
||||
Defs {
|
||||
swatches: self.swatches.iter().collect(),
|
||||
symbols: &self.symbols,
|
||||
patterns: &self.patterns,
|
||||
@@ -1176,9 +1225,9 @@ impl Clipboard {
|
||||
char_styles: &self.char_styles,
|
||||
para_styles: &self.para_styles,
|
||||
brushes: Brushes::Ready(&self.brushes),
|
||||
graph_designs: designs,
|
||||
index: DefIndex::default(),
|
||||
};
|
||||
Used::of(&defs, &self.nodes)
|
||||
}
|
||||
}
|
||||
|
||||
/// The used global and spot colours whose name `d` gives another one: (pasted, document).
|
||||
@@ -1199,7 +1248,8 @@ impl Clipboard {
|
||||
/// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another
|
||||
/// document's are, while its image blobs are still the document's own under their keys.
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
|
||||
self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc)
|
||||
let used = self.used(d);
|
||||
self.import_used_with_images(d, &used, choices, same_doc && !self.colors_converted, same_doc)
|
||||
}
|
||||
|
||||
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
|
||||
@@ -1210,7 +1260,7 @@ impl Clipboard {
|
||||
if same_doc {
|
||||
return;
|
||||
}
|
||||
let used = self.used();
|
||||
let used = self.used(d);
|
||||
let colors: BTreeMap<String, Color> = self
|
||||
.conflicts(d, &used)
|
||||
.into_iter()
|
||||
@@ -1247,6 +1297,11 @@ impl Clipboard {
|
||||
) -> Result<Imported> {
|
||||
let mut out = Imported::default();
|
||||
out.relink.filters = self.filter_links(d, same_doc)?;
|
||||
let held = |name: &str| d.graph_designs.iter().any(|x| x.name == name);
|
||||
let new_designs = self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name) && !held(&g.name)).count();
|
||||
if new_designs > 0 && d.graph_designs.len().saturating_add(new_designs) > GraphDesign::MAX {
|
||||
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
|
||||
}
|
||||
self.import_images(d, used, same_doc_images, &mut out);
|
||||
self.import_swatches(d, used, choices, same_doc, &mut out);
|
||||
self.import_kinsoku_sets(d, used, same_doc, &mut out);
|
||||
@@ -1330,11 +1385,18 @@ impl Clipboard {
|
||||
.collect(),
|
||||
None => HashMap::new(),
|
||||
};
|
||||
// A symbol whose graphs the paste draws again with the document's designs is
|
||||
// also the document's one that holds its art drawn that way (an earlier paste
|
||||
// added it).
|
||||
let redrawn = (!fresh && d.symbols.iter().any(|s| copy_of(&def.name, &s.name)))
|
||||
.then(|| self.redrawn_art(d, &def.art, &out.relink))
|
||||
.flatten();
|
||||
let r = &out.relink;
|
||||
let p = place(&mut d.symbols, def, same_doc, |a, b| {
|
||||
!fresh
|
||||
&& options.is_none_or(|o| theirs.get(&a.name) == Some(o))
|
||||
&& same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|
||||
&& (same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|
||||
|| redrawn.as_ref().is_some_and(|art| without_ids(&a.art) == *art))
|
||||
});
|
||||
if let Some(name) = p.new_name(&def.name) {
|
||||
if let Some(o) = options {
|
||||
@@ -1370,6 +1432,7 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
self.import_graphic_styles(d, used, same_doc, &mut out);
|
||||
self.import_graph_designs(d, used, same_doc, &mut out)?;
|
||||
for (r, name, def) in added_styles {
|
||||
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
|
||||
if let Some(s) = theirs.iter_mut().find(|s| s.name == name) {
|
||||
@@ -1380,6 +1443,7 @@ impl Clipboard {
|
||||
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
|
||||
out.relink.node(Arc::make_mut(&mut s.art));
|
||||
}
|
||||
out.added_symbols = added_symbols.into_iter().collect();
|
||||
for p in d.patterns.iter_mut().filter(|p| added_patterns.contains(&p.name)) {
|
||||
for a in &mut p.art {
|
||||
out.relink.node(Arc::make_mut(a));
|
||||
@@ -1496,6 +1560,10 @@ impl Clipboard {
|
||||
for a in self.brushes.iter().flat_map(Brush::art) {
|
||||
node_filters(a, &mut found);
|
||||
}
|
||||
// A design the document has under the same name stays its own, so its art here is not pasted.
|
||||
for g in self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)) {
|
||||
node_filters(&g.art, &mut found);
|
||||
}
|
||||
for g in &self.graphic_styles {
|
||||
appearance_filters(&g.appearance, &mut found);
|
||||
}
|
||||
@@ -1574,6 +1642,7 @@ impl Clipboard {
|
||||
for w in &bases {
|
||||
let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge {
|
||||
out.merged += 1;
|
||||
out.merged_swatches.insert(w.name.clone());
|
||||
Placed::Existing
|
||||
} else {
|
||||
add_swatch(d, w, same_doc)
|
||||
@@ -1623,6 +1692,71 @@ impl Clipboard {
|
||||
out.relink.styles.insert(g.id, d.graphic_style_id(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol art `art` relinked by `relink` with its graphs drawn again with the designs `d` holds
|
||||
/// under a name whose design the clipboard lacks or holds with other art, as a paste that adds
|
||||
/// the symbol draws it, its ids left out ([`without_ids`]). `None` when no graph of it draws
|
||||
/// with such a design.
|
||||
fn redrawn_art(&self, d: &mut Document, art: &Arc<Node>, relink: &Relink) -> Option<Node> {
|
||||
let theirs = |n: &str| self.graph_designs.iter().find(|g| g.name == n);
|
||||
let differs: BTreeSet<String> = d
|
||||
.graph_designs
|
||||
.iter()
|
||||
.filter(|x| theirs(&x.name).is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art))
|
||||
.map(|x| x.name.clone())
|
||||
.collect();
|
||||
if differs.is_empty() || !crate::cmd::graph::holds_designs(art, &differs) {
|
||||
return None;
|
||||
}
|
||||
let mut n = (**art).clone();
|
||||
relink.node(&mut n);
|
||||
crate::cmd::graph::redraw_detached(d, &mut n, &differs);
|
||||
Some(without_ids(&n))
|
||||
}
|
||||
|
||||
/// Graph designs: the document's design of a name stays as it is and the pasted graphs draw
|
||||
/// with it ([`Imported::kept_designs`]); a design the document lacks is added under its name, its art following the
|
||||
/// resources placed above, with fresh ids. Called once every other resource is placed.
|
||||
fn import_graph_designs(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) -> Result<()> {
|
||||
// Every name the pasted graphs draw with whose design in the document would draw them
|
||||
// otherwise: another design of that name, one the clipboard holds no design for (deleted
|
||||
// and made again), or, from another document, the same art when a resource came in renamed
|
||||
// or a swatch took the document's color, that the design's art uses. (An SVG filter effect
|
||||
// carries its definition, so a filter that draws otherwise makes the art differ.)
|
||||
let defs = self.defs(&self.graph_designs);
|
||||
let moved = |n: &str| {
|
||||
if same_doc || (out.relink.renames.is_empty() && out.merged_swatches.is_empty()) {
|
||||
return false;
|
||||
}
|
||||
let uses = designs_used(&defs, &[n.to_string()]);
|
||||
out.relink.renames.iter().any(|(r, names)| names.keys().any(|from| uses.has(*r, from)))
|
||||
|| out.merged_swatches.iter().any(|w| uses.has(Res::Swatch, w))
|
||||
};
|
||||
let differs = |n: &str| {
|
||||
let ours = d.graph_designs.iter().find(|x| x.name == n);
|
||||
let theirs = self.graph_designs.iter().find(|g| g.name == n);
|
||||
ours.is_some_and(|x| theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art) || moved(n))
|
||||
};
|
||||
let named = used.names.get(&Res::GraphDesign).into_iter().flatten();
|
||||
let kept: Vec<String> = named.filter(|n| differs(n)).cloned().collect();
|
||||
out.kept_designs.extend(kept);
|
||||
for g in self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)) {
|
||||
if d.graph_designs.iter().any(|x| x.name == g.name) {
|
||||
out.placed(Res::GraphDesign, &g.name, &Placed::Existing);
|
||||
continue;
|
||||
}
|
||||
if d.graph_designs.len() >= GraphDesign::MAX {
|
||||
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
|
||||
}
|
||||
let mut art = (*g.art).clone();
|
||||
out.relink.node(&mut art);
|
||||
let art = d.reid(&art);
|
||||
d.graph_designs.push(GraphDesign { name: g.name.clone(), art: Arc::new(art) });
|
||||
out.placed(Res::GraphDesign, &g.name, &Placed::Added);
|
||||
out.added_designs.insert(g.name.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a loaded text style is in the document ([`import_text_styles`]).
|
||||
@@ -1662,6 +1796,72 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
|
||||
Ok(placed)
|
||||
}
|
||||
|
||||
/// The resources graph designs `names` of `src` use, through the definitions they lead to.
|
||||
fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used {
|
||||
let mut used = Used::default();
|
||||
let mut todo = vec![];
|
||||
for n in names {
|
||||
used.note(defs, Ref::Name(Res::GraphDesign, n), &mut todo);
|
||||
}
|
||||
used.follow(defs, todo);
|
||||
used
|
||||
}
|
||||
|
||||
/// A document holding `src`'s graph designs and the swatches, patterns, symbols, styles, brushes
|
||||
/// and images their art uses, and nothing else: what a document opened as a library keeps for the
|
||||
/// Graph Column and Graph Marker dialogs. `None` when `src` has no graph designs.
|
||||
pub(crate) fn graph_design_library(src: &Document) -> Option<Document> {
|
||||
if src.graph_designs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let names: Vec<String> = src.graph_designs.iter().map(|g| g.name.clone()).collect();
|
||||
let library = OnceCell::new();
|
||||
let used = designs_used(&Defs::of(src, &library), &names);
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
let mut d = clip.to_document();
|
||||
// A new document's default swatches and graphic styles give way to the source's of the same
|
||||
// name or id, so a design draws with the source's.
|
||||
let defaults = d.swatches.len().saturating_sub(clip.swatches.len());
|
||||
let mut i = 0;
|
||||
d.swatches.retain(|s| {
|
||||
i += 1;
|
||||
i > defaults || !clip.swatches.iter().any(|c| c.name == s.name)
|
||||
});
|
||||
// The swatch groups are all a new document's.
|
||||
for g in d.swatch_groups.iter_mut() {
|
||||
g.swatches.retain(|s| !clip.swatches.iter().any(|c| c.name == s.name));
|
||||
}
|
||||
let defaults = d.graphic_styles.len().saturating_sub(clip.graphic_styles.len());
|
||||
let mut i = 0;
|
||||
d.graphic_styles.retain(|g| {
|
||||
i += 1;
|
||||
i > defaults || !clip.graphic_styles.iter().any(|c| (c.id != 0 && c.id == g.id) || c.name == g.name)
|
||||
});
|
||||
// The symbols keep their Symbol Options, which the document keeps by name.
|
||||
for (name, options) in &clip.symbol_options {
|
||||
options.give(&mut d, name);
|
||||
}
|
||||
d.title = src.title.clone();
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Add graph designs `names` of `src` to `d`, with the swatches, patterns, symbols, styles,
|
||||
/// brushes and images their art uses, placed as Paste places them ([`Clipboard::import_into`]; a
|
||||
/// global or spot color whose name `d` gives another color is `d`'s). A design `d` has under the
|
||||
/// same name stays as it is, and the art of `src`'s design of that name is not followed. → the
|
||||
/// names of the designs added ([`Imported::added_designs`]): those of `names` `d` lacked, and those
|
||||
/// their art uses; with the symbols added and the designs `d` kept that their art draws with
|
||||
/// ([`Imported::added_symbols`], [`Imported::kept_designs`]). An error, with `d` unchanged, when `d`
|
||||
/// would hold more than [`GraphDesign::MAX`] designs.
|
||||
pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result<Imported> {
|
||||
let library = OnceCell::new();
|
||||
let held = |n: &str| d.graph_designs.iter().any(|x| x.name == n);
|
||||
let followed: Vec<GraphDesign> = src.graph_designs.iter().filter(|g| names.contains(&g.name) || !held(&g.name)).cloned().collect();
|
||||
let used = designs_used(&Defs { graph_designs: &followed, ..Defs::of(src, &library) }, names);
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
clip.import_used(d, &used, &SwatchChoices::default(), false)
|
||||
}
|
||||
|
||||
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
|
||||
/// share one namespace).
|
||||
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Color",
|
||||
[],
|
||||
None,
|
||||
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
|
||||
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; a color outside sRGB (a Lab color, a CMYK color or an RGB color in a wider working RGB space) is clipped to sRGB first",
|
||||
always,
|
||||
convert_color
|
||||
),
|
||||
@@ -1362,10 +1362,15 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let intent = intent_param(p, C)?.unwrap_or(c.settings().intent);
|
||||
let lab = c.lab(&col);
|
||||
let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") {
|
||||
"rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))),
|
||||
"cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))),
|
||||
"gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))),
|
||||
"lab" => ("lab", vec![lab.l, lab.a, lab.b]),
|
||||
"rgb" => ("rgb", json!(values(&c.convert(&col, Model::Rgb, intent)))),
|
||||
"cmyk" => ("cmyk", json!(values(&c.convert(&col, Model::Cmyk, intent)))),
|
||||
"gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))),
|
||||
"lab" => ("lab", json!([lab.l, lab.a, lab.b])),
|
||||
"oklch" => {
|
||||
// RGB numbers past 0..1 ([2, 2, 2]) display clipped, as `hex` reports them.
|
||||
let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col).map(|v| v.clamp(0.0, 1.0)));
|
||||
("oklch", json!([l * 100.0, ch, h]))
|
||||
}
|
||||
other => return Err(bad(C, format!("unknown model `{other}`"))),
|
||||
};
|
||||
let de = c.gamut_error(&col);
|
||||
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Circle Through Points",
|
||||
[],
|
||||
None,
|
||||
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
|
||||
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
circle_through_points
|
||||
),
|
||||
@@ -443,20 +443,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
|
||||
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
|
||||
/// undo step, named as an Ellipse tool drag is.
|
||||
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With
|
||||
/// `anchors: "points"` the circle is a plain path with an anchor at each point
|
||||
/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an
|
||||
/// Ellipse tool drag is.
|
||||
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
|
||||
};
|
||||
let key = "anchors";
|
||||
let at_points = match p.get(key).map(Value::as_str) {
|
||||
None | Some(Some("standard")) => false,
|
||||
Some(Some("points")) => true,
|
||||
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))),
|
||||
};
|
||||
let (center, radius) = shapes::circle_through_points(&points)
|
||||
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays through the points.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
let mut out = if at_points {
|
||||
add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))?
|
||||
} else {
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?
|
||||
};
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
|
||||
@@ -1568,6 +1568,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for xf in placements {
|
||||
for (k, n) in clip.nodes.iter().enumerate() {
|
||||
let mut c = d.reid(n);
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c);
|
||||
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
|
||||
if xf != Affine::IDENTITY {
|
||||
@@ -1651,6 +1653,17 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for id in &new_ids {
|
||||
super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default());
|
||||
}
|
||||
// A pasted graph whose design the document has under the same name draws with the document's,
|
||||
// in the pasted objects and in the art of the symbols the paste added.
|
||||
if !imported.kept_designs.is_empty() {
|
||||
super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?;
|
||||
super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
|
||||
}
|
||||
// The graphs already in the document that draw with a design the paste added are drawn
|
||||
// again with it; the pasted ones already draw with it.
|
||||
if !imported.added_designs.is_empty() {
|
||||
super::graph::refresh_graphs(d, &imported.added_designs, &new_ids, &imported.added_symbols)?;
|
||||
}
|
||||
sel.set(new_ids.iter().copied());
|
||||
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
|
||||
// paste of guides alone keeps them where they were, but onto another artboard or every
|
||||
|
||||
@@ -52,7 +52,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Apply Effect",
|
||||
[],
|
||||
None,
|
||||
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
|
||||
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (with params bevel {custom: name}: the custom bevel's points, used in place of the bevels file's; the journal records them so a replay draws the same bevel after the file changes)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -79,7 +79,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Effect Options",
|
||||
[],
|
||||
None,
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} → {ids}",
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}",
|
||||
has_doc,
|
||||
set_params
|
||||
),
|
||||
@@ -442,6 +442,17 @@ fn check_revolve_count(n: &Node, cmd: &str) -> Result<()> {
|
||||
|
||||
pub(crate) const ONE_3D: &str = "An object takes one 3D effect. Edit the existing effect's options, or remove it first.";
|
||||
|
||||
/// The Pathfinder Options that `effect.apply` gives a Pathfinder effect for the keys its `params`
|
||||
/// leave out: the preferences' Pathfinder Options in force.
|
||||
pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOptions {
|
||||
let current = super::pathops::current_pf_options(s);
|
||||
effects::PathfinderEffectOptions {
|
||||
precision: current.precision,
|
||||
remove_redundant_points: current.remove_redundant_points,
|
||||
remove_unpainted: current.remove_unpainted,
|
||||
}
|
||||
}
|
||||
|
||||
/// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the
|
||||
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one;
|
||||
/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
|
||||
@@ -465,13 +476,30 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::params::check_effect_color(C, id, ¶ms)?;
|
||||
super::params::check_effect_channel(C, id, ¶ms)?;
|
||||
super::params::check_effect_center(C, id, ¶ms)?;
|
||||
super::params::check_effect_pathfinder(C, id, ¶ms)?;
|
||||
// Crop Marks take their style from the preferences when applied.
|
||||
if id == effects::CROP_MARKS && params.get("style").is_none() {
|
||||
params["style"] = json!(s.crop_mark_style().id());
|
||||
}
|
||||
// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those `params`
|
||||
// give aside. They join the journal entry, so replaying it gives the same effect.
|
||||
if effects::takes_pathfinder_options(id) {
|
||||
if let Value::Object(filled) = pathfinder_effect_options(s).to_params() {
|
||||
for (key, v) in filled {
|
||||
if params.get(&key).is_none() {
|
||||
params[key.as_str()] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
s.note_journal("params", params.clone());
|
||||
}
|
||||
if texture_load_effect(id) {
|
||||
load_texture(&mut params, C)?;
|
||||
}
|
||||
// A custom bevel by name takes a copy of its points from the bevels file.
|
||||
if bevel_effect(id) {
|
||||
super::bevels::resolve_custom(s, p, &mut params, C)?;
|
||||
}
|
||||
// An SVG filter needs its <filter> element, and is named by its id.
|
||||
if id == effects::SVG_FILTER {
|
||||
let xml = params.get("xml").and_then(Value::as_str).ok_or_else(|| bad(C, "give `xml`, one SVG <filter> element"))?;
|
||||
@@ -789,10 +817,14 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::params::check_effect_color(C, effect, ¶ms)?;
|
||||
super::params::check_effect_channel(C, effect, ¶ms)?;
|
||||
super::params::check_effect_center(C, effect, ¶ms)?;
|
||||
super::params::check_effect_pathfinder(C, effect, ¶ms)?;
|
||||
}
|
||||
if edited.iter().any(|e| texture_load_effect(e)) {
|
||||
load_texture(&mut params, C)?;
|
||||
}
|
||||
if edited.iter().any(|e| bevel_effect(e)) || kind == Some(effects::EXTRUDE) {
|
||||
super::bevels::resolve_custom(s, p, &mut params, C)?;
|
||||
}
|
||||
let targets = effect_targets(s, p, item, index, C)?;
|
||||
// The type each 3D effect already has, with nothing else to change, is no edit (and is not
|
||||
// checked again).
|
||||
@@ -808,6 +840,15 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
}
|
||||
// Pathfinder effects given the values they already evaluate with, and nothing else to change,
|
||||
// are no edit and record no undo step.
|
||||
if kind.is_none() && warp_id.is_none() && visible.is_none() {
|
||||
let d = &s.doc()?.doc;
|
||||
let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect();
|
||||
if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, ¶ms)) {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
}
|
||||
// An SVG filter is named by its id: another filter renames the effect.
|
||||
if edited.iter().any(|e| e == effects::SVG_FILTER)
|
||||
&& let Some(xml) = params.get("xml").and_then(Value::as_str)
|
||||
@@ -876,6 +917,36 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// Does effect `id` take a `bevel` (Extrude & Bevel, Extrude & Bevel (Classic)), which may be a
|
||||
/// custom bevel given by name?
|
||||
fn bevel_effect(id: &str) -> bool {
|
||||
id == effects::EXTRUDE || id == effects::CLASSIC_EXTRUDE
|
||||
}
|
||||
|
||||
/// Does merging `params` into Pathfinder effect `e` leave it drawing as it does: the same Pathfinder
|
||||
/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their
|
||||
/// defaults is unchanged), each option given equal to the one it stores (a precision that Scale
|
||||
/// Strokes & Effects took past its range evaluates at the bound but is still edited), and every
|
||||
/// other value given equal to the one it has?
|
||||
fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool {
|
||||
if !effects::takes_pathfinder_options(&e.id) {
|
||||
return false;
|
||||
}
|
||||
let Some(given) = params.as_object().filter(|m| !m.is_empty()) else { return true };
|
||||
let current = effects::merged_params(&e.id, &e.params);
|
||||
let mut after = current.clone();
|
||||
if let Value::Object(m) = &mut after {
|
||||
m.extend(given.clone());
|
||||
}
|
||||
let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v));
|
||||
let same_value = |a: &Value, b: &Value| a == b || a.as_f64().is_some_and(|x| b.as_f64() == Some(x));
|
||||
let stored_same = given
|
||||
.iter()
|
||||
.filter(|(k, _)| effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str()))
|
||||
.all(|(k, v)| e.params.get(k).is_none_or(|stored| same_value(stored, v)));
|
||||
others_same && stored_same && effects::PathfinderEffectOptions::from_params(¤t) == effects::PathfinderEffectOptions::from_params(&after)
|
||||
}
|
||||
|
||||
// ---------- Load Texture ----------
|
||||
|
||||
/// Effect › Distort › Glass.
|
||||
|
||||
@@ -1193,7 +1193,8 @@ impl SaveJob {
|
||||
}
|
||||
// The other open documents that place this one show the new version.
|
||||
let written = self.plan.path.clone().filter(|_| matches!(self.plan.format.id, "vectorcraft" | "template"));
|
||||
// A save of the arrowheads file lists its heads in the arrowhead menus.
|
||||
// A save of the arrowheads file lists its heads in the arrowhead menus, and one of the
|
||||
// bevels file its bevels in the Bevel Shape menus.
|
||||
let native = self.plan.format.id == "vectorcraft";
|
||||
if let Some(st) = s.document_mut(uid) {
|
||||
self.finish(st);
|
||||
@@ -1204,6 +1205,7 @@ impl SaveJob {
|
||||
if let Some(path) = written {
|
||||
if native {
|
||||
s.arrowheads_saved(&path);
|
||||
s.bevels_saved(&path);
|
||||
}
|
||||
crate::cmd::links::refresh_placed(s, uid, &path);
|
||||
}
|
||||
|
||||
@@ -141,7 +141,11 @@ impl Builder {
|
||||
if fills.is_empty() { Body::Complex } else { Body::Fills { shape: self.shape(path, rule, Kind::Vector)?, fills } }
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
|
||||
// A distorted image's frame joins its corners.
|
||||
let frame = match n.image_frame().filter(|_| n.is_distorted_image()) {
|
||||
Some(bp) => PathData::from_bezpath(&bp),
|
||||
None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf),
|
||||
};
|
||||
self.shape(frame, FillRule::NonZero, Kind::Other)?;
|
||||
Body::Complex
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`.
|
||||
// While the Live Paint Bucket is active the proxies show the default paint, whose stops can be
|
||||
// selected with a part picked.
|
||||
if s.tool_id() != super::paint::LIVE_PAINT_BUCKET && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
|
||||
if !s.bucket_paints() && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
let index = match p.get("index") {
|
||||
@@ -111,7 +111,7 @@ impl StopOwner {
|
||||
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
|
||||
fill: s.fill_active,
|
||||
item: s.appearance_item(),
|
||||
bucket: s.tool_id() == super::paint::LIVE_PAINT_BUCKET,
|
||||
bucket: s.bucket_paints(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -804,7 +804,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke);
|
||||
leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect()
|
||||
}
|
||||
_ => item.targets(s, p)?,
|
||||
_ => item.targets_for(s, p, !stroke)?,
|
||||
};
|
||||
if targets.is_empty() {
|
||||
return Err(EngineError::Other("nothing selected".into()));
|
||||
|
||||
@@ -41,6 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph
|
||||
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, to_csv};
|
||||
pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs};
|
||||
pub use edit::{GraphTypeSubject, graph_type_subject};
|
||||
pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed};
|
||||
pub use generate::calculated_axes;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::data::fmt_value;
|
||||
use super::designs::design_names;
|
||||
use super::designs::{bring_in_for, design_names, from_library, libraries_json};
|
||||
use super::edit::{regenerate, spec_of, target};
|
||||
use super::generate::generate_with;
|
||||
use super::markers::{design_frame, fit_affine};
|
||||
@@ -437,7 +437,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let picked = picked_series(s, p, id, count, C)?;
|
||||
let names = design_names(&s.doc()?.doc);
|
||||
let mut names = design_names(&s.doc()?.doc);
|
||||
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked.clone() };
|
||||
// The column design the picked series (all of them with none picked) share; a design deleted since doesn't count,
|
||||
// as those series draw plain columns.
|
||||
@@ -446,14 +446,21 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let shared = used.first().copied().flatten().filter(|c| used.iter().all(|x| *x == Some(*c))).cloned();
|
||||
let Some(v) = p.get("design") else {
|
||||
let options = shared.clone().unwrap_or_default();
|
||||
return Ok(json!({
|
||||
let mut out = json!({
|
||||
"designs": names,
|
||||
"design": shared.map(|c| c.design),
|
||||
"columnType": options.column_type.id(),
|
||||
"each": options.each,
|
||||
"fractions": options.fractions.id(),
|
||||
}));
|
||||
});
|
||||
if let Some(libs) = libraries_json(s) {
|
||||
out["libraries"] = libs;
|
||||
}
|
||||
return Ok(out);
|
||||
};
|
||||
// A design of a loaded library comes into the document in the same undo step.
|
||||
let library = from_library(s, p, C)?;
|
||||
names.extend(library.as_ref().map(|(_, n)| n.clone()));
|
||||
let design = match v {
|
||||
Value::Null => None,
|
||||
Value::String(n) if names.contains(n) => Some(n.clone()),
|
||||
@@ -485,11 +492,17 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Drawn once on a copy of the document, to refuse designs past the budget before the edit.
|
||||
let mut probe = (*s.doc()?.doc).clone();
|
||||
if let Some((lib, name)) = &library {
|
||||
bring_in_for(&mut probe, lib, name, id, &mut spec)?;
|
||||
}
|
||||
let looks = column_designs(&probe, &spec);
|
||||
if generate_with(&mut probe, &spec, &looks).is_none() {
|
||||
return Err(bad(C, "the design is too big to draw in every column of this graph"));
|
||||
}
|
||||
s.edit("Graph Column", |d, sel| {
|
||||
if let Some((lib, name)) = &library {
|
||||
bring_in_for(d, lib, name, id, &mut spec)?;
|
||||
}
|
||||
regenerate(d, id, spec)?;
|
||||
if !reselect.is_empty() {
|
||||
reselect_series(d, sel, id, &reselect);
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Design…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list)}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with]}",
|
||||
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list), library?: the id or name of a document loaded with swatch.library.load (Other Library…) that holds graph designs, add?: name|[names] of that library's designs (copy them into the document as one undo step, with the swatches, patterns, symbols, styles, brushes and images their art uses, as pasting brings them; a design the document already has under the same name stays as it is) → {added: [names], existing: [names the document already had]}}; library alone → {designs: [the library's names]}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with], libraries?: [{library, name, designs}] (the loaded libraries that hold graph designs)}",
|
||||
has_doc,
|
||||
design
|
||||
),
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Column…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, seriesIndexes?: [index], design?: name|null, columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions}",
|
||||
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used), columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions, libraries?: [{library, name, designs}]}",
|
||||
has_selection,
|
||||
set_column
|
||||
),
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Marker…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, seriesIndexes?: [index], design?: name|null} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null}",
|
||||
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used)} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null, libraries?: [{library, name, designs}]}",
|
||||
has_selection,
|
||||
set_marker
|
||||
),
|
||||
|
||||
@@ -1,44 +1,291 @@
|
||||
use super::edit::regenerate;
|
||||
use super::{Arc, Document, GraphDesign, GraphSpec, Result, Session, Value, bad, json, ok, str_param};
|
||||
use super::edit::{regenerate, regenerate_detached};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::{Arc, Document, GraphDesign, GraphKind, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param};
|
||||
use crate::cmd::clipboard::resources::import_graph_designs;
|
||||
use crate::cmd::swatchlib::{concealed_library_id, shown_library_id};
|
||||
|
||||
/// The document's graph design names, in order.
|
||||
pub(super) fn design_names(d: &Document) -> Vec<String> {
|
||||
d.graph_designs.iter().map(|x| x.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// Whether graph `g` draws a series with design `name`, as its marker or its columns.
|
||||
/// The library param `library` names: a document Other Library… loaded (`swatch.library.load`)
|
||||
/// that holds graph designs, by its id, the id a reply showed for it, or its name (in any case, as
|
||||
/// swatch library names are matched). `None` without
|
||||
/// `library`.
|
||||
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Arc<Document>>> {
|
||||
let key = match p.get("library") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(Value::String(k)) => k.as_str(),
|
||||
Some(_) => {
|
||||
let list = "graph.design";
|
||||
return Err(bad(cmd, format!("`library` is a library id or name (see {list})")));
|
||||
}
|
||||
};
|
||||
let libs = &s.graph_design_libraries;
|
||||
let own = concealed_library_id(s, key);
|
||||
libs.get(key)
|
||||
.or_else(|| own.as_deref().and_then(|id| libs.get(id)))
|
||||
.or_else(|| libs.iter().find(|l| l.name.eq_ignore_ascii_case(key)))
|
||||
.map(|l| Some(l.doc.clone()))
|
||||
.ok_or_else(|| bad(cmd, format!("no library `{key}`")))
|
||||
}
|
||||
|
||||
/// The loaded libraries' designs, as lists show them: `[{library, name, designs}]`; `None` when no
|
||||
/// loaded library holds graph designs.
|
||||
pub(super) fn libraries_json(s: &Session) -> Option<Value> {
|
||||
let libs: Vec<Value> = s
|
||||
.graph_design_libraries
|
||||
.iter()
|
||||
.map(|l| json!({ "library": shown_library_id(s, &l.id), "name": l.name, "designs": design_names(&l.doc) }))
|
||||
.collect();
|
||||
(!libs.is_empty()).then(|| json!(libs))
|
||||
}
|
||||
|
||||
/// The library design `p`'s `design` names, with the library to bring it in from, when `p` gives a
|
||||
/// `library` and the document has no design of that name: the document's own design of a name is
|
||||
/// the one a graph draws with.
|
||||
pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result<Option<(Arc<Document>, String)>> {
|
||||
let Some(lib) = library_param(s, p, cmd)? else { return Ok(None) };
|
||||
let Some(Value::String(n)) = p.get("design") else { return Ok(None) };
|
||||
if s.doc()?.doc.graph_designs.iter().any(|x| x.name == *n) {
|
||||
return Ok(None);
|
||||
}
|
||||
if !lib.graph_designs.iter().any(|x| x.name == *n) {
|
||||
return Err(bad(cmd, format!("no design named `{n}`")));
|
||||
}
|
||||
Ok(Some((lib, n.clone())))
|
||||
}
|
||||
|
||||
/// Add designs `names` of library `lib` to `d` with the resources their art uses, and redraw the
|
||||
/// graphs that already name a design the document lacked: one of `names`, or one their art uses.
|
||||
/// The graphs in the art of the symbols that came in are drawn with the designs the document kept.
|
||||
pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> {
|
||||
let imported = import_graph_designs(lib, d, names)?;
|
||||
if !imported.kept_designs.is_empty() {
|
||||
redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
|
||||
}
|
||||
if !imported.added_designs.is_empty() {
|
||||
refresh_graphs(d, &imported.added_designs, &[], &BTreeSet::new())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`bring_in`] library design `name` for graph `id`, whose new spec is `spec`: when that redraws
|
||||
/// the graph, `spec` takes the rectangle the redraw gave it, so a graph moved or resized since it
|
||||
/// was last drawn stays where it is.
|
||||
pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: super::NodeId, spec: &mut GraphSpec) -> Result<()> {
|
||||
bring_in(d, lib, &[name.to_string()])?;
|
||||
if let Some(g) = d.node(id).and_then(|n| n.extras().graph.as_deref()) {
|
||||
spec.rect = g.rect;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether graph `g` draws a series with design `name`: as the marker of a series drawn with
|
||||
/// markers (every series of a scatter or radar graph, and line series) while Mark Data Points is
|
||||
/// on or the legend has an entry for the series, or as the columns of a series drawn as columns or
|
||||
/// bars.
|
||||
fn draws_with(g: &GraphSpec, name: &str) -> bool {
|
||||
let scatter = g.kind == GraphKind::Scatter;
|
||||
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
// The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank
|
||||
// (a scatter graph's entries are its pairs of series, labeled by the first of each pair).
|
||||
let in_legend = |s: usize| {
|
||||
let entries = if scatter { nser.div_ceil(2) } else { nser };
|
||||
let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str);
|
||||
g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label)
|
||||
};
|
||||
// Point markers use the same range of designs: a scatter graph plots a pair of series for each.
|
||||
let plotted = if scatter { nser.div_ceil(2) } else { nser };
|
||||
let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s));
|
||||
let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line);
|
||||
let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar);
|
||||
g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s))
|
||||
|| g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s))
|
||||
}
|
||||
|
||||
/// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or
|
||||
/// not the series draws with it.
|
||||
fn names_design(g: &GraphSpec, name: &str) -> bool {
|
||||
g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name)
|
||||
}
|
||||
|
||||
/// Regenerate the graphs whose series use design `name` (it was added or removed).
|
||||
/// Regenerate the graphs whose series use design `name` (it was added or removed), in the layers,
|
||||
/// in opacity-mask art and in symbols' art.
|
||||
fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> {
|
||||
let mut ids = vec![];
|
||||
refresh_graphs(d, &BTreeSet::from([name.to_string()]), &[], &BTreeSet::new())
|
||||
}
|
||||
|
||||
/// Regenerate the graphs that draw a series with one of the designs `names`, in the layers, in
|
||||
/// opacity-mask art and in symbols' art, except those in the subtrees of `skip` and in the art of
|
||||
/// symbols `skip_symbols`.
|
||||
pub(crate) fn refresh_graphs(d: &mut Document, names: &BTreeSet<String>, skip: &[super::NodeId], skip_symbols: &BTreeSet<String>) -> Result<()> {
|
||||
let mut skipped = std::collections::HashSet::new();
|
||||
for n in skip.iter().filter_map(|id| d.node(*id)) {
|
||||
n.walk(&mut |m| {
|
||||
skipped.insert(m.id);
|
||||
});
|
||||
}
|
||||
let (mut ids, mut masked) = (vec![], vec![]);
|
||||
d.walk(|n| {
|
||||
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) {
|
||||
if skipped.contains(&n.id) {
|
||||
return;
|
||||
}
|
||||
if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
|
||||
ids.push(n.id);
|
||||
}
|
||||
if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, names)) {
|
||||
masked.push(n.id);
|
||||
}
|
||||
});
|
||||
for id in ids {
|
||||
if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) {
|
||||
regenerate(d, id, spec)?;
|
||||
}
|
||||
}
|
||||
// The graphs in objects' opacity-mask art.
|
||||
for id in masked {
|
||||
let Some(mut art) = d.node(id).and_then(|n| n.extras().mask.as_deref()).map(|m| (*m.art).clone()) else { continue };
|
||||
redraw_in(d, &mut art, names);
|
||||
if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) {
|
||||
mask.art = Arc::new(art);
|
||||
}
|
||||
}
|
||||
// And the graphs in symbols' art, which instances draw.
|
||||
let symbols: BTreeSet<String> = d.symbols.iter().map(|s| s.name.clone()).filter(|s| !skip_symbols.contains(s)).collect();
|
||||
redraw_symbols_with_designs(d, &symbols, names);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The designs no graph's series draw with (Select Unused).
|
||||
/// [`redraw_in`] for the clipboard: graph art `n`, outside the document, drawn again with `d`'s
|
||||
/// designs `names`.
|
||||
pub(crate) fn redraw_detached(d: &mut Document, n: &mut Node, names: &BTreeSet<String>) {
|
||||
if holds(n, names) {
|
||||
redraw_in(d, n, names);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series
|
||||
/// with one of the designs `names`.
|
||||
pub(crate) fn holds_designs(n: &Node, names: &BTreeSet<String>) -> bool {
|
||||
holds(n, names)
|
||||
}
|
||||
|
||||
/// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs
|
||||
/// `names`: pasted graphs, after the paste kept the document's own designs of those names.
|
||||
pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet<String>) -> Result<()> {
|
||||
for id in ids {
|
||||
let Some(mut n) = d.node(*id).filter(|n| holds(n, names)).cloned() else { continue };
|
||||
redraw_in(d, &mut n, names);
|
||||
*d.node_mut(*id).ok_or(super::EngineError::NoNode(*id))? = n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Draw the graphs in the art of symbols `symbols` again that draw a series with one of the
|
||||
/// designs `names`: graphs of the symbols a paste added, after the paste kept the document's own
|
||||
/// designs of those names.
|
||||
pub(crate) fn redraw_symbols_with_designs(
|
||||
d: &mut Document,
|
||||
symbols: &std::collections::BTreeSet<String>,
|
||||
names: &std::collections::BTreeSet<String>,
|
||||
) {
|
||||
for i in 0..d.symbols.len() {
|
||||
let Some(s) = d.symbols.get(i).filter(|s| symbols.contains(&s.name) && holds(&s.art, names)) else { continue };
|
||||
let old = s.art.clone();
|
||||
let mut art = (*old).clone();
|
||||
redraw_in(d, &mut art, names);
|
||||
let Some(s) = d.symbols.get_mut(i) else { continue };
|
||||
s.art = Arc::new(art);
|
||||
// Instances' changes to parts the redraw replaced are dropped.
|
||||
let name = s.name.clone();
|
||||
crate::cmd::symboledit::follow_art_change(d, &name, &old);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series
|
||||
/// with one of the designs `names`.
|
||||
fn holds(n: &Node, names: &std::collections::BTreeSet<String>) -> bool {
|
||||
let mut found = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
found |= m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name)));
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Redraw the graphs of `n`'s subtree, the art of opacity masks included, that draw a series with
|
||||
/// one of the designs `names`.
|
||||
fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet<String>) {
|
||||
if let Some(mut art) = n.extras().mask.as_deref().filter(|m| holds(&m.art, names)).map(|m| (*m.art).clone()) {
|
||||
redraw_in(d, &mut art, names);
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
|
||||
mask.art = Arc::new(art);
|
||||
}
|
||||
}
|
||||
if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
|
||||
regenerate_detached(d, n);
|
||||
return;
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut().filter(|c| holds(c, names)) {
|
||||
redraw_in(d, Arc::make_mut(c), names);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The designs no graph's series draw with (Select Unused): graphs in the layers, in opacity-mask
|
||||
/// art and in symbols' art count.
|
||||
fn unused_designs(d: &Document) -> Vec<String> {
|
||||
let mut used = std::collections::HashSet::new();
|
||||
d.walk(|n| {
|
||||
let mut note = |n: &Node| {
|
||||
if let Some(g) = n.extras().graph.as_deref() {
|
||||
used.extend(g.series_markers.iter().flatten().cloned());
|
||||
used.extend(g.series_columns.iter().flatten().map(|c| c.design.clone()));
|
||||
}
|
||||
});
|
||||
};
|
||||
for art in d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(art, &mut note);
|
||||
}
|
||||
d.graph_designs.iter().map(|x| x.name.clone()).filter(|n| !used.contains(n)).collect()
|
||||
}
|
||||
|
||||
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that names design
|
||||
/// `name` for a series ([`names_design`]).
|
||||
fn names_in(n: &Node, name: &str) -> bool {
|
||||
let mut found = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
found |= m.extras().graph.as_deref().is_some_and(|g| names_design(g, name));
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Graph `g`'s series that name design `old` name `new` instead.
|
||||
fn rename_series(g: &mut GraphSpec, old: &str, new: &str) {
|
||||
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
|
||||
*m = new.to_string();
|
||||
}
|
||||
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
|
||||
c.design = new.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// [`rename_series`] for the graphs of `n`'s subtree, the art of opacity masks included.
|
||||
fn rename_in(n: &mut Node, old: &str, new: &str) {
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()).filter(|m| names_in(&m.art, old)) {
|
||||
rename_in(Arc::make_mut(&mut mask.art), old, new);
|
||||
}
|
||||
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
|
||||
rename_series(g, old, new);
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut().filter(|c| names_in(c, old)) {
|
||||
rename_in(Arc::make_mut(c), old, new);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Design names from param `key`: one name or a list of names.
|
||||
fn names_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Vec<String>>> {
|
||||
match p.get(key) {
|
||||
@@ -105,22 +352,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(x) = d.graph_designs.iter_mut().find(|x| x.name == old) {
|
||||
x.name = new.clone();
|
||||
}
|
||||
let mut graphs = vec![];
|
||||
let (mut graphs, mut masked) = (vec![], vec![]);
|
||||
d.walk(|n| {
|
||||
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, &old)) {
|
||||
if n.extras().graph.as_deref().is_some_and(|g| names_design(g, &old)) {
|
||||
graphs.push(n.id);
|
||||
}
|
||||
if n.extras().mask.as_deref().is_some_and(|m| names_in(&m.art, &old)) {
|
||||
masked.push(n.id);
|
||||
}
|
||||
});
|
||||
for id in graphs {
|
||||
if let Some(g) = d.node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) {
|
||||
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
|
||||
*m = new.clone();
|
||||
}
|
||||
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
|
||||
c.design = new.clone();
|
||||
}
|
||||
rename_series(g, &old, &new);
|
||||
}
|
||||
}
|
||||
// The graphs in opacity-mask art and in symbols' art follow too, their art as it is.
|
||||
for id in masked {
|
||||
if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) {
|
||||
rename_in(Arc::make_mut(&mut mask.art), &old, &new);
|
||||
}
|
||||
}
|
||||
for s in d.symbols.iter_mut().filter(|s| names_in(&s.art, &old)) {
|
||||
rename_in(Arc::make_mut(&mut s.art), &old, &new);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({ "name": to }));
|
||||
@@ -159,7 +413,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
// Designs from a document loaded as a library: those the document has under the same name stay
|
||||
// as they are.
|
||||
if let Some(mut wanted) = names_param(p, "add", C)? {
|
||||
let lib = library_param(s, p, C)?.ok_or_else(|| bad(C, "missing `library`"))?;
|
||||
if let Some(n) = wanted.iter().find(|n| !lib.graph_designs.iter().any(|x| x.name == **n)) {
|
||||
return Err(bad(C, format!("no design named `{n}`")));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
wanted.retain(|n| seen.insert(n.clone()));
|
||||
let (existing, added): (Vec<String>, Vec<String>) = wanted.into_iter().partition(|n| taken(s, n));
|
||||
if !added.is_empty() {
|
||||
s.edit("New Design", |d, _| bring_in(d, &lib, &added))?;
|
||||
}
|
||||
return Ok(json!({ "added": added, "existing": existing }));
|
||||
}
|
||||
if let Some(lib) = library_param(s, p, C)? {
|
||||
return Ok(json!({ "designs": design_names(&lib) }));
|
||||
}
|
||||
// The list, with the designs no graph draws with (Select Unused picks those).
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(json!({ "designs": design_names(d), "unused": unused_designs(d) }))
|
||||
let mut out = json!({ "designs": design_names(d), "unused": unused_designs(d) });
|
||||
if let Some(libs) = libraries_json(s) {
|
||||
out["libraries"] = libs;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -109,6 +109,33 @@ pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) {
|
||||
/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them).
|
||||
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
carry_moves(n, &mut spec);
|
||||
let children = generate(d, &spec);
|
||||
spec.placed = children_bounds(&children);
|
||||
spec.placed_art = art_bounds(&children);
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
n.extras_mut().graph = Some(Box::new(spec));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`regenerate`] graph `n` from its own spec, where `n` is outside `d`'s layers (in a symbol's art).
|
||||
pub(super) fn regenerate_detached(d: &mut Document, n: &mut Node) {
|
||||
let Some(mut spec) = n.extras().graph.as_deref().cloned() else { return };
|
||||
carry_moves(n, &mut spec);
|
||||
let children = generate(d, &spec);
|
||||
spec.placed = children_bounds(&children);
|
||||
spec.placed_art = art_bounds(&children);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
n.extras_mut().graph = Some(Box::new(spec));
|
||||
}
|
||||
|
||||
/// Adjust `spec`'s plot rect for any move or scale of graph `n` since its last generation.
|
||||
fn carry_moves(n: &Node, spec: &mut GraphSpec) {
|
||||
if let Some((placed, now)) = measured(n)
|
||||
&& placed.width() > 1e-9
|
||||
&& placed.height() > 1e-9
|
||||
@@ -119,15 +146,6 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R
|
||||
* Affine::translate(-placed.origin().to_vec2());
|
||||
spec.rect = a.transform_rect_bbox(spec.rect);
|
||||
}
|
||||
let children = generate(d, &spec);
|
||||
spec.placed = children_bounds(&children);
|
||||
spec.placed_art = art_bounds(&children);
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
n.extras_mut().graph = Some(Box::new(spec));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::designs::design_names;
|
||||
use super::designs::{bring_in_for, design_names, from_library, libraries_json};
|
||||
use super::edit::{regenerate, spec_of, target};
|
||||
use super::series::{picked_series, reselect_series};
|
||||
use super::{Affine, Arc, Document, GraphSpec, Node, NodeKind, Rect, Result, Session, Value, bad, json};
|
||||
@@ -55,7 +55,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let picked = picked_series(s, p, id, count, C)?;
|
||||
let names = design_names(&s.doc()?.doc);
|
||||
let mut names = design_names(&s.doc()?.doc);
|
||||
let Some(v) = p.get("design") else {
|
||||
// The design the picked series (all of them with none picked) share, or null.
|
||||
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked };
|
||||
@@ -63,8 +63,15 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let used: Vec<Option<&String>> =
|
||||
all.iter().map(|i| spec.series_markers.get(*i).and_then(Option::as_ref).filter(|n| names.contains(n))).collect();
|
||||
let shared = used.first().copied().flatten().filter(|d| used.iter().all(|x| *x == Some(*d)));
|
||||
return Ok(json!({ "designs": names, "design": shared }));
|
||||
let mut out = json!({ "designs": names, "design": shared });
|
||||
if let Some(libs) = libraries_json(s) {
|
||||
out["libraries"] = libs;
|
||||
}
|
||||
return Ok(out);
|
||||
};
|
||||
// A design of a loaded library comes into the document in the same undo step.
|
||||
let library = from_library(s, p, C)?;
|
||||
names.extend(library.as_ref().map(|(_, n)| n.clone()));
|
||||
let design = match v {
|
||||
Value::Null => None,
|
||||
Value::String(n) if names.contains(n) => Some(n.clone()),
|
||||
@@ -83,10 +90,21 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
while spec.series_markers.last().is_some_and(Option::is_none) {
|
||||
spec.series_markers.pop();
|
||||
}
|
||||
if marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)) > MARKER_BUDGET {
|
||||
let cost = match &library {
|
||||
Some((lib, name)) => {
|
||||
let mut probe = (*s.doc()?.doc).clone();
|
||||
bring_in_for(&mut probe, lib, name, id, &mut spec)?;
|
||||
marker_cost(&spec, &marker_designs(&probe, &spec))
|
||||
}
|
||||
None => marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)),
|
||||
};
|
||||
if cost > MARKER_BUDGET {
|
||||
return Err(bad(C, "the design is too big to draw at every data point of this graph"));
|
||||
}
|
||||
s.edit("Graph Marker", |d, sel| {
|
||||
if let Some((lib, name)) = &library {
|
||||
bring_in_for(d, lib, name, id, &mut spec)?;
|
||||
}
|
||||
regenerate(d, id, spec)?;
|
||||
if !reselect.is_empty() {
|
||||
reselect_series(d, sel, id, &reselect);
|
||||
|
||||
@@ -5469,6 +5469,964 @@ fn graph_designs_are_saved_pasted_and_deleted() {
|
||||
assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
}
|
||||
|
||||
/// Graph design "Coin" in the active document: a 10 × 10 rectangle filled with global swatch "Gold".
|
||||
fn save_coin_design(s: &mut Session) {
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": "#d4a017", "global": true})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Gold", "ids": [r]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "Coin"})).unwrap();
|
||||
}
|
||||
|
||||
/// Load a saved document holding [`save_coin_design`]'s design as a swatch library (Other
|
||||
/// Library…) → its id.
|
||||
fn load_coin_library(s: &mut Session) -> String {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut src);
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Coins.vectorcraft"});
|
||||
let r = s.execute("swatch.library.load", &p).unwrap();
|
||||
assert_eq!(r["graphDesigns"], 1);
|
||||
r["library"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Whether some object of `n` is filled with a colour linked to swatch `name`.
|
||||
fn paints_with_swatch(n: &vectorcraft_doc::Node, name: &str) -> bool {
|
||||
let mut found = false;
|
||||
n.walk(&mut |m| found |= m.appearance.items.iter().any(|it| matches!(it.paint(), Paint::Solid { swatch: Some(w), .. } if w == name)));
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// The Column dialog's list: none of the document's, Coin from the library.
|
||||
let q = s.execute("graph.column", &json!({})).unwrap();
|
||||
assert_eq!((q["designs"].clone(), q["libraries"][0]["library"].clone()), (json!([]), json!(lib)));
|
||||
assert_eq!(q["libraries"][0]["designs"], json!(["Coin"]));
|
||||
assert!(s.execute("graph.column", &json!({"design": "Coin"})).is_err(), "not the document's");
|
||||
let steps = undo_len(&s);
|
||||
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
|
||||
assert_eq!(undo_len(&s), steps + 1, "one undo step");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
|
||||
assert!(d.swatch("Gold").is_some_and(|w| w.global), "the swatch the design's art uses comes along");
|
||||
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold"));
|
||||
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "the columns draw the design");
|
||||
// Undo takes the design, its swatch and the columns' design out together.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.is_empty() && d.swatch("Gold").is_none() && spec(&s, id).series_columns.is_empty());
|
||||
// Marker takes them too.
|
||||
let line = graph(&mut s, "line");
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
s.execute("graph.marker", &json!({"design": "Coin", "library": lib})).unwrap();
|
||||
assert_eq!(spec(&s, line).series_markers, [Some("Coin".to_string()), Some("Coin".to_string())]);
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
|
||||
// An unknown library or design, and a library that is not a string, are refused.
|
||||
for p in [json!({"design": "Coin", "library": "Nope"}), json!({"design": "Nope", "library": lib}), json!({"design": "Coin", "library": 3})] {
|
||||
assert!(s.execute("graph.column", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_design_applied_to_a_moved_graph_that_names_it_keeps_the_graph_in_place() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
// A library's name works in any case, as swatch library names do.
|
||||
assert_eq!(s.execute("graph.design", &json!({"library": "COINS"})).unwrap(), json!({"designs": ["Coin"]}));
|
||||
for (kind, cmd) in [("line", "graph.marker"), ("column", "graph.column")] {
|
||||
// The graph names design "Coin", which the document no longer has, and is moved after.
|
||||
save_design(&mut s, "Coin");
|
||||
let id = graph(&mut s, kind);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute(cmd, &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
let rect = spec(&s, id).rect;
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap();
|
||||
s.execute(cmd, &json!({"id": id.0, "design": "Coin", "library": lib})).unwrap();
|
||||
let now = spec(&s, id).rect;
|
||||
assert!((now.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (now.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{cmd}: {now:?}");
|
||||
assert!((now.width() - rect.width()).abs() < 1e-6 && (now.height() - rect.height()).abs() < 1e-6, "{cmd}: {now:?}");
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_the_document_has_under_the_same_name_stays_as_it_is() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
|
||||
assert_eq!(s.execute("graph.design", &json!({"library": lib})).unwrap(), json!({"designs": ["Coin"]}));
|
||||
let steps = undo_len(&s);
|
||||
let r = s.execute("graph.design", &json!({"library": lib, "add": ["Coin", "Coin"]})).unwrap();
|
||||
assert_eq!(r, json!({"added": [], "existing": ["Coin"]}));
|
||||
assert_eq!(undo_len(&s), steps, "nothing changed: no undo step");
|
||||
// Applying it with the library draws with the document's own design.
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
|
||||
assert!(d.swatch("Gold").is_none());
|
||||
assert!(s.execute("graph.design", &json!({"add": "Coin"})).is_err(), "no library");
|
||||
assert!(s.execute("graph.design", &json!({"library": lib, "add": "Nope"})).is_err());
|
||||
assert!(s.execute("graph.design", &json!({"library": lib, "add": 4})).is_err());
|
||||
// The document without it takes it as one undo step.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let r = s.execute("graph.design", &json!({"library": "Coins", "add": "Coin"})).unwrap();
|
||||
assert_eq!(r, json!({"added": ["Coin"], "existing": []}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.graph_designs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_brings_the_designs_its_series_draw_with() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
|
||||
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold") && d.swatch("Gold").is_some());
|
||||
// A data edit redraws the pasted graph with the design.
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
s.execute("graph.setData", &json!({"id": pasted.0, "csv": ",A\nQ1,4\nQ2,6"})).unwrap();
|
||||
assert!(paints_with_swatch(series(s.doc().unwrap().doc.node(pasted).unwrap(), 0), "Gold"));
|
||||
// A document with its own design of that name keeps it.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
|
||||
// The pasted graph is drawn with that design straight away.
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
// The document's design is a rectangle and an ellipse, the pasted one a rectangle alone: each
|
||||
// column and the legend swatch hold two paths.
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_the_document_keeps_brings_none_of_the_pasted_designs_resources() {
|
||||
// A column graph whose spec names marker design "Coin", which only line series draw: the
|
||||
// graph's own art does not use the design's swatch.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
|
||||
assert!(spec(&s, id).series_markers.iter().any(|m| m.as_deref() == Some("Coin")));
|
||||
assert!(!paints_with_swatch(s.doc().unwrap().doc.node(id).unwrap(), "Gold"));
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A document with its own "Coin" keeps it and takes nothing the pasted design's art uses.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_none());
|
||||
// A document without one takes the design and its swatch.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_naming_a_deleted_design_draws_with_the_documents_design_of_that_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
assert!(spec(&s, id).series_columns.iter().flatten().any(|c| c.design == "Coin"), "the graph still names it");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_comes_in_renamed() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff0000", "global": true})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [r]})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
// An edit of the graph's art that drawing the graph again would not keep.
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// A copy of the document holds the same design; its "Ink" is another color, so the pasted
|
||||
// rectangle's swatch takes the document's color, or with "add" comes in renamed.
|
||||
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
|
||||
s.execute("select.set", &json!({"ids": [id.0, r]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "color": "#0000ff"})).unwrap();
|
||||
for conflict in ["merge", "add"] {
|
||||
let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
|
||||
let ink_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Ink"));
|
||||
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
|
||||
assert_eq!((r["merged"].clone(), ink_renamed), expected, "{conflict}: {r}");
|
||||
let st = s.doc().unwrap();
|
||||
let d = &st.doc;
|
||||
let pasted = st.selection.objects.iter().copied().find(|i| d.node(*i).is_some_and(|n| n.extras().graph.is_some())).unwrap();
|
||||
let names: Vec<Option<String>> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
|
||||
assert_eq!(names[0].as_deref(), Some("Mine"), "{conflict}: not drawn again: {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_is_drawn_again_when_its_designs_svg_filter_comes_in_under_another_name() {
|
||||
const SHIFT: &str = r#"<filter id="Shift"><feOffset dx="3" dy="3"/></filter>"#;
|
||||
const SHIFT_MORE: &str = r#"<filter id="Shift"><feOffset dx="9" dy="9"/></filter>"#;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("svgFilter.apply", &json!({"name": "Shift", "ids": [r]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "Coin"})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// A copy of the document holds the same design, but its "Shift" filter draws otherwise, so the
|
||||
// pasted graph's filter keeps its own definition under another name.
|
||||
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap();
|
||||
s.execute("svgFilter.define", &json!({"xml": SHIFT_MORE, "replace": "Shift"})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let pasted = st.selection.objects.to_vec()[0];
|
||||
let names: Vec<Option<String>> = series(st.doc.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
|
||||
assert_ne!(names[0].as_deref(), Some("Mine"), "drawn again with the document's design: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_that_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A document whose "Coin" is a rectangle and an ellipse: the symbol's graph draws with it.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
|
||||
let mut graphs = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let columns: Vec<usize> = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
// A graph that names "Coin", which the document no longer has, kept as a symbol's art.
|
||||
save_design(&mut s, "Coin");
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Chart").unwrap().art;
|
||||
let mut graphs = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_brought_in_from_a_library_leaves_a_scatter_graph_that_names_it_for_a_slot_it_does_not_plot() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
// Four data columns plot two series, so marker slot 2 is never drawn.
|
||||
let id = make(&mut s, "scatter", ",y1,x1,y2,x2\nP,1,10,2,20\nQ,3,11,4,22");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(spec(&s, id).mark_points, "Mark Data Points is on");
|
||||
s.execute("graph.marker", &json!({"design": "Coin", "library": lib, "seriesIndexes": [2]})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_markers.get(2).cloned().flatten().as_deref(), Some("Coin"));
|
||||
// An edit of the graph's art that drawing the graph again would not keep.
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
|
||||
let names: Vec<Option<String>> = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
|
||||
assert_eq!(names[0].as_deref(), Some("Mine"), "not drawn again: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_a_library_design_brings_draws_its_graph_with_the_documents_design_it_keeps() {
|
||||
// The library's design "A" holds an instance of symbol "Chart", whose graph draws columns with
|
||||
// the library's "B": a rectangle and an ellipse.
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut src, "B");
|
||||
let id = graph(&mut src, "column");
|
||||
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
src.execute("graph.column", &json!({"design": "B"})).unwrap();
|
||||
let instance = src.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "A"})).unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let mut s = Session::new();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Lib.vectorcraft"});
|
||||
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
|
||||
// The document's own "B" is a single rectangle, and stays.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "B"})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "A"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graph_designs.len(), 2, "A came in and B stayed");
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
|
||||
let mut graphs = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let columns: Vec<usize> = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [1, 1, 1, 1], "drawn with the document's B");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_brought_in_from_a_library_redraws_a_graph_in_an_opacity_mask() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
|
||||
let mut graphs = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(s.doc().unwrap().doc.node(NodeId(r)).unwrap(), &mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_drops_its_changes_to_graph_parts_a_design_change_redraws() {
|
||||
use vectorcraft_doc::symbol_overrides::SymbolOverride;
|
||||
let mut s = Session::new();
|
||||
let lib = load_coin_library(&mut s);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap();
|
||||
let instance = NodeId(instance);
|
||||
// A change to the graph itself, and one to a part of it that drawing it again replaces.
|
||||
let changes = vec![
|
||||
SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() },
|
||||
SymbolOverride { path: vec![0], opacity: Some(0.25), ..Default::default() },
|
||||
];
|
||||
s.edit("Change", |d, _| {
|
||||
if let Some(n) = d.node_mut(instance) {
|
||||
n.extras_mut().symbol_overrides = changes;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
|
||||
let kept = s.doc().unwrap().doc.node(instance).unwrap().extras().symbol_overrides.clone();
|
||||
assert_eq!(kept.iter().map(|o| o.path.clone()).collect::<Vec<_>>(), [Vec::<u32>::new()], "{kept:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_in_an_opacity_mask_draws_with_the_documents_design_when_pasted() {
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let mask_graph = |n: &vectorcraft_doc::Node| {
|
||||
let mut graphs = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
graphs.into_iter().next().expect("the masked graph")
|
||||
};
|
||||
// In a symbol's art and among the pasted objects.
|
||||
for in_symbol in [true, false] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let copied = if in_symbol { s.execute("symbol.new", &json!({"name": "Masked", "ids": [r]})).unwrap()["id"].as_u64().unwrap() } else { r };
|
||||
s.execute("select.set", &json!({"ids": [copied]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let g = if in_symbol {
|
||||
mask_graph(&st.doc.symbols.iter().find(|x| x.name == "Masked").expect("the symbol came in").art)
|
||||
} else {
|
||||
mask_graph(st.doc.node(st.selection.objects.to_vec()[0]).unwrap())
|
||||
};
|
||||
let columns: Vec<usize> = series(&g, 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "in a symbol: {in_symbol}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// Made again under the same name as a rectangle and an ellipse.
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the design the document has now");
|
||||
}
|
||||
|
||||
/// The graphs in `n`'s subtree, those in opacity-mask art included.
|
||||
fn graphs_in(n: &vectorcraft_doc::Node) -> Vec<vectorcraft_doc::Node> {
|
||||
let mut graphs = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
graphs
|
||||
}
|
||||
|
||||
/// Load a saved document holding [`save_coin_design`]'s "Coin" and design "Chart", an instance of
|
||||
/// symbol "Plot" whose column graph names "Coin" as its columns (`columns`) or only as a marker
|
||||
/// its columns do not draw, as a swatch library → its id.
|
||||
fn load_chart_library(s: &mut Session, columns: bool) -> String {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut src);
|
||||
let id = graph(&mut src, "column");
|
||||
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
src.execute(if columns { "graph.column" } else { "graph.marker" }, &json!({"design": "Coin"})).unwrap();
|
||||
let instance = src.execute("symbol.new", &json!({"name": "Plot", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "Chart"})).unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Charts.vectorcraft"});
|
||||
s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_design_brings_none_of_the_resources_of_a_design_the_document_keeps() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_chart_library(&mut s, false);
|
||||
// The document keeps its own "Coin": nothing the library's "Coin" uses comes in.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.symbols.iter().any(|x| x.name == "Plot"), "the design's symbol came in");
|
||||
assert!(d.swatch("Gold").is_none());
|
||||
// A document without one takes the design and its swatch.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.iter().any(|x| x.name == "Coin") && d.swatch("Gold").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_a_library_design_brings_along_redraws_the_graphs_that_name_it() {
|
||||
let mut s = Session::new();
|
||||
let lib = load_chart_library(&mut s, true);
|
||||
// A graph that names "Coin", which the document no longer has.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
let r = s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
|
||||
assert_eq!(r, json!({"added": ["Chart"], "existing": []}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "drawn with the library's Coin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_that_adds_a_design_redraws_the_documents_graphs_that_name_it_and_not_the_pasted_ones() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
// An edit of the copied graph's art that drawing it again would not keep.
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A document whose graph names "Coin", which it no longer has.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let own = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert!(paints_with_swatch(series(st.doc.node(own).unwrap(), 0), "Gold"), "drawn with the pasted Coin");
|
||||
let pasted = st.selection.objects.to_vec()[0];
|
||||
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
|
||||
assert_eq!(first.as_deref(), Some("Mine"), "the pasted graph is not drawn again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_that_adds_a_marker_design_a_graph_does_not_show_leaves_that_graph_as_it_is() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A line graph whose series name "Coin", which the document no longer has, as a marker that
|
||||
// Mark Data Points does not show, with no legend or with a legend that has no entry for them.
|
||||
for (legend, csv) in [(false, ",2024,2025\nQ1,3,2\nQ2,5,4"), (true, ",,\nQ1,3,2\nQ2,5,4")] {
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let p = json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv});
|
||||
let own = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
|
||||
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("graph.setType", &json!({"id": own.0, "markPoints": false, "legend": legend})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
|
||||
let mark = series(s.doc().unwrap().doc.node(own).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.iter().any(|x| x.name == "Coin"), "legend {legend}: the paste added Coin");
|
||||
let first = series(d.node(own).unwrap(), 0).children().unwrap()[0].name.clone();
|
||||
assert_eq!(first.as_deref(), Some("Mine"), "legend {legend}: not drawn again");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_pasted_twice_with_a_graph_the_document_draws_again_is_added_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// A document whose "Coin" is other art: the first paste draws the symbol's graph with it.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
// The paths of each column of the symbol's graph: 2 for the document's Coin, 1 for the copied one.
|
||||
let columns = |s: &Session| {
|
||||
let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone();
|
||||
let graph = graphs_in(&art).remove(0);
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
series(&graph, 0).children().unwrap().iter().map(|n| paths(n)).collect::<Vec<usize>>()
|
||||
};
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(columns(&s), [2, 2, 2, 2], "the first paste draws with the document's Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
|
||||
assert_eq!(names, ["Chart"]);
|
||||
assert_eq!(columns(&s), [2, 2, 2, 2], "drawn with the document's Coin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_pasted_twice_whose_designs_swatch_takes_the_documents_color_is_added_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
// A copy of the document holds the same "Coin"; its "Gold" is another color.
|
||||
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
for conflict in ["merge", "add"] {
|
||||
s.execute("document.open", &json!({"name": format!("{conflict}.vectorcraft"), "dataBase64": saved})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Gold", "color": "#0000ff"})).unwrap();
|
||||
let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
|
||||
let gold_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Gold"));
|
||||
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
|
||||
assert_eq!((r["merged"].clone(), gold_renamed), expected, "{conflict}: {r}");
|
||||
s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
|
||||
assert_eq!(names, ["Chart"], "{conflict}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_graph_that_only_names_a_kept_design_as_an_undrawn_marker_keeps_its_art() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
// A column graph whose series name "Coin" as a marker, which columns do not draw.
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
|
||||
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.edit("Name", |d, _| {
|
||||
if let Some(n) = d.node_mut(mark) {
|
||||
n.name = Some("Mine".into());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let pasted = st.selection.objects.to_vec()[0];
|
||||
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
|
||||
assert_eq!(first.as_deref(), Some("Mine"), "not drawn again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_design_renames_it_in_the_graphs_of_symbols_and_opacity_masks() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut s);
|
||||
let in_symbol = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [in_symbol.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol.0]})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
let masked = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let before = graphs_in(&s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
|
||||
s.execute("graph.design", &json!({"rename": "Coin", "to": "Medal"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let symbol = graphs_in(&d.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
|
||||
let mask = graphs_in(d.node(NodeId(r)).unwrap());
|
||||
for (where_, g) in [("symbol", &symbol[0]), ("mask", &mask[0])] {
|
||||
let designs: Vec<String> = g.extras().graph.as_deref().unwrap().series_columns.iter().flatten().map(|c| c.design.clone()).collect();
|
||||
assert!(!designs.is_empty() && designs.iter().all(|n| n == "Medal"), "{where_}: {designs:?}");
|
||||
}
|
||||
assert_eq!(symbol[0].children(), before[0].children(), "the symbol's graph keeps its art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_only_a_graph_in_a_symbol_or_a_mask_draws_with_is_not_unused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
save_design(&mut s, "Pill");
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
let masked = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
|
||||
s.execute("graph.column", &json!({"design": "Pill"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("graph.design", &json!({})).unwrap()["unused"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_copied_to_user_defined_keeps_its_graph_designs_under_the_loaded_id() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-user");
|
||||
let mut s = Session::new();
|
||||
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let loaded = load_coin_library(&mut s);
|
||||
// The User Defined copy is a swatch file: it holds the swatches alone.
|
||||
let copy = s.execute("swatch.library.copyToUser", &json!({"library": loaded})).unwrap()["library"].as_str().unwrap().to_string();
|
||||
assert_ne!(copy, loaded);
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let libraries = s.execute("graph.design", &json!({})).unwrap()["libraries"].clone();
|
||||
assert_eq!(libraries, json!([{"library": loaded, "name": libraries[0]["name"], "designs": ["Coin"]}]));
|
||||
assert_eq!(s.execute("graph.design", &json!({"library": loaded})).unwrap(), json!({"designs": ["Coin"]}));
|
||||
assert!(s.execute("graph.design", &json!({"library": copy})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-size");
|
||||
let path = dir.join("big.vectorcraft");
|
||||
let f = std::fs::File::create(&path).unwrap();
|
||||
f.set_len(((256 << 20) + 1) as u64).unwrap();
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("swatch.library.load", &json!({"path": path})).unwrap_err().to_string();
|
||||
assert!(e.contains("larger than 256 MB"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_with_graph_designs_and_no_swatches_loads_for_its_designs() {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut src, "Pill");
|
||||
let mut d = (*src.doc().unwrap().doc).clone();
|
||||
d.swatches.clear();
|
||||
d.swatch_groups.clear();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Pills.vectorcraft"});
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("swatch.library.load", &p).unwrap();
|
||||
assert_eq!((r["count"].clone(), r["graphDesigns"].clone()), (json!(0), json!(1)));
|
||||
// Without graph designs it has nothing to offer.
|
||||
d.graph_designs.clear();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Bare.vectorcraft"});
|
||||
let e = s.execute("swatch.library.load", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("has no swatches of its own"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
// A default swatch the source made global and gave another color, used by a design.
|
||||
let name = src.doc().unwrap().doc.swatches.iter().find(|w| !w.name.starts_with('[')).unwrap().name.clone();
|
||||
let mine = Paint::solid(vectorcraft_color::Color::rgb(0.1, 0.7, 0.3));
|
||||
let (n, p) = (name.clone(), mine.clone());
|
||||
src.edit("Change", move |d, _| {
|
||||
if let Some(w) = d.swatches.iter_mut().find(|w| w.name == n) {
|
||||
w.paint = p;
|
||||
w.global = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("paint.setFill", &json!({"swatch": name, "ids": [r]})).unwrap();
|
||||
src.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "Green"})).unwrap();
|
||||
let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap();
|
||||
let named: Vec<_> = lib.swatches.iter().filter(|w| w.name == name).collect();
|
||||
assert_eq!(named.len(), 1, "one swatch named {name}");
|
||||
assert_eq!(named[0].paint, mine);
|
||||
// And one named like a swatch in a default group.
|
||||
let grouped = src.doc().unwrap().doc.swatch_groups.iter().flat_map(|g| g.swatches.iter()).next().unwrap().name.clone();
|
||||
let (n, p) = (grouped.clone(), mine.clone());
|
||||
src.edit("Change", move |d, _| {
|
||||
if let Some(w) = d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut()).find(|w| w.name == n) {
|
||||
w.paint = p;
|
||||
w.global = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = src.execute("shape.rectangle", &json!({"x": 650, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("paint.setFill", &json!({"swatch": grouped, "ids": [r]})).unwrap();
|
||||
src.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "Grouped"})).unwrap();
|
||||
let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap();
|
||||
let all: Vec<_> = lib.swatches.iter().chain(lib.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter(|w| w.name == grouped).collect();
|
||||
assert_eq!(all.len(), 1, "one swatch named {grouped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() {
|
||||
// With a limit of 3 bytes: text and base64 of 3 bytes pass, and of 4 bytes are refused.
|
||||
let too_big = |p: serde_json::Value| crate::cmd::swatchlib::library_too_big(&p, "swatch.library.load", 3).unwrap();
|
||||
assert!(!too_big(json!({"data": "abc"})));
|
||||
assert!(too_big(json!({"data": "abcd"})));
|
||||
let b64 = |n: usize| vectorcraft_format::base64_encode(&vec![7u8; n]);
|
||||
assert!(!too_big(json!({"dataBase64": b64(3)})));
|
||||
assert!(too_big(json!({"dataBase64": b64(4)})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_library_file_is_read_no_further_than_the_size_limit() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-bound");
|
||||
let path = dir.join("grown.gpl");
|
||||
std::fs::write(&path, [b'a'; 9]).unwrap();
|
||||
let mut s = Session::new();
|
||||
let p = json!({"path": path});
|
||||
let parsed = |_: &[u8], _: &str| Err(crate::EngineError::Other("parsed".into()));
|
||||
// A file that grew past the limit after the size check is refused when it is read.
|
||||
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(8), parsed).unwrap_err().to_string();
|
||||
assert!(e.contains("larger than"), "{e}");
|
||||
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(9), parsed).unwrap_err().to_string();
|
||||
assert!(e.contains("parsed"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_the_head_of_a_swatch_library_file_stops_at_the_limit() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-head");
|
||||
let path = dir.join("long.gpl");
|
||||
std::fs::write(&path, vec![b'a'; 1 << 20]).unwrap();
|
||||
// The read the limit check relies on returns the bytes up to one past the limit, not the file.
|
||||
let head = crate::cmd::fileio::read_file_head(&path.to_string_lossy(), 9).unwrap();
|
||||
assert_eq!(head.len(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_design_brings_its_symbols_with_their_symbol_options() {
|
||||
// The source design is an instance of symbol "Corner" with 9-slice scaling, a top-left
|
||||
// registration point and the Graphic export type.
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap();
|
||||
src.execute("select.all", &json!({})).unwrap();
|
||||
let opts = json!({"name": "Corner", "nineSlice": true, "registration": 0, "exportType": "graphic"});
|
||||
let inst = src.execute("symbol.new", &opts).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("select.set", &json!({"ids": [inst]})).unwrap();
|
||||
src.execute("graph.design", &json!({"new": "Corner Mark"})).unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
|
||||
let mut s = Session::new();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Corners.vectorcraft"});
|
||||
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
s.execute("graph.design", &json!({"library": lib, "add": "Corner Mark"})).unwrap();
|
||||
let (from, to) = (&src.doc().unwrap().doc, &s.doc().unwrap().doc);
|
||||
assert!(from.symbol_nine_slice("Corner").is_some());
|
||||
assert_eq!(to.symbol_nine_slice("Corner"), from.symbol_nine_slice("Corner"));
|
||||
assert_eq!(to.symbol_registration("Corner"), from.symbol_registration("Corner"));
|
||||
assert_eq!(to.symbol_export_type("Corner"), from.symbol_export_type("Corner"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designs_and_markers_survive_save_and_open() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -1211,6 +1211,16 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// Distorted image `im` shows the file read for `link` (`img`) and keeps its corners and its
|
||||
/// clipping: the new pixels fill them. Its transform is scaled to the new pixel size, so a reader
|
||||
/// that places it by the transform still gives it its old size.
|
||||
fn refill_distorted(im: &mut ImageObject, link: &LinkInfo, img: &RasterImage) {
|
||||
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
|
||||
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
|
||||
}
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
|
||||
}
|
||||
|
||||
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
|
||||
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
|
||||
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
|
||||
@@ -1235,7 +1245,12 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
let distorted = n.is_distorted_image();
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
if distorted {
|
||||
refill_distorted(im, &link, &img);
|
||||
return (n, clip);
|
||||
}
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
let (old_pt, old_clip) = match old.get(&im.key) {
|
||||
@@ -1251,6 +1266,14 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
|
||||
}
|
||||
for id in ids {
|
||||
if d.node(*id).is_some_and(Node::is_distorted_image) {
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::Image(im) = &mut n.kind
|
||||
{
|
||||
refill_distorted(im, &link, &img);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(NodeKind::Image(im)) = d.node(*id).map(|n| &n.kind) else { continue };
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
@@ -2068,6 +2091,9 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
// Whether the images were found as the missing links (nothing selected, a folder given) rather
|
||||
// than named or selected.
|
||||
let mut found_missing = false;
|
||||
let mut ids: Vec<NodeId> = match (&each, ids_param(p, "ids", C)?) {
|
||||
(Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(),
|
||||
(None, Some(ids)) => ids,
|
||||
@@ -2075,6 +2101,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selected: Vec<NodeId> = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect();
|
||||
match folder_param {
|
||||
Some(_) if selected.is_empty() => {
|
||||
found_missing = true;
|
||||
groups(&st.doc, None).into_iter().filter(|g| probe(g, LinkBase::of(st)).0 == Status::Missing).flat_map(|g| g.ids).collect()
|
||||
}
|
||||
_ => selected,
|
||||
@@ -2087,6 +2114,11 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the images to relink, or pass ids"));
|
||||
}
|
||||
// A named or selected distorted image is refused before a folder is searched, whether or not
|
||||
// its file is found there.
|
||||
if !found_missing && let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// All Instances: the other stored objects linked to the same files, each once.
|
||||
if scope == Scope::All {
|
||||
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
|
||||
@@ -2131,6 +2163,11 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
(None, None, None) => return Err(bad(C, "give path (a file) or folder")),
|
||||
}
|
||||
// A new file's placement options place a plain image: a distorted one is left as it is.
|
||||
let distorted = files.iter().flat_map(|(ids, _)| ids).find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image));
|
||||
if let Some(id) = distorted {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// Every file is read and checked before any is copied.
|
||||
let mut checked = vec![];
|
||||
for (ids, path) in files {
|
||||
@@ -2593,6 +2630,9 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the linked images or placed documents, or pass ids"));
|
||||
}
|
||||
if let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// A DCS file's plates print from its file.
|
||||
let separated = |id: &NodeId| match kind(id) {
|
||||
Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated),
|
||||
@@ -2721,6 +2761,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if im.link.is_some() {
|
||||
return Err(bad(C, format!("image {} is linked already", id.0)));
|
||||
}
|
||||
if n.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
|
||||
let stored = stored_extension(blob);
|
||||
@@ -2772,6 +2815,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
if n.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
embedded.push((id, n.display_name(), blob));
|
||||
}
|
||||
@@ -2984,7 +3030,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (px, py) = file_pt(&st.doc, &im.key);
|
||||
out["effectivePpi"] = out["ppi"].take();
|
||||
out["ppi"] = json!([72.0 / px, 72.0 / py]);
|
||||
(out["scale"], out["rotation"]) = scale_rotation(im.xf, (px, py));
|
||||
// A distorted image is measured at its middle, as its effective resolution is.
|
||||
let xf = stored(&doc, id).and_then(vectorcraft_doc::image_quad::nearest_affine).unwrap_or(im.xf);
|
||||
(out["scale"], out["rotation"]) = scale_rotation(xf, (px, py));
|
||||
out["format"] = json!(format_label(&st.doc, im));
|
||||
out["placement"] = placement_json(im.placement);
|
||||
out["status"] = json!("embedded");
|
||||
|
||||
@@ -244,12 +244,22 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_) => return Err(bad(C, "handle must be in or out")),
|
||||
};
|
||||
let independent = switch_or(p, "independent", false, C)?;
|
||||
let symmetric = switch_or(p, "symmetric", false, C)?;
|
||||
let link = switch_or(p, "link", false, C)?;
|
||||
let with = spine_points_param(p, C)?;
|
||||
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
|
||||
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "`with` moves points, not a handle"));
|
||||
}
|
||||
if symmetric && independent {
|
||||
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
|
||||
}
|
||||
if symmetric && handle.is_none() {
|
||||
return Err(bad(C, "`symmetric` places a handle: give `handle`"));
|
||||
}
|
||||
if link && symmetric {
|
||||
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
|
||||
}
|
||||
if link && independent {
|
||||
return Err(bad(C, "`link` and `independent` cannot both be true"));
|
||||
}
|
||||
@@ -264,6 +274,8 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
|
||||
let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out));
|
||||
// At an open end of the spine the handle moves as it would without `symmetric`.
|
||||
let symmetric = symmetric && pull_out;
|
||||
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
|
||||
if let Some(out) = handle {
|
||||
if link {
|
||||
@@ -271,6 +283,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
a.set_handle(out, q, independent);
|
||||
}
|
||||
if symmetric {
|
||||
let opposite = a.p - (q - a.p);
|
||||
if out { a.h_in = opposite } else { a.h_out = opposite }
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let delta = q - a.p;
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Spine Point",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
|
||||
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, except at an open end of the spine; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `symmetric` and `link` need `handle`, `symmetric` cannot go with `independent`, and `link` cannot go with `independent` or `symmetric`; all default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
|
||||
has_doc,
|
||||
spine_move_anchor
|
||||
),
|
||||
|
||||
@@ -25,14 +25,23 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let (rows, cols) = if at.is_some() { (1, 1) } else { (rows, cols) };
|
||||
let roots = roots_param(s, p)?;
|
||||
// The distorted images left as they are, each with why.
|
||||
let mut distorted = vec![];
|
||||
let (ids, index) = s.edit("Create Gradient Mesh", |d, sel| {
|
||||
let mut out = vec![];
|
||||
let mut index = None;
|
||||
let mut refused = None;
|
||||
let model = d.color_mode.model();
|
||||
distorted.clear();
|
||||
for id in &roots {
|
||||
let Some(n) = d.node(*id).cloned() else { continue };
|
||||
let m = if let NodeKind::Image(im) = &n.kind {
|
||||
if n.is_distorted_image() {
|
||||
let e = super::super::xform::distorted_image_error(C, *id);
|
||||
distorted.push(json!({"id": id.0, "reason": e.to_string()}));
|
||||
refused.get_or_insert(e);
|
||||
continue;
|
||||
}
|
||||
// An embedded image: the points take the picture's colours there.
|
||||
match image_mesh(d, im, rows, cols) {
|
||||
Ok(mut m) => {
|
||||
@@ -40,7 +49,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(m)
|
||||
}
|
||||
Err(why) => {
|
||||
refused.get_or_insert(why);
|
||||
refused.get_or_insert_with(|| bad(C, why));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -60,7 +69,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match m.add_lines_at(q, tol) {
|
||||
Some(i) => index = Some(i),
|
||||
None => {
|
||||
refused.get_or_insert("point is outside the object");
|
||||
refused.get_or_insert_with(|| bad(C, "point is outside the object"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -75,7 +84,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
out.push(*id);
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(bad(C, refused.unwrap_or("select a path, a compound path or an embedded image")));
|
||||
return Err(refused.unwrap_or_else(|| bad(C, "select a path, a compound path or an embedded image")));
|
||||
}
|
||||
sel.set(out.iter().copied());
|
||||
Ok((out, index))
|
||||
@@ -84,6 +93,9 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(i) = index {
|
||||
r["index"] = json!(i);
|
||||
}
|
||||
if !distorted.is_empty() {
|
||||
r["skipped"] = json!(distorted);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
|
||||
@@ -998,6 +998,9 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result<MosaicPlan> {
|
||||
.ok_or_else(|| bad(C, "select an image"))?;
|
||||
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
if node.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) {
|
||||
return Err(bad(C, "the image has no embedded pixels"));
|
||||
}
|
||||
@@ -1285,6 +1288,9 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.ok_or_else(|| bad(C, "select an image"))?;
|
||||
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
if node.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
if switch_or(p, "trim", false, C)? {
|
||||
if p.get("ppi").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi"));
|
||||
@@ -1495,11 +1501,16 @@ fn mask_image(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
.selection
|
||||
.objects
|
||||
.iter()
|
||||
.find_map(|id| match st.doc.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Image(im)) => {
|
||||
Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf)))
|
||||
.find_map(|id| {
|
||||
let n = st.doc.node(*id)?;
|
||||
match &n.kind {
|
||||
// A distorted image's outline joins its corners.
|
||||
NodeKind::Image(_) if n.is_distorted_image() => Some((*id, PathData::from_bezpath(&n.image_frame()?))),
|
||||
NodeKind::Image(im) => {
|
||||
Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| bad("object.maskImage", "select an image"))?;
|
||||
let (gid, pid) = s.edit("Mask", |d, sel| {
|
||||
|
||||
@@ -209,7 +209,7 @@ impl Session {
|
||||
/// the first selected object (so the last selection's once nothing is selected). Not while the
|
||||
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with.
|
||||
pub(crate) fn inherit_new_art(&mut self) {
|
||||
if self.prefs.new_art_basic || self.tool_id() == super::paint::LIVE_PAINT_BUCKET {
|
||||
if self.prefs.new_art_basic || self.bucket_paints() {
|
||||
return;
|
||||
}
|
||||
let Some(st) = self.active() else { return };
|
||||
|
||||
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -124,7 +124,7 @@ fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<Live
|
||||
}
|
||||
|
||||
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
|
||||
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
|
||||
let items = match p.get("items").filter(|v| !v.is_null()) {
|
||||
@@ -235,6 +235,13 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When every value given is the current one, the document and its undo history stay as they
|
||||
// are.
|
||||
let st = s.doc()?;
|
||||
// `rectanglesOnly`: the live rectangles among the targets; the other objects stay as they are.
|
||||
let ids: Vec<NodeId> = if p.get("rectanglesOnly").and_then(Value::as_bool) == Some(true) {
|
||||
let rectangle = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Path { live: Some(l), .. }) if matches!(**l, LiveShape::Rectangle { .. }));
|
||||
ids.into_iter().filter(rectangle).collect()
|
||||
} else {
|
||||
ids
|
||||
};
|
||||
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
|
||||
// past the document's coordinate limit is an error before anything changes.
|
||||
let mut lines = std::collections::BTreeMap::new();
|
||||
@@ -278,16 +285,23 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let Some(c) = LiveCorners::new(path, live.as_deref()) else { return true };
|
||||
let picked = corners_of(*id).unwrap_or_else(|| c.picked(st.selection.anchors.get(id)));
|
||||
// Setting corners folds a scale left in a rectangle's transform into its size, which
|
||||
// changes it.
|
||||
live.as_deref().is_none_or(|l| l.folded() == *l)
|
||||
// Setting a radius folds a scale left in a rectangle's transform into its size, which
|
||||
// changes it. A kind the corners already have leaves the rectangle as it is.
|
||||
(radius.is_none() || live.as_deref().is_none_or(|l| l.folded() == *l))
|
||||
&& picked.iter().all(|k| {
|
||||
*k < c.base.anchor_count()
|
||||
&& radius.is_none_or(|r| (c.drawn_radius(*k) - r.max(0.0)).abs() < 1e-9)
|
||||
// A radius stored in document units can be larger than it draws; a relative
|
||||
// one is a fraction, so it is compared as drawn.
|
||||
&& radius.is_none_or(|r| {
|
||||
let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) };
|
||||
(now - r.max(0.0)).abs() < 1e-9
|
||||
})
|
||||
&& kind.is_none_or(|kd| c.kind(*k) == kd)
|
||||
})
|
||||
};
|
||||
if ids.iter().all(has_values) {
|
||||
// The objects every value given already matches stay as they are, beside others that change.
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| !has_values(id)).collect();
|
||||
if ids.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Live Shape", |d, sel| {
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Overprint",
|
||||
[],
|
||||
None,
|
||||
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind → {changed: objects}",
|
||||
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
|
||||
has_doc,
|
||||
set_overprint
|
||||
),
|
||||
@@ -135,7 +135,7 @@ fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>
|
||||
.into_iter()
|
||||
.map(|fill| {
|
||||
let it = item.of_kind(s, fill);
|
||||
let ids = it.targets(s, p)?;
|
||||
let ids = it.targets_for(s, p, fill)?;
|
||||
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
|
||||
Ok((fill, it, ids))
|
||||
})
|
||||
|
||||
@@ -203,10 +203,11 @@ impl Session {
|
||||
/// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item
|
||||
/// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With
|
||||
/// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that
|
||||
/// object as the instance draws it. None while the Live Paint Bucket is the active tool: the
|
||||
/// proxies show the colors it paints with.
|
||||
/// object as the instance draws it. None while the Live Paint Bucket is the active tool (or
|
||||
/// another tool works for it, [`Session::bucket_paints`]): the proxies show the colors it
|
||||
/// paints with.
|
||||
pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option<usize>)> {
|
||||
if self.tool_id() == LIVE_PAINT_BUCKET {
|
||||
if self.bucket_paints() {
|
||||
return None;
|
||||
}
|
||||
let st = self.active()?;
|
||||
@@ -215,12 +216,15 @@ impl Session {
|
||||
}
|
||||
let first = st.doc.node(*st.selection.subjects().first()?)?;
|
||||
let item = self.appearance_item();
|
||||
// Only an active Appearance row is shown here: it is a row of the first selected object.
|
||||
if first.appearance.item_of_kind(item, !stroke).is_some() {
|
||||
return Some((Cow::Borrowed(first), item));
|
||||
}
|
||||
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
|
||||
// object without a painted object shows the defaults for new art.
|
||||
for id in st.selection.subjects() {
|
||||
// object without a painted object shows the defaults for new art. A face or edge selected with
|
||||
// its Live Paint group counts with the group, wherever it is in the selection.
|
||||
let covered = live_paint_covered(&st.doc, st.selection.subjects());
|
||||
for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, stroke, &mut nodes);
|
||||
@@ -272,14 +276,6 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the faces and edges of `n` when it is a Live Paint group, else none.
|
||||
pub(crate) fn live_paint_parts(n: &Node) -> Vec<NodeId> {
|
||||
if !is_live_paint(n) {
|
||||
return vec![];
|
||||
}
|
||||
faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect()
|
||||
}
|
||||
|
||||
/// The objects whose paints the proxies show for a selected `n`, the ones the paint commands
|
||||
/// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and
|
||||
/// other containers inside them), a compound path for its parts. A Live Paint group stands for its
|
||||
@@ -330,8 +326,9 @@ impl DocState {
|
||||
// Looking the first object up builds the id cache when there is none.
|
||||
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
|
||||
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
|
||||
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
|
||||
let mut covered = std::collections::HashSet::new();
|
||||
// The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well,
|
||||
// they count with their group's.
|
||||
let covered = live_paint_covered(&self.doc, &self.selection.objects);
|
||||
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
|
||||
// place it appears.
|
||||
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
|
||||
@@ -341,7 +338,6 @@ impl DocState {
|
||||
if covered.contains(&n.id) {
|
||||
continue;
|
||||
}
|
||||
covered.extend(live_paint_parts(n));
|
||||
painted(n, true, false, &mut fills);
|
||||
painted(n, true, true, &mut strokes);
|
||||
}
|
||||
@@ -378,11 +374,28 @@ impl DocState {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the
|
||||
/// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while
|
||||
/// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a
|
||||
/// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the
|
||||
/// sample its click takes before it switches back to the bucket.
|
||||
pub fn bucket_paints(&self) -> bool {
|
||||
let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET);
|
||||
// A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it.
|
||||
self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket)
|
||||
}
|
||||
|
||||
/// The tool the active tool's armed one-shot pick switches back to after its click
|
||||
/// ([`vectorcraft_tools::Tool::returns_to`]).
|
||||
pub fn tool_returns_to(&self) -> Option<String> {
|
||||
self.tool.returns_to().map(str::to_string)
|
||||
}
|
||||
|
||||
/// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item.
|
||||
/// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors.
|
||||
/// Neither is mixed while the Live Paint Bucket is the active tool ([`Session::proxy_source`]).
|
||||
pub fn proxy_mixed(&self) -> (bool, bool) {
|
||||
if self.tool_id() == LIVE_PAINT_BUCKET {
|
||||
if self.bucket_paints() {
|
||||
return (false, false);
|
||||
}
|
||||
self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points()))
|
||||
@@ -737,12 +750,13 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
|
||||
}
|
||||
|
||||
/// Is the Live Paint Bucket the active tool while `p` names no `ids`, `id` or `item`? A fill,
|
||||
/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]) while `p` names no `ids`,
|
||||
/// `id` or `item`? A fill,
|
||||
/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults
|
||||
/// and the selection keeps its paint.
|
||||
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
|
||||
// A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row.
|
||||
s.tool_id() == LIVE_PAINT_BUCKET && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
|
||||
s.bucket_paints() && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
|
||||
}
|
||||
|
||||
/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise.
|
||||
@@ -820,6 +834,36 @@ pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: boo
|
||||
out
|
||||
}
|
||||
|
||||
/// Faces, edges and the other objects (the hidden source paths) of Live Paint groups.
|
||||
pub(crate) type LivePaintParts = (std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>);
|
||||
|
||||
/// The faces, the edges and the hidden source paths of the Live Paint groups in `roots` (or inside them),
|
||||
/// found as [`live_paint_parts_skipped`] finds them.
|
||||
pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts {
|
||||
let groups = live_paint_groups(d, roots);
|
||||
let mut hidden = inside_live_paint(d, &groups);
|
||||
let (mut faces, mut edges) = (std::collections::HashSet::new(), std::collections::HashSet::new());
|
||||
for (_, f, e) in &groups {
|
||||
faces.extend(f.iter().copied());
|
||||
edges.extend(e.iter().copied());
|
||||
}
|
||||
hidden.retain(|id| !faces.contains(id) && !edges.contains(id));
|
||||
(faces, edges, hidden)
|
||||
}
|
||||
|
||||
/// The faces and edges in `selected` whose Live Paint group is selected too, itself or inside another selected
|
||||
/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an
|
||||
/// object in `selected` is inside a Live Paint group.
|
||||
pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint));
|
||||
if !selected.iter().any(inside) {
|
||||
return std::collections::HashSet::new();
|
||||
}
|
||||
let (mut parts, edges, _) = live_paint_split(d, selected);
|
||||
parts.extend(edges);
|
||||
parts
|
||||
}
|
||||
|
||||
/// The instance whose object is selected with Direct Selection, and that object's path
|
||||
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
|
||||
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
|
||||
@@ -1337,7 +1381,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
|
||||
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
|
||||
// no row for) is still an error.
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?;
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?;
|
||||
let of = match item {
|
||||
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
|
||||
ItemTarget::Top => None,
|
||||
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use super::{live_paint_covered, painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use crate::{DocState, Session};
|
||||
|
||||
thread_local! {
|
||||
@@ -39,12 +39,11 @@ fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -
|
||||
}
|
||||
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
|
||||
let mut covered = HashSet::new();
|
||||
let covered = live_paint_covered(&st.doc, &st.selection.objects);
|
||||
st.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
if !covered.contains(&n.id) {
|
||||
covered.extend(live_paint_parts(n));
|
||||
painted(n, true, false, &mut fills);
|
||||
painted(n, true, true, &mut strokes);
|
||||
}
|
||||
|
||||
@@ -516,7 +516,30 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
|
||||
}
|
||||
check_effect_color(id, effect, params)?;
|
||||
check_effect_channel(id, effect, params)?;
|
||||
check_effect_center(id, effect, params)
|
||||
check_effect_center(id, effect, params)?;
|
||||
check_effect_pathfinder(id, effect, params)
|
||||
}
|
||||
|
||||
/// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given
|
||||
/// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and
|
||||
/// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves
|
||||
/// before they edit, as they run [`check_effect_color`].
|
||||
pub(crate) fn check_effect_pathfinder(id: &str, effect: &str, params: &Value) -> Result<()> {
|
||||
use vectorcraft_render::effects;
|
||||
if !effects::takes_pathfinder_options(effect) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(v) = params.get("precision")
|
||||
&& !v.as_f64().is_some_and(|p| effects::PATHFINDER_EFFECT_PRECISION.contains(&p))
|
||||
{
|
||||
return Err(bad(id, "precision must be from 0.001 to 10 pt"));
|
||||
}
|
||||
for key in ["removeRedundantPoints", "removeUnpainted"] {
|
||||
if params.get(key).is_some_and(|v| !v.is_boolean()) {
|
||||
return Err(bad(id, format!("`{key}` must be true or false")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key
|
||||
@@ -557,9 +580,11 @@ fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> {
|
||||
/// A value of the type effect `effect` reads for `key`, a parameter its params description names
|
||||
/// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`,
|
||||
/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number
|
||||
/// and a Gaussian Blur's `linear` is true or false. A Glass, Texturizer or Rough Pastels
|
||||
/// `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of Crop
|
||||
/// Marks have checks of their own; they aren't listed.
|
||||
/// and a Gaussian Blur's `linear` is true or false. A Pathfinder effect's `precision` is a number and
|
||||
/// its `removeRedundantPoints` and `removeUnpainted` are true or false. A Glass, Texturizer or Rough
|
||||
/// Pastels `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version`, the `style` of Crop
|
||||
/// Marks and an Extrude & Bevel's custom `bevelName` and `bevelProfile` have checks of their own;
|
||||
/// they aren't listed.
|
||||
pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
|
||||
use vectorcraft_render::effects;
|
||||
let number = || Some(Value::from(0.0));
|
||||
@@ -568,6 +593,8 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
|
||||
"variation" if effect == "stylize.scribble" => number(),
|
||||
"width" if effect == "path.outlineStroke" => number(),
|
||||
"linear" if effect == "blur.gaussian" => Some(Value::Bool(false)),
|
||||
"precision" if effects::takes_pathfinder_options(effect) => number(),
|
||||
"removeRedundantPoints" | "removeUnpainted" if effects::takes_pathfinder_options(effect) => Some(Value::Bool(false)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false; with link false, at moves the anchor and both handles before placing the chosen handle",
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
|
||||
has_doc,
|
||||
set_handle
|
||||
),
|
||||
@@ -461,6 +461,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return link_handle(s, p, id, si, ai, out, pos);
|
||||
}
|
||||
let independent = switch_or(p, "independent", false, "path.setHandle")?;
|
||||
let symmetric = switch_or(p, "symmetric", false, "path.setHandle")?;
|
||||
if symmetric && independent {
|
||||
return Err(bad("path.setHandle", "`independent` and `symmetric` cannot both be true"));
|
||||
}
|
||||
// The other handle is mirrored only where a segment leaves the anchor on its side: at an open
|
||||
// end the handle moves as it would without `symmetric`.
|
||||
let symmetric = symmetric && has_segment(s, id, si, ai, !out)?;
|
||||
let at = match p.get("at").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?),
|
||||
@@ -472,6 +479,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& at.is_none_or(|to| to == a.p)
|
||||
&& (if out { a.h_out } else { a.h_in }) == pos
|
||||
&& !(independent && a.kind != AnchorKind::Corner)
|
||||
&& (!symmetric || (if out { a.h_in } else { a.h_out }) == a.p - (pos - a.p))
|
||||
{
|
||||
return ok();
|
||||
}
|
||||
@@ -504,6 +512,10 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
a.set_handle(out, pos, independent);
|
||||
}
|
||||
if symmetric {
|
||||
let opposite = a.p - (pos - a.p);
|
||||
if out { a.h_in = opposite } else { a.h_out = opposite }
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
@@ -519,6 +531,9 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
|
||||
if switch_or(p, "independent", false, C)? {
|
||||
return Err(bad(C, "`link` and `independent` cannot both be true"));
|
||||
}
|
||||
if switch_or(p, "symmetric", false, C)? {
|
||||
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
|
||||
}
|
||||
if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
@@ -655,6 +670,16 @@ fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result<Option<Anc
|
||||
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied())
|
||||
}
|
||||
|
||||
/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or
|
||||
/// incoming side; false when the path, subpath or anchor is not there.
|
||||
fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result<bool> {
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out)))
|
||||
}
|
||||
|
||||
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?;
|
||||
let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?;
|
||||
|
||||
@@ -685,14 +685,21 @@ fn pf_label(op: PathfinderOp) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
|
||||
/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
|
||||
fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result<PathfinderOptions> {
|
||||
/// The Pathfinder Options in the preferences, as the panel's operations and a new Pathfinder effect
|
||||
/// take them.
|
||||
pub(crate) fn current_pf_options(s: &Session) -> PathfinderOptions {
|
||||
let mut stored = s.prefs.pathfinder;
|
||||
if !PATHFINDER_PRECISION_RANGE.contains(&stored.precision) {
|
||||
// A preferences file edited by hand: the default, rather than refitting everything away.
|
||||
stored.precision = po::DEFAULT_PRECISION;
|
||||
}
|
||||
stored
|
||||
}
|
||||
|
||||
/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
|
||||
/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
|
||||
fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result<PathfinderOptions> {
|
||||
let stored = current_pf_options(s);
|
||||
let keys = ["precision", "removeRedundantPoints", "removeUnpainted"];
|
||||
let given: serde_json::Map<String, Value> =
|
||||
p.as_object().into_iter().flatten().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
|
||||
@@ -630,19 +630,7 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
|
||||
/// `image_xf`), also for an image alone in a clip group when the new art is an 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 {
|
||||
// An image alone in a clip group (as a PSD or PSB file's clipping path places it,
|
||||
// [`fileio::file_clipped`]) is measured as the image when the new art is an image; a DCS
|
||||
// file's plates are not.
|
||||
let image = match &old.kind {
|
||||
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
|
||||
[path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind {
|
||||
NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image,
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
};
|
||||
let image = replace_measured(d, old, new_image);
|
||||
if image_xf && let NodeKind::Image(im) = &image.kind {
|
||||
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);
|
||||
@@ -655,6 +643,22 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
|
||||
Affine::translate(c - natural.center())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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[..] {
|
||||
[path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind {
|
||||
NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image,
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
}
|
||||
}
|
||||
|
||||
/// `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);
|
||||
@@ -814,6 +818,17 @@ 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.
|
||||
if let Some(o) = old_node
|
||||
&& !is_text
|
||||
{
|
||||
let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
|
||||
if image.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(PLACE, image.id));
|
||||
}
|
||||
}
|
||||
let m = match (old_node, rect) {
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
|
||||
(None, Some(r)) => fit(natural, r),
|
||||
@@ -1173,6 +1188,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = super::links::with_brush_art(&st.doc);
|
||||
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution, taken at the middle of a distorted image.
|
||||
let ppi = effective_ppi(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf));
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
|
||||
let doc_path = super::links::LinkBase::of(st).doc;
|
||||
@@ -1184,7 +1201,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
|
||||
"pixelWidth": im.width,
|
||||
"pixelHeight": im.height,
|
||||
"ppi": effective_ppi(im.xf),
|
||||
"ppi": ppi,
|
||||
"width": size.width(),
|
||||
"height": size.height(),
|
||||
}))
|
||||
|
||||
@@ -153,6 +153,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"color.gamutCheck",
|
||||
"color.harmony",
|
||||
"color.plates",
|
||||
"color.used",
|
||||
"dataset.capture",
|
||||
"dataset.delete",
|
||||
"dataset.list",
|
||||
@@ -746,5 +747,7 @@ pub(super) const DENIED: &[&str] = &[
|
||||
"stroke.arrowheads.edit",
|
||||
"stroke.arrowheads.list",
|
||||
"text.similarFonts",
|
||||
"threeD.bevels.edit",
|
||||
"threeD.bevels.list",
|
||||
"type.compositeFonts.set",
|
||||
];
|
||||
@@ -404,6 +404,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
"Update Links",
|
||||
choice(&[("automatically", "Automatically"), ("manually", "Manually"), ("askWhenModified", "Ask When Modified")])
|
||||
),
|
||||
p!("pdfTextAs", "File Handling", "Files", "PDF Text", choice(&[("text", "Editable"), ("outlines", "Outlines")])),
|
||||
// Clipboard Handling
|
||||
p!("copyAsSvg", "Clipboard Handling", "On Copy", "Include SVG Code", bool),
|
||||
p!("copyAsPdf", "Clipboard Handling", "On Copy", "PDF", bool),
|
||||
@@ -752,6 +753,13 @@ impl Session {
|
||||
t.set_option("cornerRadius", &r);
|
||||
}
|
||||
}
|
||||
// A press of the tool that is dropped keeps the new radius, also when the tool lent a
|
||||
// selection tool for the press.
|
||||
if self.press_taken_by("roundedRectangle")
|
||||
&& let Some((_, saved)) = self.press_options.as_mut()
|
||||
{
|
||||
saved.insert("cornerRadius".into(), r);
|
||||
}
|
||||
}
|
||||
if fonts_folder_changed {
|
||||
let folder = self.prefs.fonts_folder.trim();
|
||||
|
||||
@@ -455,6 +455,10 @@ fn places(map: Affine) -> bool {
|
||||
/// member).
|
||||
pub(crate) fn replace_with_image(mut v: Node, image: Node) -> Node {
|
||||
if !v.is_layer() {
|
||||
// The new pixels already show a distorted image's distortion.
|
||||
if let Some(e) = v.extras_if_any() {
|
||||
e.image_quad = None;
|
||||
}
|
||||
return Node { kind: image.kind, appearance: Default::default(), ..v };
|
||||
}
|
||||
v.appearance = Default::default();
|
||||
|
||||
@@ -29,6 +29,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
colors
|
||||
),
|
||||
cmd!(
|
||||
query "color.used",
|
||||
"Document Colors",
|
||||
[],
|
||||
None,
|
||||
"{selection?: true (false: the objects select.all takes, also while something is selected), limit?: n (only the n most used; default all)} → {colors: [{key, hex, color: the color in its own model ({model, …}), count, swatch?: the global swatch it is linked to (from its first linked use in paint order, a plain use before a gradient stop that mixes the swatch's ink with process inks; left out when only such stops link it), tint?: 0..100 to three decimals (the percent of that swatch's color the same use stores)}] as recolor.colors lists them, selection: true when they are the selection's, uses: the uses of every color, those past limit included} the unique colors of the selection, or with nothing selected or selection false of the objects select.all takes without the hidden and locked objects inside them, most used first; the selection is left as it is",
|
||||
has_doc,
|
||||
used
|
||||
),
|
||||
cmd!(
|
||||
"recolor.apply",
|
||||
"Recolor Artwork",
|
||||
@@ -130,7 +139,8 @@ type Region = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule);
|
||||
#[derive(Clone)]
|
||||
struct ImageRead<'a> {
|
||||
blob: &'a vectorcraft_doc::ImageBlob,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
/// Pixel space to the page: the image's transform, or a distorted image's projective map.
|
||||
map: vectorcraft_geom::Homography,
|
||||
size: (f64, f64),
|
||||
area: Option<Rect>,
|
||||
clip: Option<Vec<Region>>,
|
||||
@@ -261,9 +271,9 @@ impl<'a> Theme<'a> {
|
||||
let keeps: Vec<Box<dyn Fn(f64, f64) -> bool + '_>> = group
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let (xf, (w, h), area, clip, cost, tested) = (r.xf, r.size, r.area, &r.clip, elements(r), &tested);
|
||||
let (map, (w, h), area, clip, cost, tested) = (r.map, r.size, r.area, &r.clip, elements(r), &tested);
|
||||
Box::new(move |u: f64, v: f64| {
|
||||
let p = xf * Point::new(u * w, v * h);
|
||||
let Some(p) = map.apply(Point::new(u * w, v * h)) else { return false };
|
||||
area.is_none_or(|a| a.contains(p))
|
||||
&& clip.as_ref().is_none_or(|rs| {
|
||||
tested.set(tested.get().saturating_add(cost));
|
||||
@@ -278,7 +288,7 @@ impl<'a> Theme<'a> {
|
||||
.map(|(r, keep)| {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let (w, h) = r.size;
|
||||
let inv = r.xf.inverse();
|
||||
let inv = r.map.inverse();
|
||||
// The box sampled: the marquee, cut to the clipping paths' bounds, so a small
|
||||
// region a clip shows of a large image is still sampled densely.
|
||||
let clip_box = r.clip.as_ref().map(|rs| rs.iter().map(|(bp, _)| bp.bounding_box()).reduce(|a, b| a.union(b)).unwrap_or_default());
|
||||
@@ -286,12 +296,16 @@ impl<'a> Theme<'a> {
|
||||
(Some(a), Some(c)) => Some(a.intersect(c)),
|
||||
(a, c) => a.or(c),
|
||||
};
|
||||
let box_uv = region.map(|a| {
|
||||
let uv: Vec<Point> =
|
||||
[(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)].into_iter().map(|(x, y)| inv * Point::new(x, y)).collect();
|
||||
// A region that crosses a distorted image's horizon has no box: the whole
|
||||
// image is sampled, and `keep` tests each pixel.
|
||||
let box_uv = region.zip(inv).and_then(|(a, inv)| {
|
||||
let uv: Vec<Point> = [(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)]
|
||||
.into_iter()
|
||||
.map(|(x, y)| inv.apply(Point::new(x, y)))
|
||||
.collect::<Option<_>>()?;
|
||||
let low = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::INFINITY, f64::min);
|
||||
let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max);
|
||||
[low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h]
|
||||
Some([low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h])
|
||||
});
|
||||
(box_uv, if r.clip.is_some() { clipped } else { budget }, keep.as_ref())
|
||||
})
|
||||
@@ -401,7 +415,9 @@ impl<'a> Theme<'a> {
|
||||
None
|
||||
};
|
||||
let size = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
|
||||
self.queue_image(ImageRead { blob, xf: im.xf, size, area, clip: self.clip.clone(), colorize });
|
||||
// A distorted image's pixels are where its projective map puts them.
|
||||
let map = n.image_map().unwrap_or_else(|| vectorcraft_geom::Homography::from_affine(im.xf));
|
||||
self.queue_image(ImageRead { blob, map, size, area, clip: self.clip.clone(), colorize });
|
||||
return;
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
@@ -945,16 +961,19 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"colors": colors.iter().map(key_str).collect::<Vec<_>>(), "objects": theme.objects}))
|
||||
}
|
||||
|
||||
/// A colour the art uses: how often, and the global swatch it is linked to.
|
||||
/// A color the art uses: how often, and the global swatch of its first linked use in paint order.
|
||||
struct Used {
|
||||
color: Color,
|
||||
count: usize,
|
||||
swatch: Option<String>,
|
||||
/// The global swatch of the first linked use that is not a gradient stop mixing the swatch's
|
||||
/// ink with process inks, with the tint (0..1) its paint stores when the paint gives one.
|
||||
plain: Option<(String, Option<f32>)>,
|
||||
}
|
||||
|
||||
/// The unique colours of the objects `ids` and the objects inside them, most used first (ties by
|
||||
/// key): fills, strokes, gradient stops, text, mesh points and the tiles of the patterns used as
|
||||
/// fills or strokes. With `only`, an object not in it is left out with everything it holds.
|
||||
/// key): fills, strokes, gradient stops, text, mesh points, the tiles of the patterns used as
|
||||
/// fills or strokes, and the tiles of the patterns those tiles use. With `only`, an object not in it is left out with everything it holds.
|
||||
fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) -> Vec<Used> {
|
||||
fn read<'a>(n: &'a Node, only: Option<&BTreeSet<NodeId>>, out: &mut Vec<&'a Node>) {
|
||||
if only.is_some_and(|o| !o.contains(&n.id)) {
|
||||
@@ -967,44 +986,64 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
|
||||
}
|
||||
let mut index: HashMap<ColorKey, usize> = HashMap::new();
|
||||
let mut used: Vec<(ColorKey, Used)> = vec![];
|
||||
let mut count = |c: &Color, link: Option<&str>| {
|
||||
let mut count_tint = |c: &Color, link: Option<&str>, tint: Option<f32>, mixed: bool| {
|
||||
let k = ColorKey::of(c);
|
||||
let i = *index.entry(k).or_insert_with(|| {
|
||||
used.push((k, Used { color: *c, count: 0, swatch: None }));
|
||||
used.push((k, Used { color: *c, count: 0, swatch: None, plain: None }));
|
||||
used.len() - 1
|
||||
});
|
||||
let u = &mut used[i].1;
|
||||
u.count += 1;
|
||||
if u.swatch.is_none() {
|
||||
u.swatch = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())).map(str::to_string);
|
||||
if u.swatch.is_some() && (u.plain.is_some() || mixed) {
|
||||
return;
|
||||
}
|
||||
if let Some(l) = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())) {
|
||||
if u.swatch.is_none() {
|
||||
u.swatch = Some(l.to_string());
|
||||
}
|
||||
if u.plain.is_none() && !mixed {
|
||||
u.plain = Some((l.to_string(), tint));
|
||||
}
|
||||
}
|
||||
};
|
||||
// The patterns used as fills or strokes: their tiles count once each.
|
||||
// The patterns used as fills or strokes, and the patterns their tiles use: each tile counts
|
||||
// once, and a pattern whose tile uses itself, directly or through other patterns, counts once.
|
||||
let mut patterns: Vec<&str> = vec![];
|
||||
let mut nodes = vec![];
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
read(n, only, &mut nodes);
|
||||
}
|
||||
for m in nodes {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())),
|
||||
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| count(&p.color, None));
|
||||
}
|
||||
paints(m, &mut count_tint, &mut patterns);
|
||||
}
|
||||
for def in patterns.iter().filter_map(|p| d.pattern(p)) {
|
||||
def.art.iter().for_each(|n| node_colors(n, &mut count));
|
||||
let mut next = 0;
|
||||
while let Some(&name) = patterns.get(next) {
|
||||
next += 1;
|
||||
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
|
||||
a.walk(&mut |m| paints(m, &mut count_tint, &mut patterns));
|
||||
}
|
||||
}
|
||||
used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0)));
|
||||
used.into_iter().map(|(_, u)| u).collect()
|
||||
}
|
||||
|
||||
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
|
||||
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
|
||||
/// add the patterns it is painted with to `patterns`.
|
||||
fn paints<'a>(m: &'a Node, count: &mut impl FnMut(&Color, Option<&str>, Option<f32>, bool), patterns: &mut Vec<&'a str>) {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, tint } => count(color, swatch.as_deref(), Some(*tint), false),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref(), Some(s.tint), s.plates.is_some())),
|
||||
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| count(&p.color, None, None, false));
|
||||
}
|
||||
}
|
||||
|
||||
/// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the
|
||||
/// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once).
|
||||
fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec<Color> {
|
||||
@@ -1047,30 +1086,61 @@ fn scope_ids(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<NodeId>, Option<B
|
||||
let st = s.doc()?;
|
||||
let ids = match p.get("ids") {
|
||||
Some(_) => checked_ids_param(s, p, "ids", cmd)?,
|
||||
None if st.selection.is_empty() => {
|
||||
let only = super::select::selectable_ids(&st.doc, st.isolation);
|
||||
return Ok((super::select::selectable(&st.doc, st.isolation), Some(only)));
|
||||
}
|
||||
None if st.selection.is_empty() => return Ok(all_art(st)),
|
||||
None => st.selection.objects.clone(),
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
Ok((super::edit::outermost(&st.doc, ids).into_iter().filter(|id| seen.insert(*id)).collect(), None))
|
||||
}
|
||||
|
||||
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
|
||||
let st = s.doc()?;
|
||||
let v: Vec<Value> = used_colors(&st.doc, &ids, only.as_ref())
|
||||
.iter()
|
||||
/// The objects Select All takes, and the objects whose colors count ([`scope_ids`] with nothing
|
||||
/// selected).
|
||||
fn all_art(st: &crate::DocState) -> (Vec<NodeId>, Option<BTreeSet<NodeId>>) {
|
||||
let only = super::select::selectable_ids(&st.doc, st.isolation);
|
||||
(super::select::selectable(&st.doc, st.isolation), Some(only))
|
||||
}
|
||||
|
||||
/// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see
|
||||
/// [`used_colors`]). Each names the swatch of its first linked use. With `with_color`, each has its
|
||||
/// color in its own model, and the swatch and tint come from its first linked use that is not a
|
||||
/// gradient stop mixing the swatch's ink with process inks (none when every linked use is one).
|
||||
fn colors_json(used: &[Used], with_color: bool) -> Vec<Value> {
|
||||
used.iter()
|
||||
.map(|u| {
|
||||
let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count});
|
||||
if let Some(w) = &u.swatch {
|
||||
if with_color {
|
||||
v["color"] = json!(u.color);
|
||||
if let Some((w, tint)) = &u.plain {
|
||||
v["swatch"] = json!(w);
|
||||
if let Some(t) = tint {
|
||||
v["tint"] = json!((f64::from(*t) * 100_000.0).round() / 1000.0);
|
||||
}
|
||||
}
|
||||
} else if let Some(w) = &u.swatch {
|
||||
v["swatch"] = json!(w);
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "colors": v }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
|
||||
let st = s.doc()?;
|
||||
Ok(json!({ "colors": colors_json(&used_colors(&st.doc, &ids, only.as_ref()), false) }))
|
||||
}
|
||||
|
||||
/// `color.used {selection?, limit?}`: the colors of the selection, or of the art Select All takes.
|
||||
fn used(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.used";
|
||||
let limit = super::index_opt(p, "limit", C)?.unwrap_or(usize::MAX);
|
||||
let selection = switch_or(p, "selection", true, C)? && !s.doc()?.selection.is_empty();
|
||||
let (ids, only) = if selection { scope_ids(s, &json!({}), C)? } else { all_art(s.doc()?) };
|
||||
let st = s.doc()?;
|
||||
let used = used_colors(&st.doc, &ids, only.as_ref());
|
||||
let uses: usize = used.iter().map(|u| u.count).sum();
|
||||
let shown = used.get(..limit.min(used.len())).unwrap_or_default();
|
||||
Ok(json!({ "colors": colors_json(shown, true), "selection": selection, "uses": uses }))
|
||||
}
|
||||
|
||||
/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a
|
||||
@@ -2051,7 +2121,14 @@ mod tests {
|
||||
bp.line_to((size, size));
|
||||
bp.line_to((0.0, size));
|
||||
bp.close_path();
|
||||
ImageRead { blob, xf: Affine::IDENTITY, size: (size, size), area: None, clip: Some(vec![(bp, FillRule::NonZero)]), colorize: None }
|
||||
ImageRead {
|
||||
blob,
|
||||
map: vectorcraft_geom::Homography::from_affine(Affine::IDENTITY),
|
||||
size: (size, size),
|
||||
area: None,
|
||||
clip: Some(vec![(bp, FillRule::NonZero)]),
|
||||
colorize: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The reads of one image inside clip groups share the work limit: three reads of a 64 px
|
||||
|
||||
+740
-37
@@ -10,9 +10,11 @@
|
||||
//! path, inside groups too) is compared with the glyphs of the candidate fonts
|
||||
//! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched
|
||||
//! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object
|
||||
//! per line of glyphs, with the first glyph's fill and stroke. Shapes that match no font stay as
|
||||
//! they are and are reported. Near matches (another version of the font, simplified outlines,
|
||||
//! merged glyphs) and images are phase 2.
|
||||
//! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced
|
||||
//! apart takes that spacing as its tracking ([`Line::tracked`]), and lines stacked at one leading
|
||||
//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). Shapes
|
||||
//! that match no font stay as they are and are reported. Near matches (another version of the
|
||||
//! font, simplified outlines, merged glyphs) and images are phase 2.
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
use std::sync::Arc;
|
||||
@@ -39,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Retype",
|
||||
["Type"],
|
||||
None,
|
||||
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
|
||||
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
|
||||
has_selected_path,
|
||||
retype
|
||||
)]
|
||||
@@ -163,8 +165,11 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vecto
|
||||
}
|
||||
|
||||
/// One line of retyped glyphs.
|
||||
#[derive(Clone)]
|
||||
struct Line {
|
||||
pieces: Vec<NodeId>,
|
||||
/// Tracking in 1/1000 em, added after each character, spaces included.
|
||||
tracking: f64,
|
||||
/// What each piece matched, as `pieces`.
|
||||
matches: Vec<GlyphMatch>,
|
||||
/// Every glyph the first piece fits, while the line holds only it: the next glyph may tell
|
||||
@@ -204,16 +209,53 @@ impl Line {
|
||||
// Wrapped: type turned 180° has angles near +π and −π.
|
||||
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
&& across < size * 0.05
|
||||
&& (m.origin - self.end).dot(dir) > -size * 0.25
|
||||
// After the line's end, or, for type tracked tighter than that, still ahead of the
|
||||
// last glyph's start (by more than rounding); the layout check decides whether it fits.
|
||||
&& ((m.origin - self.end).dot(dir) > -size * 0.25
|
||||
|| self.matches.last().is_some_and(|last| (m.origin - last.origin).dot(dir) > size * 1e-3))
|
||||
}
|
||||
|
||||
fn size(&self) -> f64 {
|
||||
self.scale * self.face.units_per_em()
|
||||
}
|
||||
|
||||
/// The shapes of the one-contour glyphs that stand alone on this line: neither the glyph before
|
||||
/// nor the one after continues it by starting after the end of the glyph before it. A glyph
|
||||
/// that joined the line only through the tight-tracking test counts as alone. A line of three
|
||||
/// glyphs or more is type (its tracking can be read), so none of its glyphs is alone.
|
||||
fn lone_one_contour(&self) -> Vec<NodeId> {
|
||||
if self.matches.len() >= 3 {
|
||||
return vec![];
|
||||
}
|
||||
let dir = self.dir();
|
||||
let size = self.size();
|
||||
// Does glyph `k` start after the end of the glyph before it, less a quarter em?
|
||||
let after_previous = |k: usize| match (k.checked_sub(1).and_then(|j| self.matches.get(j)), self.matches.get(k)) {
|
||||
(Some(a), Some(b)) => (b.origin - (a.origin + dir * (a.face.advance(a.gid) * a.scale))).dot(dir) > -size * 0.25,
|
||||
_ => false,
|
||||
};
|
||||
let n = self.matches.len();
|
||||
(0..n)
|
||||
.filter(|&k| !after_previous(k) && !after_previous(k + 1))
|
||||
.filter_map(|k| self.matches.get(k).filter(|m| m.contours == 1).and_then(|_| self.pieces.get(k).copied()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The line's tracking in points.
|
||||
fn tracking_pt(&self) -> f64 {
|
||||
self.tracking * self.size() / 1000.0
|
||||
}
|
||||
|
||||
fn push(&mut self, id: NodeId, m: &GlyphMatch) {
|
||||
// A gap wider than half a space before the glyph is spaces the outlines left no shape for.
|
||||
// A gap, past the tracking, wider than half a space before the glyph is spaces the
|
||||
// outlines left no shape for. Each space takes the tracking too.
|
||||
let dir = self.dir();
|
||||
let gap = (m.origin - self.end).dot(dir);
|
||||
let space = space_advance(&self.face) * self.scale;
|
||||
if space > 0.0 && gap > space * 0.5 {
|
||||
let n = ((gap / space).round() as usize).clamp(1, 64);
|
||||
let gap = (m.origin - self.end).dot(dir) - self.tracking_pt();
|
||||
// Tracking tighter than a space's width gives each space a negative advance.
|
||||
let space = space_advance(&self.face) * self.scale + self.tracking_pt();
|
||||
let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 };
|
||||
if spaces.is_finite() && spaces > 0.5 {
|
||||
let n = (spaces.round() as usize).clamp(1, 64);
|
||||
self.text.extend(std::iter::repeat_n(' ', n));
|
||||
}
|
||||
self.text.push(m.ch);
|
||||
@@ -222,13 +264,49 @@ impl Line {
|
||||
self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale);
|
||||
}
|
||||
|
||||
/// The line of this one's glyphs `from..to`, with its group, paint and transparency.
|
||||
/// The line of this one's glyphs `from..to`, with its group, paint, transparency, tracking and
|
||||
/// the spaces between those glyphs.
|
||||
fn part(&self, from: usize, to: usize) -> Option<Line> {
|
||||
let mut text = String::new();
|
||||
let mut glyph = 0usize;
|
||||
for c in self.text.chars() {
|
||||
// The text after glyph `to - 1` is not read.
|
||||
if glyph >= to {
|
||||
break;
|
||||
}
|
||||
if c == ' ' {
|
||||
// Spaces before glyph `glyph`, after glyph `glyph - 1`.
|
||||
if glyph > from {
|
||||
text.push(c);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if glyph >= from {
|
||||
text.push(c);
|
||||
}
|
||||
glyph += 1;
|
||||
}
|
||||
if glyph != to || to > self.matches.len() {
|
||||
return self.respaced(from, to, self.tracking);
|
||||
}
|
||||
let mut l = self.respaced(from, to.min(from.saturating_add(1)), self.tracking)?;
|
||||
l.pieces = self.pieces.get(from..to)?.to_vec();
|
||||
l.matches = self.matches.get(from..to)?.to_vec();
|
||||
let last = l.matches.last()?;
|
||||
l.end = last.origin + l.dir() * (last.face.advance(last.gid) * last.scale);
|
||||
l.text = text;
|
||||
Some(l)
|
||||
}
|
||||
|
||||
/// The line of this one's glyphs `from..to` at `tracking`, with its group, paint and
|
||||
/// transparency, its spaces read again from the gaps at that tracking.
|
||||
fn respaced(&self, from: usize, to: usize, tracking: f64) -> Option<Line> {
|
||||
let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?);
|
||||
let (first, m) = (ids.first()?, ms.first()?);
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
let mut l = Line {
|
||||
pieces: vec![*first],
|
||||
tracking,
|
||||
matches: vec![m.clone()],
|
||||
first_cands: vec![],
|
||||
text: m.ch.to_string(),
|
||||
@@ -248,8 +326,8 @@ impl Line {
|
||||
Some(l)
|
||||
}
|
||||
|
||||
/// The point type that sets this line.
|
||||
fn text_object(&self, system_layout: bool) -> TextObject {
|
||||
/// The point type that sets this line, not yet laid out (for a layout check).
|
||||
fn probe(&self, system_layout: bool) -> TextObject {
|
||||
let style = CharStyle {
|
||||
font_family: self.face.family.clone(),
|
||||
font_style: self.face.style.clone(),
|
||||
@@ -258,6 +336,7 @@ impl Line {
|
||||
// Each outlined glyph was drawn on its own; a ligature would draw another shape.
|
||||
features: vec!["-liga".into()],
|
||||
size: self.scale * self.face.units_per_em(),
|
||||
tracking: self.tracking,
|
||||
fill: self.appearance.fill_paint(),
|
||||
stroke: self.appearance.stroke_paint(),
|
||||
stroke_width: self.appearance.stroke_width(),
|
||||
@@ -277,6 +356,12 @@ impl Line {
|
||||
}
|
||||
t.para = super::create::new_type_para();
|
||||
t.system_layout = system_layout;
|
||||
t
|
||||
}
|
||||
|
||||
/// The point type that sets this line, laid out and measured.
|
||||
fn text_object(&self, system_layout: bool) -> TextObject {
|
||||
let mut t = self.probe(system_layout);
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
t
|
||||
}
|
||||
@@ -285,27 +370,262 @@ impl Line {
|
||||
/// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(&self, t: &TextObject) -> Option<usize> {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
|
||||
let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01);
|
||||
for (k, m) in self.matches.iter().enumerate() {
|
||||
let Some(g) = drawn.next() else { return Some(k) };
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
|
||||
return Some(k);
|
||||
first_mismatch(t, &self.matches, self.size())
|
||||
}
|
||||
|
||||
/// Along the line, where its first glyph starts and its last glyph's advance ends, from
|
||||
/// `from` (the tracking after the last glyph left out).
|
||||
fn span_from(&self, from: Point) -> (f64, f64) {
|
||||
let dir = self.dir();
|
||||
let last = self.matches.last().map_or(self.end, |m| m.origin + dir * (m.face.advance(m.gid) * m.scale));
|
||||
((self.origin - from).dot(dir), (last - from).dot(dir))
|
||||
}
|
||||
|
||||
/// This line with the tracking its glyphs are spaced by, when it has at least three glyphs.
|
||||
/// The glyphs are laid out untracked and without spaces, so each gap's extra is how much
|
||||
/// further apart the outlines are than the font's advances and pair kerning set them; a gap
|
||||
/// read as word spaces is measured from the glyph's own advance instead, as no pair kerning
|
||||
/// crosses a space. The extra most gaps share (the lower median, so that the word spaces of a
|
||||
/// few gaps do not count) places the word spaces; the tracking is then the lower median, over
|
||||
/// the gaps, of each gap's extra less its spaces, per character. The upper median of the
|
||||
/// extras is tried next, for a line whose word spaces are its tighter gaps, and last the lower
|
||||
/// median less one space, halved, for a line most of whose gaps hold a word space. A tracking within
|
||||
/// 0.05 of a whole number is tried rounded to it first, then as measured. A tracked line is
|
||||
/// kept when its type draws the whole line in place, or more of it from its start than
|
||||
/// untracked type does. When untracked type with the spaces also draws the whole line, the line stays
|
||||
/// untracked if the tracking is under one unit or the tracked reading drops a gap untracked
|
||||
/// type reads as one space. The line also stays as it is when its tracking is 0 or outside
|
||||
/// -1000..10000, and when its tracking is negative and the line does not paint the same as one
|
||||
/// object ([`paints_as_one`]: its glyphs may overlap). Each of the nine layouts at most takes
|
||||
/// its characters, spaces included, from `budget` before it runs; without enough left, the
|
||||
/// line stays as it is, or becomes the best tracked reading laid out before the budget ran out.
|
||||
fn tracked(self, system_layout: bool, budget: &mut usize) -> Line {
|
||||
let size = self.size();
|
||||
let n = self.pieces.len();
|
||||
if n < 3 || size <= 0.0 {
|
||||
return self;
|
||||
}
|
||||
// Each layout takes its characters, spaces included, from `budget` before it runs.
|
||||
let mut take = |text: &str| match budget.checked_sub(text.chars().count()) {
|
||||
Some(left) => {
|
||||
*budget = left;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
if !take(&self.text) {
|
||||
return self;
|
||||
}
|
||||
let plain_miss = self.first_mismatch(&self.probe(system_layout));
|
||||
let dir = self.dir();
|
||||
// Where untracked type draws the glyphs of `text` (each layout dropped once read).
|
||||
let mut bare = self.clone();
|
||||
bare.tracking = 0.0;
|
||||
let mut origins = |text: String| -> Vec<Point> {
|
||||
bare.text = text;
|
||||
let t = bare.probe(system_layout);
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect()
|
||||
};
|
||||
// With no spaces.
|
||||
let joined: String = self.matches.iter().map(|m| m.ch).collect();
|
||||
if !take(&joined) {
|
||||
return self;
|
||||
}
|
||||
let drawn = origins(joined);
|
||||
if drawn.len() != n {
|
||||
return self;
|
||||
}
|
||||
// And with one space between each two glyphs (kerning against the space included).
|
||||
let spaced = self.matches.iter().map(|m| m.ch.to_string()).collect::<Vec<_>>().join(" ");
|
||||
if !take(&spaced) {
|
||||
return self;
|
||||
}
|
||||
let drawn_spaced = origins(spaced);
|
||||
// A font whose space has ink draws more glyphs: then the glyph's own advance stands in.
|
||||
let spaced_ok = drawn_spaced.len() == n;
|
||||
let space = space_advance(&self.face) * self.scale;
|
||||
// Each gap's extra over the joined pair, and over the pair with one space between them
|
||||
// plus a space (so the extra counts the spaces as the joined pair's extra counts none).
|
||||
let gaps: Vec<(f64, f64)> = self
|
||||
.matches
|
||||
.windows(2)
|
||||
.enumerate()
|
||||
.zip(drawn.windows(2))
|
||||
.filter_map(|((i, m), p)| match (m, p) {
|
||||
([a, b], [pa, pb]) => {
|
||||
let d = (b.origin - a.origin).dot(dir);
|
||||
let apart = match (spaced_ok, drawn_spaced.get(i), drawn_spaced.get(i + 1)) {
|
||||
(true, Some(qa), Some(qb)) => d - (*qb - *qa).dot(dir) + space,
|
||||
_ => d - a.face.advance(a.gid) * a.scale,
|
||||
};
|
||||
Some((d - (*pb - *pa).dot(dir), apart))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let extra: Vec<f64> = gaps.iter().map(|g| g.0).collect();
|
||||
// The spaces in each gap at a tracking of `tr` points: each space takes the tracking too,
|
||||
// and tracking tighter than a space's width gives it a negative advance. A gap reads as
|
||||
// spaces when they fit it better than the joined pair does.
|
||||
let spaces = |tr: f64| -> Vec<usize> {
|
||||
gaps.iter()
|
||||
.map(|(joined, apart)| {
|
||||
let step = space + tr;
|
||||
// Spaces with no advance: one space, which still breaks the pair's kerning.
|
||||
let s = if step.abs() > 1e-9 { (apart - tr) / step } else { 1.0 };
|
||||
if !s.is_finite() {
|
||||
return 0;
|
||||
}
|
||||
// At least one space: the space's own kerning can make it fit a narrower gap.
|
||||
let k = (s.round().max(1.0) as usize).clamp(1, 64);
|
||||
// Spaces only where they fit better by more than rounding (1/100,000 em).
|
||||
if (apart - tr - k as f64 * step).abs() + size * 1e-5 < (joined - tr).abs() { k } else { 0 }
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The tracking the gaps give when the word spaces are placed by `seed`.
|
||||
let measure = |seed: f64| -> Option<f64> {
|
||||
let per: Vec<f64> = gaps
|
||||
.iter()
|
||||
.zip(spaces(seed))
|
||||
.map(|((joined, apart), s)| if s == 0 { *joined } else { (apart - s as f64 * space) / (s + 1) as f64 })
|
||||
.collect();
|
||||
median(per, false).map(|g| g / size * 1000.0)
|
||||
};
|
||||
// The lower median of the extras places the word spaces first; the upper one second, for a
|
||||
// line whose word spaces are its tighter gaps (tracking tighter than a space).
|
||||
let lower = median(extra.clone(), false);
|
||||
// A line whose word gaps are most of its gaps has a space and two trackings in each extra
|
||||
// (tracking is added after the glyph and after the space): the seed then places the spaces
|
||||
// from the extra less one space, shared by the two. It goes last, so a reading that fits
|
||||
// without it is kept (an untracked "a b c" has no such tracking).
|
||||
// Where untracked type already draws the whole line, a space and a tracking of half its
|
||||
// advance less draw it too: that reading is not tried.
|
||||
let spaced_seed = lower.filter(|_| plain_miss.is_some()).map(|e| (e - space) / 2.0);
|
||||
let mut tries = vec![];
|
||||
for seed in [lower, median(extra, true), spaced_seed].into_iter().flatten() {
|
||||
let Some(measured) = measure(seed) else { continue };
|
||||
for t in [round_tracking(measured), measured] {
|
||||
if !tries.contains(&t) {
|
||||
tries.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ink the outlines did not have: the last glyph is where it went wrong.
|
||||
drawn.next().map(|_| self.matches.len().saturating_sub(1))
|
||||
// The spaces in each gap of the line as it is (the reading `plain_miss` checked).
|
||||
let mut plain_gaps = vec![];
|
||||
let mut run = 0usize;
|
||||
for (i, c) in self.text.chars().enumerate() {
|
||||
if c == ' ' {
|
||||
run += 1;
|
||||
} else {
|
||||
if i > 0 {
|
||||
plain_gaps.push(run);
|
||||
}
|
||||
run = 0;
|
||||
}
|
||||
}
|
||||
let mut best: Option<(usize, Line)> = None;
|
||||
for t in tries {
|
||||
if t == 0.0 || !TRACKING.contains(&t) {
|
||||
continue;
|
||||
}
|
||||
if t < 0.0 && !paints_as_one(&self) {
|
||||
return self;
|
||||
}
|
||||
let mut tracked = self.clone();
|
||||
tracked.tracking = t;
|
||||
tracked.text = String::new();
|
||||
let gaps = spaces(t * size / 1000.0);
|
||||
for (k, (m, s)) in self.matches.iter().zip(std::iter::once(0).chain(gaps.iter().copied())).enumerate() {
|
||||
if k > 0 {
|
||||
tracked.text.extend(std::iter::repeat_n(' ', s));
|
||||
}
|
||||
tracked.text.push(m.ch);
|
||||
}
|
||||
// A reading the budget cannot lay out is skipped; the next may be shorter.
|
||||
if !take(&tracked.text) {
|
||||
continue;
|
||||
}
|
||||
// When both draw the whole line (gaps as wide as whole spaces), the tracked reading is
|
||||
// kept unless it drops a gap that untracked type reads as one space: such a gap is a
|
||||
// word space ("a b c"), and the line keeps its spaces.
|
||||
let drops_a_word_space = plain_gaps.iter().zip(&gaps).any(|(plain, tracked)| *plain == 1 && *tracked == 0);
|
||||
match (tracked.first_mismatch(&tracked.probe(system_layout)), plain_miss) {
|
||||
// Under a unit of tracking, or a word space the tracked reading drops, where
|
||||
// untracked type draws the line: no tracking.
|
||||
(None, None) if t.abs() < 1.0 || drops_a_word_space => return self,
|
||||
(None, _) => return tracked,
|
||||
(Some(k), Some(p)) if k > p && best.as_ref().is_none_or(|(b, _)| k > *b) => best = Some((k, tracked)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
best.map_or(self, |(_, l)| l)
|
||||
}
|
||||
}
|
||||
|
||||
/// Does line `l` paint the same as one object as glyph by glyph where its glyphs overlap: opaque,
|
||||
/// Normal blend, a solid fill or none, and no stroke? One object composites its transparency and
|
||||
/// blend once, spans a gradient over all of it, and strokes after filling every glyph.
|
||||
fn paints_as_one(l: &Line) -> bool {
|
||||
l.opacity == 1.0
|
||||
&& l.blend == vectorcraft_color::BlendMode::Normal
|
||||
&& matches!(l.appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. })
|
||||
&& matches!(l.appearance.stroke_paint(), vectorcraft_color::Paint::None)
|
||||
}
|
||||
|
||||
/// The tracking Retype sets, in 1/1000 em.
|
||||
const TRACKING: std::ops::RangeInclusive<f64> = -1000.0..=10000.0;
|
||||
|
||||
/// The lower median of the finite values of `v`, or the upper one when `upper`; None for fewer
|
||||
/// than two.
|
||||
fn median(mut v: Vec<f64>, upper: bool) -> Option<f64> {
|
||||
v.retain(|x| x.is_finite());
|
||||
if v.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.get(if upper { v.len() / 2 } else { (v.len() - 1) / 2 }).copied()
|
||||
}
|
||||
|
||||
/// Tracking `t` rounded to a whole number when it is within 0.05 of one.
|
||||
fn round_tracking(t: f64) -> f64 {
|
||||
if (t - t.round()).abs() < 0.05 { t.round() } else { t }
|
||||
}
|
||||
|
||||
/// The first of `matches` that type `t` (at `size`) does not draw as the outlines did: another
|
||||
/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option<usize> {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
|
||||
let tol = (size * 0.01).max(0.01);
|
||||
for (k, m) in matches.iter().enumerate() {
|
||||
let Some(g) = drawn.next() else { return Some(k) };
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
|
||||
return Some(k);
|
||||
}
|
||||
}
|
||||
// Ink the outlines did not have: the last glyph is where it went wrong.
|
||||
drawn.next().map(|_| matches.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
/// `lines` checked against their own layout: a line splits where its type stops drawing the
|
||||
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
|
||||
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
|
||||
fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>) -> Vec<Line> {
|
||||
// Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines.
|
||||
let mut budget = lines.iter().map(|l| l.pieces.len()).sum::<usize>().saturating_mul(16).saturating_add(256);
|
||||
// Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot
|
||||
// leave glyphs unchecked; past it they keep no tracking. Each measure takes the glyphs to
|
||||
// rebuild the rest and the characters it lays out (see [`Line::tracked`]); the budget covers
|
||||
// one measure of each whole line, as `retype` gives the first, and the glyph checks' budget.
|
||||
// The glyphs measured again after splits are limited apart from it, at six times each rest's
|
||||
// glyphs from half as much again as the glyph checks' budget.
|
||||
let mut remeasured = budget.saturating_add(budget / 2);
|
||||
let mut track_budget =
|
||||
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(394))).fold(budget, usize::saturating_add);
|
||||
let mut todo: std::collections::VecDeque<Line> = lines.into();
|
||||
let mut out = vec![];
|
||||
while let Some(l) = todo.pop_front() {
|
||||
@@ -323,28 +643,58 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
|
||||
break;
|
||||
};
|
||||
budget = left;
|
||||
match part.first_mismatch(&part.text_object(system_layout)) {
|
||||
match part.first_mismatch(&part.probe(system_layout)) {
|
||||
// The whole line is drawn as it was: one object.
|
||||
None if e == n => {
|
||||
out.push(part);
|
||||
break;
|
||||
}
|
||||
None => w = w.saturating_mul(2),
|
||||
// The first glyph on its own may still be drawn as it was (a contextual form
|
||||
// changed it in the line); else it stays an outline. Checked again either way.
|
||||
Some(0) if n > 1 => {
|
||||
todo.extend_front_parts(&l, [(0, 1), (1, n)]);
|
||||
// Tracking that type does not set as the outlines are spaced: the line is
|
||||
// checked again without it.
|
||||
Some(k) if l.tracking != 0.0 && k < 2 => {
|
||||
match l.respaced(0, n, 0.0) {
|
||||
Some(p) => todo.push_front(p),
|
||||
None => unmatched.extend(l.pieces.iter().copied()),
|
||||
}
|
||||
break;
|
||||
}
|
||||
Some(0) => {
|
||||
// A single glyph its type cannot draw as it was stays an outline.
|
||||
Some(0) if n == 1 => {
|
||||
unmatched.extend(l.pieces.first().copied());
|
||||
break;
|
||||
}
|
||||
// The glyphs before the mismatch, then the rest, each checked as a line of its
|
||||
// own: the type before the mismatch may draw otherwise without what follows it (a
|
||||
// font can place a glyph by the glyph after it).
|
||||
// font can place a glyph by the glyph after it), and the first glyph on its own
|
||||
// may still be drawn as it was (a contextual form changed it in the line). The
|
||||
// rest takes the tracking its own glyphs are spaced by, while the budget for
|
||||
// measuring it lasts and when type draws its first glyph as it was, followed by the
|
||||
// next two (else that glyph splits off first, and the tracking is measured from the
|
||||
// next one); past it, an untracked line's rest keeps its text as it is.
|
||||
Some(k) => {
|
||||
todo.extend_front_parts(&l, [(0, k), (k, n)]);
|
||||
let k = k.max(1);
|
||||
// A measure takes at least six times the rest's glyphs from each budget.
|
||||
let measurable = n - k >= 3 && remeasured >= (n - k).saturating_mul(6) && track_budget >= (n - k).saturating_mul(6);
|
||||
let first_drawn = measurable && {
|
||||
budget = budget.saturating_sub(3);
|
||||
l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0))
|
||||
};
|
||||
let rest = if first_drawn {
|
||||
// Rebuilding the rest for the measure takes its glyphs from the budget.
|
||||
remeasured = remeasured.saturating_sub((n - k).saturating_mul(6));
|
||||
track_budget = track_budget.saturating_sub(n - k);
|
||||
l.respaced(k, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget))
|
||||
} else if l.tracking == 0.0 {
|
||||
l.part(k, n)
|
||||
} else {
|
||||
l.respaced(k, n, 0.0)
|
||||
};
|
||||
match rest {
|
||||
Some(r) => todo.push_front(r),
|
||||
None => unmatched.extend(l.pieces.get(k..).unwrap_or_default().iter().copied()),
|
||||
}
|
||||
todo.extend_front_parts(&l, [(0, k)]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -353,6 +703,290 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
|
||||
out
|
||||
}
|
||||
|
||||
/// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes
|
||||
/// of the area type on the layers Retype changes
|
||||
/// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type.
|
||||
const MAX_WRAP_WORK: usize = 2_000_000;
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn max_wrap_work() -> usize {
|
||||
MAX_WRAP_WORK
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// [`MAX_WRAP_WORK`], lowered by tests on their own thread.
|
||||
static WRAP_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_WRAP_WORK) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn max_wrap_work() -> usize {
|
||||
WRAP_LIMIT.with(|c| c.get())
|
||||
}
|
||||
|
||||
/// Lines farther apart than this many times their size do not join into one object.
|
||||
const MAX_LEADING: f64 = 3.0;
|
||||
|
||||
/// What Retype makes: one type object and the shapes it replaces.
|
||||
struct Made {
|
||||
t: TextObject,
|
||||
/// For area type, the point type that also draws the glyphs in place: the type kept when
|
||||
/// Text Wrap objects above it change the area type's layout.
|
||||
point: Option<TextObject>,
|
||||
/// The glyphs the type must draw, in order.
|
||||
matches: Vec<GlyphMatch>,
|
||||
pieces: Vec<NodeId>,
|
||||
text: String,
|
||||
face: Arc<vectorcraft_text::FontFace>,
|
||||
size: f64,
|
||||
tracking: f64,
|
||||
/// The leading set on the type: None for Auto or a single line.
|
||||
leading: Option<f64>,
|
||||
opacity: f32,
|
||||
blend: vectorcraft_color::BlendMode,
|
||||
}
|
||||
|
||||
impl Made {
|
||||
fn line(l: &Line, system_layout: bool) -> Made {
|
||||
Made {
|
||||
t: l.text_object(system_layout),
|
||||
point: None,
|
||||
matches: l.matches.clone(),
|
||||
pieces: l.pieces.clone(),
|
||||
text: l.text.clone(),
|
||||
face: l.face.clone(),
|
||||
size: l.size(),
|
||||
tracking: l.tracking,
|
||||
leading: None,
|
||||
opacity: l.opacity,
|
||||
blend: l.blend,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The alignments lines can share, in the order one is chosen: their starts, their ends, their
|
||||
/// centers.
|
||||
const ALIGNS: [vectorcraft_doc::Justify; 3] = [vectorcraft_doc::Justify::Left, vectorcraft_doc::Justify::Right, vectorcraft_doc::Justify::Center];
|
||||
|
||||
/// A run of lines that may become one object: lines after the first, each one leading further
|
||||
/// across, in the same group, paint, transparency, font, size, turn and tracking, lined up alike.
|
||||
struct Block {
|
||||
lines: Vec<Line>,
|
||||
/// The mean distance between baselines, from the first line's to the last line's.
|
||||
leading: f64,
|
||||
/// Which of [`ALIGNS`] every line so far shares.
|
||||
aligns: [bool; 3],
|
||||
/// The tracking of the first line that has one ([`Block::spaced`]).
|
||||
tracking: Option<f64>,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
fn new(l: Line) -> Block {
|
||||
let tracking = Block::spaced(&l).then_some(l.tracking);
|
||||
Block { lines: vec![l], leading: 0.0, aligns: [true; 3], tracking }
|
||||
}
|
||||
|
||||
/// Does line `l` have a tracking of its own? A line of fewer than three glyphs that kept no
|
||||
/// tracking has no gaps to measure it by ([`Line::tracked`]): it takes the block's.
|
||||
fn spaced(l: &Line) -> bool {
|
||||
l.pieces.len() >= 3 || l.tracking != 0.0
|
||||
}
|
||||
|
||||
/// Add `l` when it continues the block; `l` back when it does not. `follows` tells whether the
|
||||
/// shape `l` starts with comes right after the block's last shape, with nothing between them
|
||||
/// in paint order.
|
||||
fn take(&mut self, l: Line, follows: impl Fn(NodeId, NodeId) -> bool) -> Option<Line> {
|
||||
let (Some(first), Some(prev)) = (self.lines.first(), self.lines.last()) else { return Some(l) };
|
||||
let (Some(a), Some(b)) = (prev.pieces.last(), l.pieces.first()) else { return Some(l) };
|
||||
let size = first.size();
|
||||
let tol = (size * 0.01).max(0.01);
|
||||
let same = follows(*a, *b)
|
||||
&& l.parent == first.parent
|
||||
&& l.appearance == first.appearance
|
||||
&& l.opacity == first.opacity
|
||||
&& l.blend == first.blend
|
||||
&& l.face.id() == first.face.id()
|
||||
&& (l.scale - first.scale).abs() <= first.scale * 1e-4
|
||||
&& ((l.angle - first.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
// The lines' estimates may differ a little; the layout check decides.
|
||||
&& (!Block::spaced(&l) || self.tracking.is_none_or(|t| (l.tracking - t).abs() < 1.0))
|
||||
// Lines whose ink overlaps, or a gradient spanning them, would paint otherwise as one.
|
||||
&& paints_as_one(first);
|
||||
if !same {
|
||||
return Some(l);
|
||||
}
|
||||
// Across the lines, down from the first line's baseline.
|
||||
let across = Vec2::new(-first.angle.sin(), first.angle.cos());
|
||||
let down = (l.origin - first.origin).dot(across);
|
||||
let n = self.lines.len() as f64;
|
||||
// The mean distance between the baselines so far, which this line's must continue.
|
||||
let leading = if self.lines.len() == 1 { down } else { self.leading };
|
||||
// A quarter of the size is the least leading; the outlines' positions are rounded.
|
||||
if !(leading >= size * 0.25 * (1.0 - 1e-6) && leading <= size * MAX_LEADING) || (down - n * leading).abs() > tol {
|
||||
return Some(l);
|
||||
}
|
||||
let leading = down / n;
|
||||
let (s0, e0) = first.span_from(first.origin);
|
||||
let (s, e) = l.span_from(first.origin);
|
||||
let fits = [(s - s0).abs() <= tol, (e - e0).abs() <= tol, ((s + e) - (s0 + e0)).abs() * 0.5 <= tol];
|
||||
let aligns = [self.aligns[0] && fits[0], self.aligns[1] && fits[1], self.aligns[2] && fits[2]];
|
||||
if !aligns.contains(&true) {
|
||||
return Some(l);
|
||||
}
|
||||
self.leading = leading;
|
||||
self.aligns = aligns;
|
||||
if self.tracking.is_none() && Block::spaced(&l) {
|
||||
self.tracking = Some(l.tracking);
|
||||
}
|
||||
self.lines.push(l);
|
||||
None
|
||||
}
|
||||
|
||||
/// The block as one area type object when type draws every glyph in its place as area type,
|
||||
/// else as one point type object when that does. When neither does, the lines before the line
|
||||
/// of the first glyph the type moves are made again as a block, and the lines from that one on
|
||||
/// are joined again ([`blocks`]); the first line on its own stays one object. Area type whose
|
||||
/// frame would reach past [`crate::MAX_COORD`] stays point type, and point type whose bounds
|
||||
/// would stays one object per line. Each try takes six times the
|
||||
/// block's glyphs from `budget` (point and area type are each laid out, measured and checked);
|
||||
/// without enough left, each line is one object.
|
||||
fn made(self, system_layout: bool, budget: &mut usize) -> Vec<Made> {
|
||||
let single = |lines: &[Line]| lines.iter().map(|l| Made::line(l, system_layout)).collect::<Vec<_>>();
|
||||
let (Some(first), true) = (self.lines.first(), self.lines.len() > 1) else { return single(&self.lines) };
|
||||
let Some(justify) = ALIGNS.iter().zip(self.aligns).find(|(_, ok)| *ok).map(|(j, _)| *j) else { return single(&self.lines) };
|
||||
let glyphs = self.lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add);
|
||||
let Some(left) = budget.checked_sub(glyphs.saturating_mul(6)) else { return single(&self.lines) };
|
||||
*budget = left;
|
||||
let mut all = first.clone();
|
||||
all.tracking = self.tracking.unwrap_or(first.tracking);
|
||||
all.text = self.lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>().join("\n");
|
||||
let mut t = all.probe(system_layout);
|
||||
t.para.justify = justify;
|
||||
let size = first.size();
|
||||
let mut set_leading = None;
|
||||
if let Some(r) = t.runs.first_mut() {
|
||||
// The leading that puts the last baseline where the last line's is: Auto when Auto
|
||||
// does, else the mean distance between baselines, to a thousandth of a point (as
|
||||
// typed leading is) when that still puts the last baseline in place.
|
||||
let gaps = self.lines.len().saturating_sub(1) as f64;
|
||||
let across = Vec2::new(-first.angle.sin(), first.angle.cos());
|
||||
let span = self.lines.last().map_or(0.0, |l| (l.origin - first.origin).dot(across));
|
||||
if (t.para.effective_leading(&r.style) * gaps - span).abs() > size * 1e-4 {
|
||||
let exact = span / gaps;
|
||||
let rounded = (exact * 1000.0).round() / 1000.0;
|
||||
let leading = if ((rounded - exact) * gaps).abs() <= size * 1e-4 { rounded } else { exact };
|
||||
r.style.leading = Some(leading);
|
||||
set_leading = Some(leading);
|
||||
}
|
||||
}
|
||||
let matches: Vec<GlyphMatch> = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect();
|
||||
// Aligned at its end or center, point type starts its first line elsewhere: the type moves
|
||||
// so its first glyph is where the first outline is.
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) {
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
t.xf = kurbo::Affine::translate(m.origin - at) * t.xf;
|
||||
}
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
if let Some(k) = first_mismatch(&t, &matches, size) {
|
||||
// The line that holds glyph `k`.
|
||||
let mut seen = 0usize;
|
||||
let at = self.lines.iter().position(|l| {
|
||||
seen = seen.saturating_add(l.pieces.len());
|
||||
k < seen
|
||||
});
|
||||
let Block { mut lines, leading, aligns, .. } = self;
|
||||
let rest = lines.split_off(at.unwrap_or(0).clamp(1, lines.len()));
|
||||
let mut out = if lines.len() > 1 {
|
||||
let tracking = lines.iter().find(|l| Block::spaced(l)).map(|l| l.tracking);
|
||||
Block { lines, leading, aligns, tracking }.made(system_layout, budget)
|
||||
} else {
|
||||
single(&lines)
|
||||
};
|
||||
// The lines of the rest followed each other in the block.
|
||||
out.extend(blocks(rest, |_, _| true, system_layout, budget));
|
||||
return out;
|
||||
}
|
||||
// The edit is refused when an object's bounds reach past the coordinate limit. A turned
|
||||
// block's box can reach a corner that none of its lines does: the lines then stay apart.
|
||||
let in_range =
|
||||
|t: &TextObject| Node::new(NodeId(0), NodeKind::Text(Box::new(t.clone()))).geometric_bounds().is_none_or(crate::sanity::rect_in_range);
|
||||
if !in_range(&t) {
|
||||
return single(&self.lines);
|
||||
}
|
||||
let mut area = t.clone();
|
||||
super::typemenu::point_to_area(&mut area);
|
||||
let mut point = None;
|
||||
if in_range(&area) && first_mismatch(&area, &matches, size).is_none() {
|
||||
point = Some(std::mem::replace(&mut t, area));
|
||||
}
|
||||
vec![Made {
|
||||
t,
|
||||
point,
|
||||
matches,
|
||||
pieces: self.lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(),
|
||||
text: all.text,
|
||||
face: first.face.clone(),
|
||||
size,
|
||||
tracking: all.tracking,
|
||||
leading: set_leading,
|
||||
opacity: first.opacity,
|
||||
blend: first.blend,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
/// A line of two untracked glyphs has one gap, too few to measure a tracking by
|
||||
/// ([`Line::tracked`]). It is set at the tracking of the nearest tracked line of the same font,
|
||||
/// size and turn, so the layout check ([`verified`]) tries it as that line is set: the check falls
|
||||
/// back to the line untracked, and then splits it, when the pair is not spaced so. A pair that
|
||||
/// untracked type already draws in place keeps its text, and negative tracking goes only to a pair
|
||||
/// that paints the same as one object ([`paints_as_one`]).
|
||||
fn share_tracking(lines: &mut [Line], system_layout: bool) {
|
||||
for i in 0..lines.len() {
|
||||
let Some(l) = lines.get(i).filter(|l| l.pieces.len() == 2 && l.tracking == 0.0) else { continue };
|
||||
if l.first_mismatch(&l.probe(system_layout)).is_none() {
|
||||
continue;
|
||||
}
|
||||
let like = |o: &Line| {
|
||||
o.tracking != 0.0
|
||||
&& o.parent == l.parent
|
||||
&& o.face.id() == l.face.id()
|
||||
&& (o.scale - l.scale).abs() <= l.scale * 1e-4
|
||||
&& ((o.angle - l.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
};
|
||||
let nearest = lines.iter().enumerate().filter(|(_, o)| like(o)).min_by_key(|(j, _)| j.abs_diff(i)).map(|(_, o)| o.tracking);
|
||||
if let Some(p) = nearest.filter(|t| *t > 0.0 || paints_as_one(l)).and_then(|t| l.respaced(0, 2, t)) {
|
||||
lines[i] = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of
|
||||
/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after
|
||||
/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
|
||||
fn blocks(lines: Vec<Line>, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec<Made> {
|
||||
let mut out = vec![];
|
||||
let mut block: Option<Block> = None;
|
||||
for l in lines {
|
||||
let l = match block.as_mut() {
|
||||
Some(b) => match b.take(l, &follows) {
|
||||
None => continue,
|
||||
Some(l) => l,
|
||||
},
|
||||
None => l,
|
||||
};
|
||||
if let Some(b) = block.take() {
|
||||
out.extend(b.made(system_layout, budget));
|
||||
}
|
||||
block = Some(Block::new(l));
|
||||
}
|
||||
if let Some(b) = block {
|
||||
out.extend(b.made(system_layout, budget));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Puts parts of a line at the front of the work list, in order.
|
||||
trait FrontParts {
|
||||
fn extend_front_parts<const N: usize>(&mut self, l: &Line, ranges: [(usize, usize); N]);
|
||||
@@ -407,6 +1041,7 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
Line {
|
||||
pieces: vec![id],
|
||||
tracking: 0.0,
|
||||
matches: vec![m.clone()],
|
||||
first_cands: l.first_cands.clone(),
|
||||
text: m.ch.to_string(),
|
||||
@@ -428,6 +1063,7 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
Some(Line {
|
||||
pieces: vec![pc.id],
|
||||
tracking: 0.0,
|
||||
matches: vec![m.clone()],
|
||||
first_cands: cands.to_vec(),
|
||||
text: m.ch.to_string(),
|
||||
@@ -531,8 +1167,15 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is
|
||||
// what was asked for. Lone means alone on its baseline as the outlines lie, before the
|
||||
// layout check splits lines (tracking and manual kerning split them glyph by glyph).
|
||||
let lone_pieces: std::collections::HashSet<NodeId> =
|
||||
lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect();
|
||||
let lone_pieces: std::collections::HashSet<NodeId> = lines.iter().flat_map(Line::lone_one_contour).collect();
|
||||
// Each line's tracking is measured with nine layouts at most: the line as read (its
|
||||
// characters), its glyphs without and with one space between them (three times its
|
||||
// glyphs) and six tracked readings of at most 64 spaces in each gap (390 times its
|
||||
// glyphs), so every line has what its measure can take.
|
||||
let mut budget =
|
||||
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add);
|
||||
let mut lines: Vec<Line> = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect();
|
||||
share_tracking(&mut lines, system_layout);
|
||||
let mut lines = verified(lines, system_layout, &mut unmatched);
|
||||
if pieces.len() > 1 {
|
||||
lines.retain(|l| {
|
||||
@@ -543,20 +1186,29 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
!lone
|
||||
});
|
||||
}
|
||||
(lines, unmatched, truncated)
|
||||
let at: std::collections::HashMap<NodeId, usize> = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect();
|
||||
let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) {
|
||||
(Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier),
|
||||
_ => false,
|
||||
};
|
||||
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
|
||||
// for small blocks.
|
||||
let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256);
|
||||
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated)
|
||||
};
|
||||
if lines.is_empty() {
|
||||
return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len())));
|
||||
}
|
||||
let made = s.edit("Retype", |d, sel| {
|
||||
// The layers as they were, for the Text Wrap check below.
|
||||
let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone());
|
||||
let mut ids = vec![];
|
||||
let mut emptied = vec![];
|
||||
for l in &lines {
|
||||
let Some(first) = l.pieces.first() else { continue };
|
||||
let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?;
|
||||
let t = l.text_object(system_layout);
|
||||
let id = d.alloc_id();
|
||||
let mut node = Node::new(id, NodeKind::Text(Box::new(t)));
|
||||
let mut node = Node::new(id, NodeKind::Text(Box::new(l.t.clone())));
|
||||
// The glyphs' own transparency (the group's, kept, still applies over it).
|
||||
node.opacity = l.opacity;
|
||||
node.blend = l.blend;
|
||||
@@ -603,15 +1255,66 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Text Wrap objects above new area type flow it once the edit is done: area type they
|
||||
// would move a glyph of becomes the point type that draws it in place.
|
||||
if let Some(before) = &before {
|
||||
// Worked out on a copy, so the edit's own Text Wrap refresh still sees every other
|
||||
// area type whose wrap changes, and only on the layers this edit changed, as that
|
||||
// refresh is. The copy holds only the changed layers while the work is counted; past
|
||||
// the limit, the new area type is not flowed and all of it becomes its point type.
|
||||
let mut probe = d.clone();
|
||||
let all = std::mem::take(&mut probe.layers);
|
||||
probe.layers = all
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, layer)| {
|
||||
// As resolve_wrap tells an unchanged layer: the same layer at its index first.
|
||||
!(before.layers.get(*i).is_some_and(|b| Arc::ptr_eq(b, layer))
|
||||
|| before.layers.iter().any(|b| b.id == layer.id && Arc::ptr_eq(b, layer)))
|
||||
})
|
||||
.map(|(_, layer)| layer.clone())
|
||||
.collect();
|
||||
let units = vectorcraft_doc::text::wrap_copy_units(&probe);
|
||||
let flowed = units <= max_wrap_work();
|
||||
probe.layers = all;
|
||||
if flowed && units > 0 {
|
||||
vectorcraft_doc::text::resolve_wrap(Some(before), &mut probe);
|
||||
}
|
||||
// With nothing to copy, no area type on those layers has a wrap shape.
|
||||
for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) {
|
||||
let Some(point) = &l.point else { continue };
|
||||
let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue };
|
||||
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size).is_none()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
**t = point.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut keep: Vec<NodeId> = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect();
|
||||
keep.extend(&ids);
|
||||
sel.set(keep);
|
||||
Ok(ids)
|
||||
})?;
|
||||
let d = &s.doc()?.doc;
|
||||
let area =
|
||||
|id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }));
|
||||
Ok(json!({
|
||||
"ids": made.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"texts": lines.iter().map(|l| l.text.clone()).collect::<Vec<_>>(),
|
||||
"fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::<Vec<_>>(),
|
||||
"fonts": lines
|
||||
.iter()
|
||||
.zip(&made)
|
||||
.map(|(l, id)| json!({
|
||||
"family": l.face.family,
|
||||
"style": l.face.style,
|
||||
"size": l.size,
|
||||
"tracking": l.tracking,
|
||||
"leading": l.leading,
|
||||
"area": area(id),
|
||||
}))
|
||||
.collect::<Vec<_>>(),
|
||||
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"truncated": truncated,
|
||||
}))
|
||||
|
||||
@@ -477,10 +477,10 @@ fn tracked_one_contour_letters_still_become_type() {
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}");
|
||||
assert!(texts.len() > 1, "the tracking splits the line: {r}");
|
||||
assert_eq!(r["texts"], json!([text]), "evenly tracked, the line is one object: {r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]), "{r}");
|
||||
assert_eq!(text_of(&s, r["ids"][0].as_u64().unwrap()).first_style().tracking, 50.0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,8 +521,8 @@ fn timing_with_hundreds_of_cjk_outlines() {
|
||||
|
||||
#[test]
|
||||
fn a_long_tracked_line_is_checked_in_time() {
|
||||
// Tracking splits the line at every glyph: the layout check must not lay out the rest of the
|
||||
// line again after each split.
|
||||
// Even tracking is kept on the line; the layout check of a long line must not lay out the rest
|
||||
// of the line again after each window.
|
||||
let text = "abe".repeat(150);
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap();
|
||||
@@ -533,7 +533,706 @@ fn a_long_tracked_line_is_checked_in_time() {
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text);
|
||||
assert_eq!(texts, vec![text], "the whole line is one object: {r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_overlapping_lone_glyphs_beside_art_stay_outlines() {
|
||||
// Two M outlines start 0.3 em apart, closer than the first one's advance: a tight-tracking
|
||||
// line of two, which the layout check splits again. Each is still a lone one-contour glyph.
|
||||
let mut s = session();
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "M", "size": 30}));
|
||||
let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30}));
|
||||
let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap();
|
||||
// Nothing is left to retype: both stay outlines, as the lone bar beside art does.
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err();
|
||||
assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}");
|
||||
}
|
||||
|
||||
/// Where type `t` draws each glyph that has ink, in document space.
|
||||
fn glyph_places(t: &TextObject) -> Vec<kurbo::Point> {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * kurbo::Point::ORIGIN)).collect()
|
||||
}
|
||||
|
||||
/// Type made with `p` (and `setup` run on its id), outlined and retyped: the original type, and
|
||||
/// Retype's result.
|
||||
fn retyped(s: &mut Session, p: serde_json::Value, setup: &[serde_json::Value]) -> (TextObject, serde_json::Value) {
|
||||
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
|
||||
for q in setup {
|
||||
let mut q = q.clone();
|
||||
q["id"] = json!(id);
|
||||
s.execute("text.setRangeStyle", &q).unwrap();
|
||||
}
|
||||
let before = text_of(s, id);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
(before, s.execute("type.retype", &json!({})).unwrap())
|
||||
}
|
||||
|
||||
fn assert_same_places(a: &TextObject, b: &TextObject) {
|
||||
let (pa, pb) = (glyph_places(a), glyph_places(b));
|
||||
assert_eq!(pa.len(), pb.len());
|
||||
for (x, y) in pa.iter().zip(&pb) {
|
||||
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_lines_become_one_area_type_object() {
|
||||
let mut s = session();
|
||||
let text = "First line\nSecond one\nThird";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(true), "{r}");
|
||||
assert_eq!(r["fonts"][0]["leading"], json!(null), "Auto leading gives the lines' spacing: {r}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }));
|
||||
assert_eq!(t.plain_text(), text);
|
||||
assert_same_places(&before, &t);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_a_quarter_of_the_size_apart_join_and_closer_ones_do_not() {
|
||||
// At 20 pt, 5 pt is the least leading that joins lines.
|
||||
// 4.9999999 pt is 5 pt to the rounding of the outlines' positions.
|
||||
for (leading, objects) in [(5.0, 1), (4.9999999, 1), (4.9, 2)] {
|
||||
let mut s = session();
|
||||
let text = "One\nTwo";
|
||||
let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 20}), &[json!({"leading": leading})]);
|
||||
assert_eq!(r["texts"].as_array().unwrap().len(), objects, "{leading}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_two_glyph_line_takes_the_tracking_of_the_lines_around_it() {
|
||||
let mut s = session();
|
||||
let text = "MMM\nMM\nMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 50})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_keep_their_leading_and_alignment() {
|
||||
for justify in ["left", "center", "right"] {
|
||||
let mut s = session();
|
||||
let text = "Wide first line\nmid\nlast one";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 300, "y": 100, "text": text, "size": 20, "justify": justify}), &[json!({"leading": 31})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{justify}: {r}");
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 31.0, 1e-3), "{justify}: {r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(true), "{justify}: {r}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "{justify}");
|
||||
assert_eq!(t.para.justify, before.para.justify, "{justify}");
|
||||
assert_same_places(&before, &t);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_block_near_auto_leading_keeps_its_own_leading() {
|
||||
// 24.001 pt is Auto's 24 pt within a ten-thousandth of the size per line, but 250 lines
|
||||
// move the last one a quarter of a point.
|
||||
let mut s = session();
|
||||
let text = vec!["ab"; 250].join("\n");
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 24.001})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.001, 1e-4), "{}", r["fonts"][0]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_block_at_auto_leading_of_a_fractional_size_keeps_auto() {
|
||||
// Auto leading of 20.002 pt is 24.0024 pt, finer than the thousandth of a point the leading
|
||||
// between two lines is read to.
|
||||
let mut s = session();
|
||||
// Six hundred lines: read to a thousandth, each gap would be 0.0004 pt short, and the last
|
||||
// line 0.24 pt off.
|
||||
let text = vec!["ab"; 600].join("\n");
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20.002}), &[]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert_eq!(r["fonts"][0]["leading"], json!(null), "{}", r["fonts"][0]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_block_at_a_leading_finer_than_a_thousandth_keeps_it() {
|
||||
// 23.9996 pt read to a thousandth is 24 pt, Auto for 20 pt type: over 600 lines the last one
|
||||
// would be 0.24 pt off.
|
||||
let mut s = session();
|
||||
let text = vec!["ab"; 600].join("\n");
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 23.9996})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 23.9996, 1e-6), "{}", r["fonts"][0]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_whose_first_gap_is_a_little_off_stays_one_object() {
|
||||
// The second line moved up 0.004 pt: its gap read alone, carried over 100 lines, would put
|
||||
// the last one 0.4 pt off.
|
||||
let mut s = session();
|
||||
let text = ["ab"; 100].join("\n");
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 40, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "leading": 24.004})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let kids = children_of(&s, g);
|
||||
s.execute("select.set", &json!({"ids": kids[2..4]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 0, "dy": -0.004})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
|
||||
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.004, 1e-3), "{}", r["fonts"][0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_whose_frame_would_pass_the_coordinate_limit_stay_point_type() {
|
||||
let mut s = session();
|
||||
let text = "Wide line\nWide";
|
||||
let id = s.execute("text.create", &json!({"x": 3_999_000, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
let right = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x1;
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
// The ink ends 2 pt short of the limit; Convert To Area Type's slack would reach past it.
|
||||
s.execute("object.move", &json!({"dx": vectorcraft_doc::MAX_COORD - 2.0 - right, "dy": 0})).unwrap();
|
||||
let before = text_of(&s, id);
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(false), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_type_cannot_join_ends_the_block_there() {
|
||||
// The fourth line keeps a fraction of a unit of tracking that the others do not: joined, it
|
||||
// moves, so the lines before it stay one object and the lines after it join again.
|
||||
let mut s = session();
|
||||
let line = "M".repeat(40);
|
||||
let text = [line.as_str(); 6].join("\n");
|
||||
let start = 3 * 41;
|
||||
let (before, r) =
|
||||
retyped(&mut s, json!({"x": 20, "y": 40, "text": text, "size": 20}), &[json!({"start": start, "end": start + 40, "tracking": 0.6})]);
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.len(), 3, "{texts:?} {}", r["fonts"]);
|
||||
assert_eq!(texts.join("\n"), text);
|
||||
let places: Vec<kurbo::Point> = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect();
|
||||
let want = glyph_places(&before);
|
||||
assert_eq!(places.len(), want.len());
|
||||
for (x, y) in places.iter().zip(&want) {
|
||||
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The glyphs of the outline groups `others` moved to the end of group `g`, in order, and the
|
||||
/// emptied groups removed.
|
||||
fn into_one_group(s: &mut Session, g: u64, others: &[u64]) {
|
||||
s.edit("test", |d, _| {
|
||||
for o in others {
|
||||
let kids: Vec<_> = d.node(NodeId(*o)).unwrap().children().unwrap().to_vec();
|
||||
d.remove(NodeId(*o))?;
|
||||
for k in kids {
|
||||
let at = d.node(NodeId(g)).unwrap().children().unwrap().len();
|
||||
d.insert(Some(NodeId(g)), at, (*k).clone())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_that_do_not_stack_as_a_paragraph_stay_apart() {
|
||||
let mut s = session();
|
||||
// Far apart, then lined up at nothing.
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Top", "size": 20}));
|
||||
let b = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Far", "size": 20}));
|
||||
let c = outlined(&mut s, json!({"x": 75, "y": 324, "text": "Askew", "size": 20}));
|
||||
into_one_group(&mut s, a, &[b, c]);
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Top", "Far", "Askew"]), "{r}");
|
||||
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["area"] == json!(false)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_between_lines_keeps_them_apart() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB\nCD", "size": 30}));
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
s.edit("test", |d, _| {
|
||||
let n = d.node(NodeId(rect)).unwrap().clone();
|
||||
d.remove(NodeId(rect))?;
|
||||
d.insert(Some(NodeId(g)), 2, n)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["AB", "CD"]), "the rectangle is painted between the lines: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_lines_keep_their_tracking_and_spaces() {
|
||||
let mut s = session();
|
||||
let text = "SPACED OUT\nTITLE";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_line_takes_the_tracking_of_its_block() {
|
||||
// One glyph has no gap to measure tracking by: it joins the tracked lines.
|
||||
for text in ["TITLE\nB", "B\nTITLE", "TITLE\nB\nTITLE"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unevenly_tracked_type_still_becomes_type() {
|
||||
let mut s = session();
|
||||
// Less than half a space more after e: no gap can be read as a word space.
|
||||
let text = "abcdefgh";
|
||||
let (before, r) = retyped(
|
||||
&mut s,
|
||||
json!({"x": 40, "y": 100, "text": text, "size": 30}),
|
||||
&[json!({"start": 0, "end": 4, "tracking": 50}), json!({"start": 4, "end": 8, "tracking": 120})],
|
||||
);
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text, "{r}");
|
||||
assert!(texts.len() > 1, "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]), "{r}");
|
||||
// Each object's glyphs are where the outlines were.
|
||||
let places: Vec<kurbo::Point> = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect();
|
||||
let want = glyph_places(&before);
|
||||
assert_eq!(places.len(), want.len());
|
||||
for (x, y) in places.iter().zip(&want) {
|
||||
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
|
||||
}
|
||||
// The second half keeps its own tracking.
|
||||
assert_eq!(r["fonts"].as_array().unwrap().last().unwrap()["tracking"], json!(120.0), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tracked_line_keeps_its_tracking_and_spaces() {
|
||||
let mut s = session();
|
||||
let text = "SPACED OUT";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_line_tracked_two_spaces_wide_keeps_its_tracking() {
|
||||
// Read as it is, the line holds two spaces in each gap, which the tracking measure lays out too.
|
||||
let mut s = session();
|
||||
let text = "M".repeat(400);
|
||||
let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 400})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]);
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{}", r["fonts"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_tightly_tracked_line_keeps_its_word_spaces() {
|
||||
// Read as it is, the line holds no spaces; the tracked reading holds eight in each word gap.
|
||||
let mut s = session();
|
||||
let text = vec!["MMM"; 100].join(" ");
|
||||
let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": -180})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]);
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-180.0), "{}", r["fonts"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spaced_letters_keep_their_spaces_when_type_draws_them() {
|
||||
// Most gaps are word spaces: untracked type with the spaces draws every glyph in place.
|
||||
// Every gap one word space: tracking a space wide would draw them too, without the spaces.
|
||||
// L T J: without its spaces the pairs kern, which a measure of the gaps would read as more space.
|
||||
for text in ["a a a aa", "1 2 3", "a b c d", "x = y + 1", "L T J"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slight_tracking_without_spaces_is_kept() {
|
||||
// Tracking 3 moves the last glyph less than the layout check notices: both readings draw it.
|
||||
// A word space both readings keep does not cost the tracking either.
|
||||
for text in ["MMM", "M MM"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": 3})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(3.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines Retype reads from the outlines in group `g` (all in the face of its first glyph's
|
||||
/// first match), before their tracking is measured and their layout checked.
|
||||
fn lines_in(s: &Session, g: u64) -> Vec<super::Line> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]);
|
||||
super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces);
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
|
||||
let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted);
|
||||
let face = index.matches(&pieces[0].path)[0].face.id();
|
||||
let mut lines: Vec<super::Line> = vec![];
|
||||
for pc in &pieces {
|
||||
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
|
||||
if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) {
|
||||
lines.extend(super::new_line(pc, &cands));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() {
|
||||
// Glyph `bad` of a tracked line read as another glyph of its font, as when the line's type
|
||||
// would draw another form there: the glyphs after it are still one tracked object.
|
||||
for bad in [0usize, 1] {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let lines = lines_in(&s, g);
|
||||
assert_eq!(lines.len(), 1);
|
||||
let mut budget = 1000;
|
||||
let mut l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!(l.tracking, 300.0);
|
||||
let other = l.matches[bad].gid + 1;
|
||||
l.matches[bad].gid = other;
|
||||
let bad_id = l.pieces[bad];
|
||||
let mut unmatched = vec![];
|
||||
let out = super::verified(vec![l], false, &mut unmatched);
|
||||
assert_eq!(unmatched, vec![bad_id], "{bad}");
|
||||
let last = out.last().unwrap();
|
||||
assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
|
||||
assert_eq!(last.tracking, 300.0, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tracking_measure_counts_the_spaces_it_lays_out() {
|
||||
// Three glyphs ten spaces apart: a budget of six times the glyphs, short of the first
|
||||
// layout's 23 characters, lays nothing out.
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "a b c", "size": 30}));
|
||||
let lines = lines_in(&s, g);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!(lines[0].text.chars().filter(|c| *c == ' ').count() >= 20, "{}", lines[0].text);
|
||||
let mut budget = 3 * 6;
|
||||
let l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!((budget, l.tracking), (3 * 6, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tracking_measure_needs_only_the_layouts_it_runs() {
|
||||
// The line as read, without spaces, with one space per gap, then the tracked reading: a
|
||||
// budget of exactly those characters recovers the tracking.
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let lines = lines_in(&s, g);
|
||||
assert_eq!(lines.len(), 1);
|
||||
let mut budget = lines[0].text.chars().count() + 6 + 11 + 6;
|
||||
let l = lines.into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!((budget, l.tracking), (0, 300.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() {
|
||||
// Tracking 40 spaces wide: read untracked, the rest after the split holds 40 spaces per gap,
|
||||
// and its measure still has the budget to lay them out.
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "M".repeat(100), "size": 2})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 8000})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let mut budget = 100_000;
|
||||
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!(l.tracking, 8000.0);
|
||||
l.matches[0].gid += 1;
|
||||
let mut unmatched = vec![];
|
||||
let out = super::verified(vec![l], false, &mut unmatched);
|
||||
assert_eq!(unmatched.len(), 1);
|
||||
let last = out.last().unwrap();
|
||||
assert_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() {
|
||||
// A long tracked line whose first five glyphs are read as other glyphs: the rest is still one
|
||||
// tracked object.
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(100), "size": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let mut budget = 1000;
|
||||
let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget);
|
||||
assert_eq!(l.tracking, 300.0);
|
||||
for m in l.matches.iter_mut().take(5) {
|
||||
m.gid += 1;
|
||||
}
|
||||
let mut unmatched = vec![];
|
||||
let out = super::verified(vec![l], false, &mut unmatched);
|
||||
assert_eq!(unmatched.len(), 5);
|
||||
let last = out.last().unwrap();
|
||||
assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tightly_tracked_type_keeps_its_tracking() {
|
||||
// Tracking tighter than a space: the space moves the next glyph back.
|
||||
// M MM: of its two gaps, the word space is the tighter, and the lower median.
|
||||
// M M MM: most gaps hold a word space, so the tightest extras alone seed a tracking that
|
||||
// splits the last glyph.
|
||||
for text in ["MMMM", "MMMM MM", "M MM", "MM M", "M M MM"] {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -300})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-300.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kerned_pairs_in_tight_tracking_are_not_read_as_spaces() {
|
||||
// Tracking -250 gives a space a negative advance; the pair kerning of T and a is no space.
|
||||
let mut s = session();
|
||||
let text = "MMMTaMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_space_between_kerned_letters_is_read_as_a_space() {
|
||||
// T and a kern when they touch; with a space between them they do not.
|
||||
let mut s = session();
|
||||
let text = "MMMT aMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
// Tracking that cancels the space's advance: the space still stops the pair kerning.
|
||||
let mut s = session();
|
||||
let text = "MMMT aMMM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -200})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-200.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
// Tracking that nearly cancels it: the space still moves the glyphs after it a little.
|
||||
let mut s = session();
|
||||
let text = "MMMM MM";
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -199.5})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), -199.5, 1e-3), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
// A word space a little narrower than its tracking makes it (the word after it moved left by
|
||||
// less than the layout check notices): one space still fits better than the kerned pair.
|
||||
for (tracking, dx) in [(-190, -0.18), (-193, -0.24)] {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMc aMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let kids = children_of(&s, g);
|
||||
assert_eq!(kids.len(), 8);
|
||||
s.execute("select.set", &json!({"ids": kids[4..]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["MMMc aMMM"]), "{tracking}: {r}");
|
||||
}
|
||||
// A space that kerns with the letter after it.
|
||||
let mut s = session();
|
||||
let text = "MMMd TMMM";
|
||||
let p = json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Serif 4", "style": "Regular"});
|
||||
let (before, r) = retyped(&mut s, p, &[json!({"tracking": -217})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-217.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untracked_word_is_not_read_as_spaced_letters_in_tight_tracking() {
|
||||
// Letters, each followed by a space, at tracking of minus half a space, sit where the word's
|
||||
// letters do.
|
||||
let mut s = session();
|
||||
let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "Third", "size": 24}), &[]);
|
||||
assert_eq!(r["texts"], json!(["Third"]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_barely_ahead_of_each_other_stay_one_line() {
|
||||
let mut s = session();
|
||||
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "MMMM", "size": 30}), &[json!({"tracking": -700})]);
|
||||
assert_eq!(r["texts"], json!(["MMMM"]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(-700.0), "{r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracking_near_a_whole_number_is_kept_as_measured_when_rounding_moves_glyphs() {
|
||||
let mut s = session();
|
||||
let text = "i".repeat(400);
|
||||
let (before, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 50.04})]);
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), 50.04, 1e-3), "{}", r["fonts"]);
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "tracking": -300})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let kids = children_of(&s, g);
|
||||
s.edit("test", |d, _| {
|
||||
for k in &kids {
|
||||
d.node_mut(NodeId(*k)).unwrap().opacity = 0.5;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
// Each glyph composites on its own over the one it overlaps, as the outlines did.
|
||||
assert_eq!(r["texts"], json!(["M", "M", "M", "M"]), "{r}");
|
||||
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["tracking"] == json!(0.0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translucent_gradient_or_stroked_lines_stay_apart() {
|
||||
for case in ["opacity", "blend", "gradient", "stroke"] {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "One\nTwo", "size": 30}));
|
||||
let kids = children_of(&s, g);
|
||||
match case {
|
||||
"gradient" => {
|
||||
let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
s.execute("paint.setFill", &json!({"gradient": gradient, "ids": kids})).unwrap();
|
||||
}
|
||||
"stroke" => {
|
||||
s.execute("paint.setStroke", &json!({"color": "#ff0000", "ids": kids})).unwrap();
|
||||
}
|
||||
_ => {
|
||||
s.edit("test", |d, _| {
|
||||
for k in &kids {
|
||||
let n = d.node_mut(NodeId(*k)).unwrap();
|
||||
if case == "opacity" {
|
||||
n.opacity = 0.5;
|
||||
} else {
|
||||
n.blend = vectorcraft_color::BlendMode::Multiply;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["One", "Two"]), "{case}: one object would composite or fill the lines as one: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_stay_point_type_past_the_text_wrap_limit_of_their_layer() {
|
||||
// A Text Wrap object above the lines that moves no glyph, on their layer or on another one,
|
||||
// with the limit lowered to nothing: only on their layer does it count.
|
||||
for same_layer in [true, false] {
|
||||
let mut s = session();
|
||||
let text = "First line\nSecond one";
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap();
|
||||
let before = text_of(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
if !same_layer {
|
||||
// Area type below the Text Wrap object on the other layer: work there, none on this one.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let other = s.execute("text.create", &json!({"x": 450, "y": 300, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("type.convertToAreaType", &json!({"ids": [other]})).unwrap();
|
||||
}
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 330, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
super::WRAP_LIMIT.with(|c| c.set(0));
|
||||
let r = s.execute("type.retype", &json!({}));
|
||||
super::WRAP_LIMIT.with(|c| c.set(super::MAX_WRAP_WORK));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(!same_layer), "{same_layer}: {r}");
|
||||
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_subpaths_of_a_text_wrap_object_count_as_wrap_work() {
|
||||
// Each one is copied into the wrap shapes of the area type below it.
|
||||
let mut s = session();
|
||||
let t = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Area", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("type.convertToAreaType", &json!({"ids": [t]})).unwrap();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
|
||||
let base = vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc);
|
||||
let file_work = vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc);
|
||||
s.edit("test", |d, _| {
|
||||
if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(rect)).unwrap().kind {
|
||||
for _ in 0..100 {
|
||||
path.subpaths.push(vectorcraft_geom::SubPath::new(vec![], true));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc) >= base + 100);
|
||||
// The count file import and the `.ai` editing copy use stays anchors and shapes only.
|
||||
assert_eq!(vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc), file_work);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_under_a_text_wrap_object_stay_point_type() {
|
||||
let mut s = session();
|
||||
let text = "First line\nSecond one";
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap();
|
||||
let before = text_of(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
// Above the outlines, over the end of both lines: area type would wrap round it.
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 90, "y": 70, "width": 60, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!([text]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["area"], json!(false), "{r}");
|
||||
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Point));
|
||||
assert_same_places(&before, &t);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_geom::PathData;
|
||||
use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::appearance::{ItemTarget, edit_items, item_target};
|
||||
use super::paint::{live_paint_parts, live_paint_parts_skipped, painted};
|
||||
use super::paint::{live_paint_covered, live_paint_parts_skipped, painted};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
|
||||
use crate::DocState;
|
||||
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
|
||||
@@ -250,10 +250,15 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if item == ItemTarget::Top {
|
||||
own_stroke_or_leaves(s, p)?
|
||||
} else {
|
||||
item.targets(s, p)?
|
||||
item.targets_for(s, p, false)?
|
||||
};
|
||||
// A Live Paint group without edges was still selected or given: the options do not go to new art.
|
||||
let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty();
|
||||
let live_paint = !bucket
|
||||
&& if item == ItemTarget::Top {
|
||||
!live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty()
|
||||
} else {
|
||||
!super::appearance::contents_skipped(s, p, false)?.is_empty()
|
||||
};
|
||||
let new_art = bucket || (no_targets(&ids, p) && !live_paint);
|
||||
let given = !ids.is_empty() || live_paint;
|
||||
// The art of a graph design in a series keeps the design's stroke.
|
||||
@@ -445,7 +450,7 @@ impl Session {
|
||||
/// selection's stroke.
|
||||
pub fn shown_stroke(&self) -> Option<StrokeLayer> {
|
||||
let st = self.active()?;
|
||||
if self.tool_id() == super::paint::LIVE_PAINT_BUCKET {
|
||||
if self.bucket_paints() {
|
||||
return Some(self.new_art_stroke());
|
||||
}
|
||||
if let Some(part) = st.selected_symbol_part() {
|
||||
@@ -453,12 +458,15 @@ impl Session {
|
||||
}
|
||||
let Some(first) = st.selection.objects.first() else { return Some(self.new_art_stroke()) };
|
||||
let first = st.doc.node(*first)?;
|
||||
// Only an active Appearance row is shown here: it is a row of the first selected object.
|
||||
if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) {
|
||||
return first.appearance.stroke_at(Some(i)).cloned();
|
||||
}
|
||||
// A Live Paint group without edges shows the next selected object's stroke; any other object
|
||||
// without a painted object shows none.
|
||||
for id in &st.selection.objects {
|
||||
// without a painted object shows none. A face or edge selected with its Live Paint group counts
|
||||
// with the group, wherever it is in the selection.
|
||||
let covered = live_paint_covered(&st.doc, &st.selection.objects);
|
||||
for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, true, &mut nodes);
|
||||
@@ -532,7 +540,7 @@ impl DocState {
|
||||
} else {
|
||||
let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
|
||||
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
|
||||
let covered: std::collections::HashSet<vectorcraft_doc::NodeId> = selected.iter().flat_map(|n| live_paint_parts(n)).collect();
|
||||
let covered = live_paint_covered(&self.doc, &self.selection.objects);
|
||||
for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
|
||||
painted(n, true, true, &mut nodes);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches};
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
|
||||
use super::fileio::{create_dir, extension, read_file, write_file, write_new_file};
|
||||
use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file};
|
||||
use super::menucmds::squash;
|
||||
use super::package::free_name;
|
||||
use super::patternlib;
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document's graph designs are offered by Object › Graph › Column… and Marker… (graph.column, graph.marker and graph.design take the library's id) until the app quits. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own), unless it has graph designs, which then load with no swatches. A file larger than 256 MB is refused before it is read → {library: id, name, count, graphDesigns: the document's graph designs (0 for a library file)}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
@@ -92,6 +92,45 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The graph designs of the documents Other Library… loaded (`swatch.library.load`), which the
|
||||
/// Graph Column and Graph Marker dialogs offer besides the document's own; not saved.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DesignLibraries {
|
||||
libs: Vec<DesignLibrary>,
|
||||
}
|
||||
|
||||
/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DesignLibrary {
|
||||
/// The id `swatch.library.load` gave the swatch library. A User Defined copy of it
|
||||
/// (`swatch.library.copyToUser`) holds the swatches alone, so the designs stay under this id.
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// The designs and the resources their art uses.
|
||||
pub doc: Arc<vectorcraft_doc::Document>,
|
||||
}
|
||||
|
||||
impl DesignLibraries {
|
||||
/// The libraries, in the order they were loaded.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &DesignLibrary> {
|
||||
self.libs.iter()
|
||||
}
|
||||
|
||||
/// The library loaded as swatch library `id`.
|
||||
pub fn get(&self, id: &str) -> Option<&DesignLibrary> {
|
||||
self.libs.iter().find(|l| l.id == id)
|
||||
}
|
||||
|
||||
/// Keep `doc`'s graph designs as library `id` named `name`, in place of the ones loaded as `id`
|
||||
/// before; with no designs, `id` no longer has any.
|
||||
fn set(&mut self, id: &str, name: &str, doc: Option<vectorcraft_doc::Document>) {
|
||||
self.libs.retain(|l| l.id != id);
|
||||
if let Some(doc) = doc {
|
||||
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The libraries beyond the built-in ones: User Defined (the library files in the user library
|
||||
/// folder, as last scanned) and loaded ones (`swatch.library.load`). Graphic style libraries use
|
||||
/// the same with [`vectorcraft_doc::StyleLibrary`] ([`super::stylelib`]).
|
||||
@@ -354,12 +393,32 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
/// or a file with the same extension and bytes as one there, is that User Defined library;
|
||||
/// others are listed as loaded until the app quits.
|
||||
pub(crate) fn load(&mut self, p: &Value, cmd: &str, parse: impl FnOnce(&[u8], &str) -> Result<L>) -> Result<(LibraryInfo, Arc<L>)> {
|
||||
self.load_within(p, cmd, None, parse)
|
||||
}
|
||||
|
||||
/// [`Self::load`], with a file at `path` read up to `max` bytes and refused when it is longer.
|
||||
pub(crate) fn load_within(
|
||||
&mut self,
|
||||
p: &Value,
|
||||
cmd: &str,
|
||||
max: Option<usize>,
|
||||
parse: impl FnOnce(&[u8], &str) -> Result<L>,
|
||||
) -> Result<(LibraryInfo, Arc<L>)> {
|
||||
let path = text_param(p, "path", cmd)?;
|
||||
let data = text_param(p, "data", cmd)?;
|
||||
let data_base64 = text_param(p, "dataBase64", cmd)?;
|
||||
let name = text_param(p, "name", cmd)?;
|
||||
let bytes = match (path, data, data_base64) {
|
||||
(Some(path), ..) => read_file(path)?,
|
||||
(Some(path), ..) => match max {
|
||||
Some(max) => {
|
||||
let bytes = read_file_head(path, max.saturating_add(1))?;
|
||||
if bytes.len() > max {
|
||||
return Err(bad(cmd, too_big_message(max)));
|
||||
}
|
||||
bytes
|
||||
}
|
||||
None => read_file(path)?,
|
||||
},
|
||||
(None, Some(text), _) => text.as_bytes().to_vec(),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad dataBase64"))?,
|
||||
_ => return Err(bad(cmd, "give `path`, `data` or `dataBase64`")),
|
||||
@@ -777,12 +836,40 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The error for a library file larger than `max` bytes.
|
||||
fn too_big_message(max: usize) -> String {
|
||||
format!("the file is larger than {} MB", max >> 20)
|
||||
}
|
||||
|
||||
/// Whether the library `p` gives (`path`, `data` or `dataBase64`) is larger than `max` bytes,
|
||||
/// checked before the file is read, copied or decoded.
|
||||
pub(crate) fn library_too_big(p: &Value, cmd: &str, max: usize) -> Result<bool> {
|
||||
Ok(match text_param(p, "path", cmd)? {
|
||||
Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64),
|
||||
None => match text_param(p, "data", cmd)? {
|
||||
Some(text) => text.len() > max,
|
||||
// Base64 holds 3 bytes in every 4 characters (padding and white space hold none).
|
||||
None => {
|
||||
text_param(p, "dataBase64", cmd)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.load";
|
||||
let max = super::place::document::MAX_FILE;
|
||||
if library_too_big(p, C, max)? {
|
||||
return Err(bad(C, too_big_message(max)));
|
||||
}
|
||||
let mut designs = None;
|
||||
// The document a library with pattern swatches was read from, which holds their patterns.
|
||||
let mut patterns = None;
|
||||
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library.
|
||||
// The file is read no further than the limit, so a file that grew since it was checked is
|
||||
// refused too.
|
||||
let (info, lib) = s.swatch_libraries.load_within(p, C, Some(max), |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library and whose graph
|
||||
// designs the Graph Column and Graph Marker dialogs offer.
|
||||
if palette_io::sniff_bytes(bytes) {
|
||||
return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e));
|
||||
}
|
||||
@@ -792,10 +879,17 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches.
|
||||
let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc);
|
||||
let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
|
||||
let mut lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
|
||||
let doc_designs = super::clipboard::resources::graph_design_library(&loaded.doc);
|
||||
if defaults || lib.is_empty() {
|
||||
return Err(bad(C, format!("`{file}` has no swatches of its own")));
|
||||
// A document with graph designs loads for them, with no swatches.
|
||||
if doc_designs.is_none() {
|
||||
return Err(bad(C, format!("`{file}` has no swatches of its own")));
|
||||
}
|
||||
lib.swatches.clear();
|
||||
lib.groups.clear();
|
||||
}
|
||||
designs = doc_designs;
|
||||
if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) {
|
||||
patterns = Some(Arc::new(loaded.doc));
|
||||
}
|
||||
@@ -804,7 +898,9 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if info.category == "loaded" {
|
||||
s.swatch_libraries.set_pattern_doc(&info.id, patterns);
|
||||
}
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
let count = designs.as_ref().map_or(0, |d| d.graph_designs.len());
|
||||
s.graph_design_libraries.set(&info.id, &info.name, designs);
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len(), "graphDesigns": count}))
|
||||
}
|
||||
|
||||
/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new
|
||||
|
||||
@@ -424,6 +424,19 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec<Sy
|
||||
}
|
||||
}
|
||||
|
||||
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects after
|
||||
/// its art changed from `old` outside symbol editing (a graph in it drawn again): a change to an
|
||||
/// object that is no longer there is dropped ([`follow_objects`]).
|
||||
pub(crate) fn follow_art_change(d: &mut Document, name: &str, old: &Arc<Node>) {
|
||||
let Some(new) = d.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()) else { return };
|
||||
let parts = |art: &Arc<Node>| match (&art.kind, art.children()) {
|
||||
(NodeKind::Group { .. }, Some(ch)) => (ch.to_vec(), true),
|
||||
_ => (vec![art.clone()], false),
|
||||
};
|
||||
let (old, new) = (parts(old), parts(&new));
|
||||
follow_objects(d, name, (&old.0, old.1), (&new.0, new.1));
|
||||
}
|
||||
|
||||
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects
|
||||
/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art
|
||||
/// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the
|
||||
|
||||
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Type Path Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, except at an open end of the path; independent and symmetric cannot both be true; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
|
||||
has_doc,
|
||||
set_path_handle
|
||||
),
|
||||
@@ -1449,6 +1449,10 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in");
|
||||
let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
|
||||
let independent = switch_or(p, "independent", false, C)?;
|
||||
let symmetric = switch_or(p, "symmetric", false, C)?;
|
||||
if symmetric && independent {
|
||||
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
|
||||
}
|
||||
let node = s.doc()?.doc.node(id);
|
||||
let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. }));
|
||||
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
|
||||
@@ -1461,7 +1465,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let within = |t: &TextObject| {
|
||||
t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD))
|
||||
};
|
||||
if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) {
|
||||
if !(t.set_path_handle_with_symmetry((si, ai), out, pos, independent, symmetric) && within(t)) {
|
||||
t.kind = before;
|
||||
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
|
||||
}
|
||||
|
||||
@@ -634,34 +634,40 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !matches!(t.kind, TextKind::Point) {
|
||||
continue;
|
||||
}
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
// The frame is worked out in line space, where the lines are; vertical type turns it
|
||||
// into text space with the lines.
|
||||
let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() };
|
||||
let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds);
|
||||
// Across, the frame spans the lines as they are aligned: from their starts to their ends
|
||||
// without the tracking after their last characters (`LineInfo::trailing`), not to the
|
||||
// ink, which tracking can pull past an advance. Area type aligns them alike.
|
||||
let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing)));
|
||||
if x0.is_finite() && x1.is_finite() && x0 <= x1 {
|
||||
(b.x0, b.x1) = (x0, x1);
|
||||
}
|
||||
// Line breaking counts that tracking: the slack holds the most of it.
|
||||
let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max);
|
||||
let size = t.first_style().size;
|
||||
// A little slack on the right so the text doesn't rewrap.
|
||||
let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0);
|
||||
let slack = size * 0.5 + trailing;
|
||||
let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack);
|
||||
let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(frame) };
|
||||
refresh_bounds(t);
|
||||
point_to_area(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
/// Point type `t` turned into area type in a frame around its lines, with a little slack where its
|
||||
/// alignment leaves room, so the text stays where it is and does not rewrap.
|
||||
pub(super) fn point_to_area(t: &mut TextObject) {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
// The frame is worked out in line space, where the lines are; vertical type turns it
|
||||
// into text space with the lines.
|
||||
let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() };
|
||||
let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds);
|
||||
// Across, the frame spans the lines as they are aligned: from their starts to their ends
|
||||
// without the tracking after their last characters (`LineInfo::trailing`), not to the
|
||||
// ink, which tracking can pull past an advance. Area type aligns them alike.
|
||||
let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing)));
|
||||
if x0.is_finite() && x1.is_finite() && x0 <= x1 {
|
||||
(b.x0, b.x1) = (x0, x1);
|
||||
}
|
||||
// Line breaking counts that tracking: the slack holds the most of it.
|
||||
let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max);
|
||||
let size = t.first_style().size;
|
||||
// A little slack on the right so the text doesn't rewrap.
|
||||
let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0);
|
||||
let slack = size * 0.5 + trailing;
|
||||
let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack);
|
||||
let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(frame) };
|
||||
refresh_bounds(t);
|
||||
}
|
||||
|
||||
/// How `slack` added to point type's lines in a frame is shared before and after them: where the
|
||||
/// alignment leaves room, so the text doesn't move or rewrap.
|
||||
fn slack_sides(justify: Justify, rtl: bool, slack: f64) -> (f64, f64) {
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Free Distort",
|
||||
[],
|
||||
None,
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
|
||||
has_doc,
|
||||
distort
|
||||
),
|
||||
@@ -86,6 +86,15 @@ impl Projective {
|
||||
Self { m: [a, b, p0.x, d, e, p0.y, g, h], src, pre: bx.to_doc().inverse() }
|
||||
}
|
||||
|
||||
/// Whether `p` maps in front of the warp's horizon, on the side the box's own corners are.
|
||||
fn in_front(&self, p: Point) -> bool {
|
||||
let [.., g, h] = self.m;
|
||||
let p = self.pre * p;
|
||||
let u = if self.src.width().abs() > 1e-12 { (p.x - self.src.x0) / self.src.width() } else { 0.0 };
|
||||
let v = if self.src.height().abs() > 1e-12 { (p.y - self.src.y0) / self.src.height() } else { 0.0 };
|
||||
g * u + h * v + 1.0 > 1e-9
|
||||
}
|
||||
|
||||
pub fn apply(&self, p: Point) -> Point {
|
||||
let [a, b, c, d, e, f, g, h] = self.m;
|
||||
let p = self.pre * p;
|
||||
@@ -138,6 +147,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
// A clip group is bounded by its clip path.
|
||||
NodeKind::Group { children, clip: true } => warp_children(children, pr, |i| i == 0),
|
||||
NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => warp_children(children, pr, |i| i >= skip),
|
||||
// An image's corners follow the warp exactly ([`Node::set_image_corners`]); [`distort`]
|
||||
// has checked that they stay convex.
|
||||
NodeKind::Image(_) => {
|
||||
let b = n.geometric_bounds();
|
||||
if let Some(q) = n.image_corners() {
|
||||
let _ = n.set_image_corners(q.map(|p| pr.apply(p)));
|
||||
}
|
||||
b
|
||||
}
|
||||
_ => {
|
||||
// No editable points: the affine approximation (which maps the gradients too).
|
||||
let b = n.geometric_bounds();
|
||||
@@ -157,6 +175,21 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
before
|
||||
}
|
||||
|
||||
/// Whether the warp from `src` to `q` ([`Projective::from_box`]) takes the corners of `src` to `q`,
|
||||
/// within a millionth of `q`'s shortest side plus the rounding error of coordinates as far from `q`'s
|
||||
/// first corner as the others. The warp is solved and measured with `src` and `q` moved to the
|
||||
/// origin, so coordinates far from it do not widen the allowance.
|
||||
fn reaches_corners(src: OrientedBox, q: [Point; 4]) -> bool {
|
||||
let origin = q[0].to_vec2();
|
||||
let q = q.map(|p| p - origin);
|
||||
let src = OrientedBox { rect: src.rect - src.rect.origin().to_vec2(), ..src };
|
||||
let pr = Projective::from_box(src, q);
|
||||
let side = (0..4).map(|i| q[i].distance(q[(i + 1) % 4])).fold(f64::INFINITY, f64::min);
|
||||
let far = q.iter().map(|p| p.x.abs().max(p.y.abs())).fold(0.0, f64::max);
|
||||
let tol = side * 1e-6 + far * 1e-12;
|
||||
side.is_finite() && side > 0.0 && src.corners().iter().zip(q).all(|(c, want)| pr.apply(*c).distance(want) <= tol)
|
||||
}
|
||||
|
||||
/// Warps each of `children` and returns the union of the pre-warp bounds of those `counts` picks
|
||||
/// by index.
|
||||
fn warp_children(children: &mut [Arc<Node>], pr: &Projective, counts: impl Fn(usize) -> bool) -> Option<Rect> {
|
||||
@@ -166,6 +199,76 @@ fn warp_children(children: &mut [Arc<Node>], pr: &Projective, counts: impl Fn(us
|
||||
})
|
||||
}
|
||||
|
||||
/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`]
|
||||
/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with
|
||||
/// why.
|
||||
fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> {
|
||||
if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) {
|
||||
if !q.iter().all(|p| pr.in_front(*p)) {
|
||||
return Some((n.id, Unwarpable::Horizon));
|
||||
}
|
||||
if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) {
|
||||
return Some((
|
||||
n.id,
|
||||
match e {
|
||||
vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex,
|
||||
vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr))
|
||||
}
|
||||
|
||||
/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity
|
||||
/// masks).
|
||||
fn first_image(n: &Node) -> Option<vectorcraft_doc::NodeId> {
|
||||
if matches!(n.kind, NodeKind::Image(_)) {
|
||||
return Some(n.id);
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(first_image)
|
||||
}
|
||||
|
||||
/// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups
|
||||
/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other
|
||||
/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole.
|
||||
fn warped_parts(n: &Node) -> Vec<&Node> {
|
||||
let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. });
|
||||
let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_));
|
||||
let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c);
|
||||
let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art);
|
||||
children.chain(mask).collect()
|
||||
}
|
||||
|
||||
/// The error of `command` on image `id`, which is distorted (Perspective Distort or Free Distort)
|
||||
/// in a way the command cannot keep.
|
||||
pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId) -> EngineError {
|
||||
bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0))
|
||||
}
|
||||
|
||||
/// Why an image cannot follow the corners of a distort.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Unwarpable {
|
||||
/// Its corners would fold over, meet or fall on one line.
|
||||
NotConvex,
|
||||
/// A corner would cross the warp's horizon.
|
||||
Horizon,
|
||||
/// Its corners would be too close together for a perspective map to place them.
|
||||
TooNarrow,
|
||||
}
|
||||
|
||||
/// The error of `object.distort` when image `id` cannot follow its corners.
|
||||
fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError {
|
||||
const C: &str = "object.distort";
|
||||
match why {
|
||||
Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
|
||||
Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
|
||||
Unwarpable::TooNarrow => {
|
||||
bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn distort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.distort";
|
||||
// All four corners or nothing, each exactly [x, y]: nothing malformed is left out.
|
||||
@@ -208,6 +311,26 @@ fn distort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(ids_json);
|
||||
}
|
||||
let pr = Projective::from_box(src, [tl, tr, br, bl]);
|
||||
// An image's corners follow the handles exactly, so they must stay a convex shape: nothing
|
||||
// changes when one would not.
|
||||
let doc = &s.doc()?.doc;
|
||||
// Corners that do not make a convex shape give no perspective map (the warp falls back to an
|
||||
// affine one), so an image cannot follow them.
|
||||
if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err()
|
||||
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
|
||||
{
|
||||
return Err(unwarpable_error(id, Unwarpable::NotConvex));
|
||||
}
|
||||
// Corners so close together that the map falls back to an affine one: the box's corners do
|
||||
// not reach the handles, so an image cannot follow them either.
|
||||
if !reaches_corners(src, [tl, tr, br, bl])
|
||||
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
|
||||
{
|
||||
return Err(unwarpable_error(id, Unwarpable::TooNarrow));
|
||||
}
|
||||
if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) {
|
||||
return Err(unwarpable_error(id, why));
|
||||
}
|
||||
s.edit("Free Distort", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
@@ -233,6 +356,7 @@ pub struct FillAttrs {
|
||||
|
||||
impl FillAttrs {
|
||||
pub const ALL: Self = Self { color: true, transparency: true, overprint: true };
|
||||
pub const NONE: Self = Self { color: false, transparency: false, overprint: false };
|
||||
}
|
||||
|
||||
impl Default for FillAttrs {
|
||||
@@ -260,6 +384,8 @@ pub struct StrokeAttrs {
|
||||
|
||||
impl StrokeAttrs {
|
||||
pub const ALL: Self = Self { color: true, transparency: true, overprint: true, weight: true, cap: true, join: true, miter: true, dash: true };
|
||||
pub const NONE: Self =
|
||||
Self { color: false, transparency: false, overprint: false, weight: false, cap: false, join: false, miter: false, dash: false };
|
||||
}
|
||||
|
||||
impl Default for StrokeAttrs {
|
||||
|
||||
@@ -74,6 +74,10 @@ pub struct Session {
|
||||
/// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes
|
||||
/// back as it was at the release ([`Session::pointer`]).
|
||||
pub(crate) lender: Option<Box<dyn Tool>>,
|
||||
/// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the
|
||||
/// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the
|
||||
/// colors the bucket paints with ([`Session::bucket_paints`]).
|
||||
pub(crate) back_to_bucket: bool,
|
||||
/// Pointer and key input that came while the tool computed an edit on another thread, each with
|
||||
/// its number and view, made in order once the edit is applied.
|
||||
held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>,
|
||||
@@ -149,6 +153,9 @@ pub struct Session {
|
||||
pub(crate) pending_paint: Option<Paint>,
|
||||
/// User Defined and loaded swatch libraries (Window → Swatch Libraries); not saved.
|
||||
pub swatch_libraries: cmd::swatchlib::Libraries,
|
||||
/// The graph designs of the documents loaded as swatch libraries (Window → Swatch Libraries →
|
||||
/// Other Library…), for the Graph Column and Graph Marker dialogs; not saved.
|
||||
pub graph_design_libraries: cmd::swatchlib::DesignLibraries,
|
||||
/// The selected freeform gradient point (`paint.freeform.selectPoint`) and whose gradient it
|
||||
/// was selected on: read it with [`Session::selected_freeform_point`].
|
||||
pub(crate) freeform_point: Option<(usize, cmd::gradient::StopOwner)>,
|
||||
@@ -160,6 +167,8 @@ pub struct Session {
|
||||
pub brush_libraries: cmd::brushlib::Libraries,
|
||||
/// The custom arrowheads of the arrowheads file (`stroke.arrowheads.*`); none without one.
|
||||
pub arrowheads: cmd::arrowheads::Arrowheads,
|
||||
/// The custom bevels of the bevels file (`threeD.bevels.*`); none without one.
|
||||
pub bevels: cmd::bevels::Bevels,
|
||||
/// The id each loaded library outside a request's read roots has been shown under, by its own id
|
||||
/// ([`cmd::swatchlib::concealed_library_ids`]), kept for the session.
|
||||
shown_library_ids: std::sync::Mutex<std::collections::BTreeMap<String, String>>,
|
||||
@@ -329,6 +338,9 @@ pub struct Session {
|
||||
/// The id and persistent options of the tool when the press under way began, which a dropped
|
||||
/// press puts back ([`Session::drop_tool_press`]).
|
||||
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
|
||||
/// An option of the active tool was set during the press under way, which stored all of its
|
||||
/// options, so a dropped press stores the options it puts back.
|
||||
pub(crate) press_options_stored: bool,
|
||||
/// The engine saves the selection and active layer before a Type press and restores them if it drops.
|
||||
pub(crate) press_type_selection: Option<(Selection, Option<NodeId>)>,
|
||||
/// The freeform gradient point selected once the tool took the press under way, which a
|
||||
|
||||
@@ -283,6 +283,11 @@ pub struct Prefs {
|
||||
pub low_res_proxy_eps: bool,
|
||||
pub anti_aliased_bitmaps: bool,
|
||||
pub update_links: String,
|
||||
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
|
||||
/// becomes when the open or place does not say (`text`: editable type in the file's fonts;
|
||||
/// `outlines`: the glyph outlines the file draws). The Import PDF dialog starts from it and
|
||||
/// keeps the choice it confirms.
|
||||
pub pdf_text_as: String,
|
||||
// Clipboard Handling
|
||||
pub copy_as_svg: bool,
|
||||
pub copy_as_pdf: bool,
|
||||
@@ -589,6 +594,7 @@ impl Default for Prefs {
|
||||
low_res_proxy_eps: false,
|
||||
anti_aliased_bitmaps: false,
|
||||
update_links: s("askWhenModified"),
|
||||
pdf_text_as: s("text"),
|
||||
copy_as_svg: true,
|
||||
copy_as_pdf: false,
|
||||
copy_aicb: false,
|
||||
|
||||
@@ -55,6 +55,7 @@ impl Session {
|
||||
histories_seen: None,
|
||||
tool: vectorcraft_tools::create("selection"),
|
||||
lender: None,
|
||||
back_to_bucket: false,
|
||||
held_input: Default::default(),
|
||||
input_count: 0,
|
||||
edit_started_by: None,
|
||||
@@ -84,11 +85,13 @@ impl Session {
|
||||
recent_colors: vec![],
|
||||
pending_paint: None,
|
||||
swatch_libraries: Default::default(),
|
||||
graph_design_libraries: Default::default(),
|
||||
freeform_point: None,
|
||||
style_libraries: Default::default(),
|
||||
symbol_libraries: Default::default(),
|
||||
brush_libraries: Default::default(),
|
||||
arrowheads: Default::default(),
|
||||
bevels: Default::default(),
|
||||
shown_library_ids: Default::default(),
|
||||
libraries: Default::default(),
|
||||
pdf_preset_dir: None,
|
||||
@@ -137,6 +140,7 @@ impl Session {
|
||||
plane_widget_press: false,
|
||||
pointer_held: false,
|
||||
press_options: None,
|
||||
press_options_stored: false,
|
||||
press_type_selection: None,
|
||||
press_point: None,
|
||||
ruler_guide: None,
|
||||
|
||||
@@ -323,7 +323,7 @@ impl Session {
|
||||
}
|
||||
// While the Live Paint Bucket is active, paint previews change only the bucket's colors, so
|
||||
// each preview starts from the colors the interaction began with.
|
||||
let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET;
|
||||
let bucket = self.bucket_paints();
|
||||
let (paint, restore_paint) = {
|
||||
let menu = self.menu.clone();
|
||||
let st = self.doc_mut()?;
|
||||
@@ -485,7 +485,7 @@ impl Session {
|
||||
self.pending_paint = None;
|
||||
// While the Live Paint Bucket is active, a previewed color is the bucket's color, which the
|
||||
// cancel puts back as well.
|
||||
let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET;
|
||||
let bucket = self.bucket_paints();
|
||||
if let Some(paint) = self
|
||||
.active()
|
||||
.and_then(|st| st.interaction.as_ref())
|
||||
|
||||
Loaded 100 of 296 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user